PDF pagination only takes a few lines

Cameron gives away working model for common chore

By Cameron Laird  Add a new comment

Let's put page numbers on the individual pages of a PDF document.

In fact, let's do it automatically. For the latest in Smart Development's irregular series on PDF coding techniques, I'll provide working code that we use on several of our sites.

The business requirement

Our applications produce a variety of PDF instances, many of them composed by pulling together information from a variety of sources, and synthesizing a final output. In effect, we don't know at the time individual pages are produced what other content will appear in the same report, and sometimes, not even the order of the elements. Certain customers insist their PDFs have page numbers, though; we fulfill this requirement by producing whole reports as they need to be, without page numbers, then starting over from the front and "decorating" the final version with appropriate page numbers.

The heart of the application lies in this method:

    /**
     * @see com.lowagie.text.pdf.PdfPageEvent#onEndPage(
     *      com.lowagie.text.pdf.PdfWriter,
     *      com.lowagie.text.Document)
     */
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();
        cb.saveState();
        String text = "Page " + writer.getPageNumber() + " of ";
        float textBase = document.bottom() - 20;
        float textSize = helv.getWidthPoint(text, 12);
        cb.beginText();
        cb.setFontAndSize(helv, 12);
        if ((writer.getPageNumber() % 2) == 1) {
            cb.setTextMatrix(document.left(), textBase);
            cb.showText(text);
            cb.endText();
            cb.addTemplate(total, document.left() + textSize, textBase);
        }
        // for even numbers, show the footer at the right
        else {
            float adjust = helv.getWidthPoint("0", 12);
            cb.setTextMatrix(document.right() - textSize - adjust, textBase);
            cb.showText(text);
            cb.endText();
            cb.addTemplate(total, document.right() - adjust, textBase);
        }
        cb.restoreState();
    }

Complete source is available through this link. Note the following:

  • There are plenty of paginators advertised. Some of them are quite convenient. However, all we found relied on Windows GUIs. That simply doesn't help when we need to produce thousands of finished reports automatically every month, or sometimes in a single day.
  • The specific flavor exhibited here writes "Page 15 of 60", for example, alternately on the lower right and lower left of successive pages.
  • Our paginator leverages the iText library. Please respect iText's licensing.
  • Our paginator isn't a general-purpose tool. It's only minimally configurable, we haven't tested it with a wide variety of page sizes, and it doesn't cleverly accomodate title pages or tables of contents. When we need those changes, we just update our Java source. The point of this posting is not to create such a general-purpose application; that probably requires "market analysis" of a sort at which we're not expert. What we do well is to meet specific customer requirements with compact, maintainable, and understandable code.

Naive observers make several mistakes about PDF: PDF is not, for example, an apt format for an editor or data manager. However, a reliable and powerful library makes possible PDF manipulations easy. The little paginator here illustrates how just a few lines of code can yield powerful results.

Coming up

Later this week, we'll show more examples of PDF automations, and how PDF usefully teams up with other image formats.

ITworld LIVE

DevelopmentWhite Papers & Webcasts

Webcast On Demand

How to Distribute Apps to Your Mobile Workforce

When considering enterprise app deployment, you may find some unexpected challenges and a number of options that range from simple distribution to running your own enterprise market. How can you determine the best approach for your organization? MOTODEV for Enterprise can help you understand and evaluate current enterprise deployment technologies and learn best practices that support your choice.

Sponsor: Motorola Mobility

Webcast On Demand

Authentication, Certificates and VPNs

MOTODEV for Enterprise can help get you up to speed quickly on key topics such as how to enable secure access to a company intranet from outside the firewall. This webinar provides a clear explanation of terms and technologies and what they can do for your enterprise app development.

Sponsor: Motorola Mobility

Webcast On Demand

Improving Enterprise App Quality with MOTODEV App Validator

MOTODEV for Enterprise supports quality app development for businesses, government, and institutions with technical resources and tools such as the MOTODEV App Validator, a free static analysis testing tool.

Sponsor: Motorola Mobility

White Paper

HR Analytics: Driving Return on Human Capital Investments

In today's economy, it's critical for organizations to make employee retention and development a major business focus, to ensure that valuable employees are not lost as the economy improves. With advanced BI solutions, organizations can be supported by workforce analytics to drive return on human capital investment and to see the value the workforce delivers to organizational performance. This white paper demonstrates how the increased power of having metrics and analytic insight can align core HR business processes with organizational goals and strategies and help ensure organizations make the right business decisions today for tomorrow.

White Paper

Positioning the CIO as a Powerful Business Partner with IT Portfolio Governance

In this whitepaper, learn how you can become a visionary portfolio manager and transform IT into a streamlined revenue and profit center.

See more White Papers | Webcasts

Ask a question

Ask a Question