#!/usr/bin/perl
#
# PDF merge starter:
# Merge pages from multiple PDF documents (including annotations)
# bookmarks) will be dropped.
#
# Required software: PDFlib+PDI or PDFlib Personalization Server (PPS)
# Required data: PDF documents

use PDFlib::PDFlib;
use strict;

# This is where the data files are. Adjust as necessary.
my $searchpath = "../data";

# By default annotations are also imported. In some cases this
# requires the Noto fonts for creating annotation appearance streams.
#
my $fontpath = "../../resource/font";

my $outfilename = "starter_pdfmerge.pdf";

my @pdffiles = (
    "markup_annotations.pdf",
    "pCOS-datasheet.pdf"
);

eval {
    my $p = new PDFlib::PDFlib;

    # This means we must check return values of load_font() etc.
    $p->set_option("errorpolicy=return");

    $p->set_option("SearchPath={{" . $searchpath ."}}");
    $p->set_option("SearchPath={{" . $fontpath ."}}");

    if ($p->begin_document($outfilename, "") == -1) {
        die("Error: " . $p->get_errmsg());
    }

    $p->set_info("Creator", "PDFlib starter sample");
    $p->set_info("Title", "starter_pdfmerge");

    foreach my $pdffile (@pdffiles) { 
    # Open the input PDF
    my $indoc = $p->open_pdi_document($pdffile, "");
    if ($indoc == -1) {
        printf("Error: %s\n", $p->get_errmsg());
        next;
    }

    my $endpage = $p->pcos_get_number($indoc, "length:pages");

    # Loop over all pages of the input document
    for (my $pageno = 1; $pageno <= $endpage; $pageno++) {
        my $page = $p->open_pdi_page($indoc, $pageno, "");

        if ($page == -1) {
        printf("Error: %s\n", $p->get_errmsg());
        next;
        }
        # Dummy $page size; will be adjusted later
        $p->begin_page_ext(10, 10, "");

        # Create a bookmark with the file name
        if ($pageno == 1) {
        $p->create_bookmark($pdffile, "");
        }

        # Place the imported $page on the output $page, and
        # adjust the $page size. If the page contains annotations
        # these are also imported.

        
        $p->fit_pdi_page($page, 0, 0, "adjustpage");
        $p->close_pdi_page($page);

        $p->end_page_ext("");
    }
    $p->close_pdi_document($indoc);
    }

    $p->end_document("");

};

if ($@) {
    die("$0: PDFlib Exception occurred:\n$@");
}
