#!/usr/bin/perl
# $Id: businesscard.pl,v 1.28 2009/11/23 15:33:25 rjs Exp $
#
# PDFlib client: block processing example in C
#

use PDFlib::PDFlib 8.0;
use strict;

my $infile = "boilerplate.pdf";
# This is where font/image/PDF input files live. Adjust as necessary.
#
# Note that this directory must also contain the LuciduxSans font outline
# and metrics files.
#
my $searchpath = "../data";

my %data = (   "name"			=> "Victor Kraxi",
	    "business.title"		=> "Chief Paper Officer",
	    "business.address.line1" 	=> "17, Aviation Road",
	    "business.address.city"	=> "Paperfield",
	    "business.telephone.voice"	=> "phone +1 234 567-89",
	    "business.telephone.fax"	=> "fax +1 234 567-98",
	    "business.email"		=> "victor\@kraxi.com",
	    "business.homepage"		=> "www.kraxi.com"
	);

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

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

    # Set the search path for fonts and PDF files
    $p->set_parameter("SearchPath", $searchpath);

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

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

    $p->set_info("Creator", "businesscard.pl");
    $p->set_info("Author", "Thomas Merz");
    $p->set_info("Title", "PDFlib block processing sample (Perl)");

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

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

    $p->begin_page_ext(20, 20, "");		# dummy page size

    # This will adjust the page size to the block container's size.
    $p->fit_pdi_page($page, 0, 0, "adjustpage");

    # Fill all text blocks with dynamic data
    foreach my $elem(keys %data){
	if ($p->fill_textblock($page, $elem, $data{$elem},
            "embedding encoding=winansi") == -1) {
	    printf ("Warning: %s\n", $p->get_errmsg());
	}
    }

    $p->end_page_ext("");
    $p->close_pdi_page($page);

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

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