#!/usr/bin/perl
# $Id: quickreference.pl,v 1.30 2009/11/23 15:33:25 rjs Exp $
#
# PDFlib+PDI client: mini imposition demo
#

use PDFlib::PDFlib 8.0;
use strict;

my $infile = "reference.pdf";
# This is where font/image/PDF input files live. Adjust as necessary.
my $searchpath = "../data";
my $maxrow = 2;
my $maxcol = 2;
my $width = 500.0;
my $height = 770.0;
my $endpage = 0 ;

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

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

    $p->set_parameter("SearchPath", $searchpath);

    # This line is required to avoid problems on Japanese systems
    $p->set_parameter("hypertextencoding", "winansi");

    if ($p->begin_document("quickreference.pdf", "") == -1) {
	die("Error: %s\n", $p->get_errmsg());
    }

    $p->set_info("Creator", "quickreference.pl");
    $p->set_info("Author", "Thomas Merz");
    $p->set_info("Title", "mini imposition demo (Perl)");

    my $manual = $p->open_pdi_document($infile, "");
    if ($manual == -1) {
	die("Error: %s\n", $p->get_errmsg());
    }

    my $row = 0;
    my $col = 0;

    $p->set_parameter("topdown", "true");

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

    for (my $pageno = 1; $pageno <= $endpage; $pageno++) {
	if ($row == 0 && $col == 0) {
	    $p->begin_page_ext($width, $height, "");
	    my $font = $p->load_font("Helvetica-Bold", "winansi", "");
	    $p->setfont($font, 18);
	    $p->set_text_pos(24, 24);
	    $p->show("PDFlib Quick Reference");
	}

	my $page = $p->open_pdi_page($manual, $pageno, "");

	if ($page == -1) {
	    die("Error: %s\n", $p->get_errmsg());
	}

	$p->fit_pdi_page($page, $width/$maxcol*$col, ($row + 1)
		* $height/$maxrow, "scale ". 1/$maxrow);
	$p->close_pdi_page($page);

	$col++;
	if ($col == $maxcol) {
	    $col = 0;
	    $row++;
	}
	if ($row == $maxrow) {
	    $row = 0;
	    $p->end_page_ext("");
	}
    }

    # finish the last partial page
    if ($row != 0 || $col != 0) {
	$p->end_page_ext("");
    }

    $p->end_document("");
    $p->close_pdi_document($manual);
};

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