PDFlib Cookbook

cookbook

pagination/reverse_page_order

Download Java Code       Switch to PHP Code      Show Output PDF

/* $Id: reverse_page_order.java,v 1.7 2013/01/15 10:12:01 stm Exp $
 * Reverse page order:
 * Create pages in reverse page order
 *
 * Create page no. 5 first, then page no. 4, etc.
 *
 * Required software: PDFlib/PDFlib+PDI/PPS 9
 * Required data: PDF document
 */
package com.pdflib.cookbook.pdflib.pagination;

import com.pdflib.pdflib;
import com.pdflib.PDFlibException;

public class reverse_page_order
{
    public static void main (String argv[])
    {
    /* This is where the data files are. Adjust as necessary. */
    String searchpath = "../input";
    String outfile = "reverse_page_order.pdf";
    String title = "Reverse Page Order";

    pdflib p = null;
    int lastpage = 5, pageno, font, step = 1;

    try {
        p = new pdflib();

        p.set_option("searchpath={" + searchpath + "}");

        /* This means we must check return values of load_font() etc. */
        p.set_option("errorpolicy=return");

        if (p.begin_document(outfile, "") == -1)
            throw new Exception("Error: " + p.get_errmsg());

        p.set_info("Creator", "PDFlib Cookbook");
        p.set_info("Title", title + " $Revision: 1.7 $");

        font = p.load_font("Helvetica-Bold", "unicode", "");

        if (font == -1)
        throw new Exception("Error: " + p.get_errmsg());

        /* Loop over all subsequent pages in reverse order */
        for (pageno = lastpage, step = 1; pageno > 0; pageno--, step++)
        {
            if (pageno == lastpage)
            	/* Create the first page */
                p.begin_page_ext(0, 0, "width=a4.width height=a4.height");
            else
            	/* Insert subsequent pages before what is (currently) the
            	 * first page */
                p.begin_page_ext(0, 0,
                    "width=a4.width height=a4.height pagenumber=1");

            /* Place a text line indicating the page number */
            p.setfont(font, 24);
            p.fit_textline("Page " + pageno + " created in step " + step,
                100, 500, "");

            p.end_page_ext("");
        }

        p.end_document("");

        } catch (PDFlibException e) {
            System.err.print("PDFlib exception occurred:\n");
            System.err.print("[" + e.get_errnum() + "] " + e.get_apiname() +
                ": " + e.get_errmsg() + "\n");
        } catch (Exception e) {
            System.err.println(e.getMessage());
        } finally {
            if (p != null) {
                p.delete();
            }
        }
    }
}