Adding page numbers to merged PDF
I had a project that required combining multiple one-page PDFs into a single PDF, and then adding “Page x of y” to each page. ColdFusion can’t currently do this, so I looked at iText. There was some excellent example code and many other better coders have written CF extensions to use iText, but I couldn’t find one to solve my problem exactly. I ended up using javaloader.cfc to call iText without adding it to the CF classpath, and then turning some of the example Java code into CF by object and method calls. It worked out well.
[cfm]
// add page numbers
reader = loader.create(”com.lowagie.text.pdf.PdfReader”).init(concatArgs[1]);
output = loader.create(”java.io.FileOutputStream”).init(replace(concatArgs[1],”temp.pdf”,”combined.pdf”));
stamp = loader.create(”com.lowagie.text.pdf.PdfStamper”).init(reader, output);
bf = loader.create(”com.lowagie.text.pdf.BaseFont”).createFont(”Helvetica”, “UTF-8″, “True”);
over = loader.create(”com.lowagie.text.pdf.PdfContentByte”);
pages = reader.getNumberOfPages();
for ( i = 1; i LTE pages; i = i + 1 ) {
over = stamp.getOverContent(javacast(”int”,i));
over.beginText();
over.setFontAndSize(bf, 12);
over.setTextMatrix(30, 30);
over.showText(”page ” & i & ” of ” & pages);
over.endText();
}
stamp.close();
[/cfm]

January 29th, 2008 at 12:12 am
Hi there,
I was wondering if you could please give me some basic steps of how to call this useful looking piece of scripting from the Terminal; can it be compiled so that it’s accessible from the command line or something similar?
I’m very familiar with bash, but unfortunately not at all familiar with java or itext – but if you could point me in the right direction, I’m very keen to give stuff a try … I think I’d use this script a lot.
Thanks very much!
January 29th, 2008 at 7:08 am
Hi. The underlying Java tool is iText, which can be used like any other Java code. The documentation is very good on the site: http://www.lowagie.com/iText/
I know some folks have used Python and Ruby to call iText as well, I suspect you could even find some Applescript out there. This code is specific to ColdFusion to solve a problem I had in a web application, so it’s not really suited to command line use.
January 29th, 2008 at 8:43 am
Thanks very much for your reply … I will definitely be looking into iText in the future, when I’ve got my head around Java.
I’ve just found another way to solve this problem … I found that I had a python script /Developer/Examples/Quartz/Python/watermark.py and just modified a couple of the lines to get the desired outcome.
Thanks very much … PS: I like your blog.
April 26th, 2008 at 1:29 pm
[...] needed to add page numbers to a PDF document. After some searching I came across the blog post Adding page numbers to merged PDF, which explains it for some ColdFusion environment. I extracted the Java code necessary to do this [...]