#!/usr/bin/python
# $Id: chartab.py,v 1.13 2009/04/14 15:36:54 rjs Exp $
#
# PDFlib client: hello character table in Python
#

from sys import exc_info
from traceback import print_tb
from PDFlib.PDFlib import *

# change these as required
fontname = "LuciduxSans-Oblique"

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

# list of encodings to use
encoding = ["iso8859-1", "iso8859-2", "iso8859-15"]

# whether or not to embed the font
embed = ""
# embed = "not "
embedding = "embedding"
# embedding = ""

ENCODINGS       = 3
FONTSIZE        = 16
TOP             = 700
LEFT            = 50
YINCR           = 2*FONTSIZE
XINCR           = 2*FONTSIZE

# create a new PDFlib object
p = PDFlib()

try:
    # This means we must check return values of load_font() etc.
    p.set_parameter("errorpolicy", "return")

    p.set_parameter("SearchPath", searchpath)

    # open new PDF file
    if p.begin_document("chartab.pdf", "destination {type fitwindow page 1}") == -1:
        raise PDFlibException("Error: " + p.get_errmsg())

    p.set_info("Creator", "chartab.py")
    p.set_info("Author", "Thomas Merz")
    p.set_info("Title", "Character table (Python)")

    # loop over all encodings
    for page in range(0, ENCODINGS, 1):
        p.begin_page_ext(595, 842, "")

        # print the heading and generate the bookmark
        font = p.load_font("Helvetica", "unicode", "")
        if font == -1:
            raise PDFlibException("Error: " + p.get_errmsg())

        p.setfont(font, FONTSIZE)
        buf = fontname + " (" + encoding[page] + ") " + embed + "embedded"

        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 row in range(0, 16, 1):
            buf = "x" + repr(row)
            p.show_xy(buf, LEFT + row*XINCR, TOP + YINCR)

            buf = "x" + repr(row)
            p.show_xy(buf, LEFT - XINCR, TOP - row * YINCR)

        # print the character table
        font = p.load_font(fontname, encoding[page], embedding)
        if font == -1:
            raise PDFlibException("Error: " + p.get_errmsg())

        p.setfont(font, FONTSIZE)

        y = TOP
        x = LEFT

        for row in range(0, 16, 1):
            for col in range(0, 16, 1):
                val = (16*row + col)
                if val != 0:
		    # for python 3 use
		    # buf = chr(val)
                    buf = unichr(val)
                    p.show_xy(buf, x, y)
                x += XINCR
            x = LEFT
            y -= YINCR

        p.end_page_ext("")

    p.end_document("")

except PDFlibException:
    print("PDFlib exception occurred:\n[%d] %s: %s" %
	((p.get_errnum()), p.get_apiname(),  p.get_errmsg()))
    print_tb(exc_info()[2])

except Exception:
    print("Exception occurred: %s" % (exc_info()[0]))
    print_tb(exc_info()[2])

finally:
    p.delete()
