#!/usr/bin/perl
# $Id: chartab.pl,v 1.23 2009/11/23 15:33:25 rjs Exp $
#
# PDFlib client: hello example in Perl
#

use PDFlib::PDFlib 8.0;
use strict;

# change these as required
my $fontname = "LuciduxSans-Oblique";

# This is where font/image/PDF input files live. Adjust as necessary.
my $searchpath = "../data";

# list of encodings to use
my @encodings = ( "iso8859-1", "iso8859-2", "iso8859-15" );

# whether or not to embed the font
my $embed = 1;

use constant "FONTSIZE" => 	16;
use constant "TOP" =>		700;
use constant "LEFT" => 		50;
use constant "YINCR" => 	2*FONTSIZE;
use constant "XINCR" =>		2*FONTSIZE;

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("chartab.pdf",
	    "destination {type fitwindow page 1}") == -1) {
	die("Error: %s\n", $p->get_errmsg());
    }

    $p->set_info("Creator", "chartab.pl");
    $p->set_info("Author", "Thomas Merz");
    $p->set_info("Title", "Character table (Perl)");

    # loop over all encodings
    for (my $page = 0; $page <= $#encodings; $page++) {
	$p->begin_page_ext(595, 842, "");

	# print the heading and generate the bookmark
	my $font = $p->load_font("Helvetica", "winansi", "");
	if ($font == -1) {
	    die("Error: %s\n", $p->get_errmsg());
	}
	$p->setfont($font, FONTSIZE);
	my $buf = sprintf("%s (%s) %sembedded",
	    $fontname, $encodings[$page], $embed ? "" : "not ");

	$p->show_xy($buf, LEFT - XINCR, TOP + 3 * YINCR);
	$p->create_bookmark($buf, "");

	# print the row and column captions
	$p->setfont($font, 2 * FONTSIZE/3);

	for (my $row = 0; $row < 16; $row++) {
	    $buf = sprintf("x%X", $row);
	    $p->show_xy($buf, LEFT + $row*XINCR, TOP + YINCR);

	    $buf = sprintf("%Xx", $row);
	    $p->show_xy($buf, LEFT - XINCR, TOP - $row * YINCR);
	}

	# print the character table
	$font = $p->load_font($fontname, $encodings[$page],
	    $embed ? "embedding": "");
	if ($font == -1) {
	    die("Error: %s\n", $p->get_errmsg());
	}
	$p->setfont($font, FONTSIZE);

	my $y = TOP;
	my $x = LEFT;

	for (my $row = 0; $row < 16; $row++) {
	    for (my $col = 0; $col < 16; $col++) {
		$buf = sprintf("%c", 16*$row + $col);
		$p->show_xy($buf, $x, $y);
		$x += XINCR;
	    }
	    $x = LEFT;
	    $y -= YINCR;
	}

	$p->end_page_ext("");
    }

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

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