PDFlib Cookbook

cookbook

pdf_import/import_in_reverse_order

Download Java Code        Switch to PHP Code      Show Output PDF

/* $Id: import_in_reverse_order.java,v 1.3 2013/01/15 10:12:02 stm Exp $
 * Import in reverse order:
 * Read the pages of an input PDF document and output them in reverse order
 *  
 * Open the pages of the input document in reverse order and place them in
 * the output PDF.
 *  
 * Required software: PDFlib+PDI/PPS 9
 * Required data: PDF document
 */
package com.pdflib.cookbook.pdflib.pdf_import;

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

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

    pdflib p = null;
    String pdffile = "PDFlib-datasheet.pdf";
    int indoc, pageno, endpage, page;

    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.3 $");

        /* Open the input PDF */
        indoc = p.open_pdi_document(pdffile, "");
        if (indoc == -1)
            throw new Exception("Error: " + p.get_errmsg());
   
        /* Retrieve the overall number of pages for the input document */
        endpage = (int) p.pcos_get_number(indoc, "length:pages");

        /* Loop over all pages of the input document in reverse order */
        for (pageno = endpage; pageno > 0; pageno--)
        {
            page = p.open_pdi_page(indoc, pageno, "");

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

            /* Dummy page size; will be adjusted later */
            p.begin_page_ext(10, 10, "");

            /* Place the imported page without performing
             * any changes on the output page
             */
            p.fit_pdi_page(page, 0, 0, "adjustpage");
            
            p.end_page_ext("");

            p.close_pdi_page(page);
        }
 
        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();
            }
        }
    }
}