PDFlib Cookbook

cookbook

pagination/reverse_page_order

Create pages in reverse page order.

Download Java Code  Switch to PHP Code  Show Output 

/*
 * 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;
        int exitcode = 0;

        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);

            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.println("PDFlib exception occurred:");
            System.err.println("[" + e.get_errnum() + "] " + e.get_apiname()
                + ": " + e.get_errmsg());
            exitcode = 1;
        } catch (Exception e) {
            System.err.println(e);
            exitcode = 1;
        } finally {
            if (p != null) {
                p.delete();
            }
            System.exit(exitcode);
        }
    }
}