Creating Address Labels

The following example takes an XML file representing a collection of mailing address labels and formats it as a multi-page PDF document with an arbitrary number of rows and columns. The space between columns and rows can be adjusted to accommodate different styles of label stock. This example uses the XML::Simple module to parse the input XML file. (See Chapter 7 for an example using the Sablotron XML parser.)

The example in this section writes the resulting PDF file to STDOUT. When the stringify( ) method is called, each object is translated into a string of PDF code along with the cross-reference table, headers, and trailers.

#!/usr/bin/perl -w
#
# Use the PDF::API2 module to generate columns of
# text for printing names and addresses on labels.

use strict;

use PDF::API2;      # Used to generate the PDF output
use XML::Simple;    # Used to parse the XML input

my %font = ( );      # A hash holding plain and bold font styles
my ($rows, $columns) = (11,3);      # Size of each label is calculated
my ($hspace, $vspace) = (6, 0);   # Space between columns and rows
my ($tmargin, $bmargin,            # The margins of the page
    $lmargin, $rmargin) = (36, 36, 36, 36);
my ($width, $height) = (612, 792); # Dimensions of page
my $print_grid_lines = 1;          # If true, print grid lines

# Calculate the width and height of each label

my $colwidth = ($width-$lmargin-$rmargin-
                ($columns-1)*$hspace)/$columns;
my $rowheight = ($height-$tmargin-$bmargin-
                 ($rows-1)*$vspace)/$rows;

First create a new top-level PDF object. ...

Get Perl Graphics Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.