Friday, March 6, 2009

Merge/Combine two pdf pages into a single pdf page (Perl)

I needed to be able to add markup to an existing pdf file. In particular, I have a template and need to add a barcode programmatically. However, I am working mostly in Python and had already written the code to generate my barcode with placement, and wanted to just overlay that onto my existing pdf template.

With the template pdf:

And the barcode pdf:

I was aiming for:

First, I attempted to do this with the pyPdf library.

from pyPdf import PdfFileWriter, PdfFileReader
barcodepdf = PdfFileReader(file("barcode.pdf", "rb"))
templatepdf = PdfFileReader(file("freecar.pdf", "rb"))
output = PdfFileWriter()
barcodePage = barcodepdf.getPage(0)
templatePage = templatepdf.getPage(0)


outputStream = file("output.pdf", "wb")

This works in my samples, but I encountered problems with my application template: my i and E characters were turned invisible. Maybe a font problem?

Here's what I was looking at:

I decided to go with the Perl PDF::API2 library. It properly handled my files and gave me the output I was looking for--with no missing characters.

# in1.pdf in2.pdf out.pdf
# Combine the first page from
# two input pdf files
# into a single page in a
# new pdf file.

use PDF::API2;
$input1pdf = PDF::API2->open($ARGV[0]);
$input2pdf = PDF::API2->open($ARGV[1]);
$outputpdf = PDF::API2->new;

# Bring in the template page
$page = $outputpdf->importpage($input1pdf,1);

# Overlay the second input page over the first
$page = $outputpdf->importpage
($input2pdf,1, $outputpdf->openpage(1));

#Save the new file

1 comment:

  1. Andrew,

    Is this script right ? I couldn't get it to work. Did it get messed up when you copied it ?


    David Berk