BASKET
Search
PDFlib

pdfa/pdfa2a_invoice

Download Java Code      Switch to PHP Code     Show Output PDF

/*

 * $Id: pdfa2a_invoice.java,v 1.2 2013/02/20 12:48:29 stm Exp $

 *

 * Combined PDF/UA-1 and PDF/A-2a invoice generation demo

 *

 * Required software: PDFlib+PDI/PPS 9

 * (set run_sample_with_pdi=false below to run the sample code without PDI)

 * Required data: two fonts, raster image, Tagged PDF

 */


package com.pdflib.cookbook.pdflib.pdfa;


import java.text.DateFormat;

import java.text.NumberFormat;

import java.util.Calendar;

import java.util.Date;

import java.util.Locale;


import com.pdflib.pdflib;

import com.pdflib.PDFlibException;


public class pdfa2a_invoice {

    final static boolean run_sample_with_pdi = true;


    final static double x_table = 55;

    final static double tablewidth = 475;


    final static double y_address = 682;

    final static double x_salesrep = 455;

    final static double y_invoice = 542;

    final static double y_invoice_p2 = 800;

    final static double bottom = 40;

    final static double imagesize = 90;


    final static double fontsize = 11;

    final static double fontsizesmall = 9;


    final static String fontname = "DejaVuSerif";


    final static String basefontoptions =

        "fontname=" + fontname + " fontsize=" + fontsize

            + " encoding=unicode embedding";


    final static String basetagoptions = "tag={tagname=P}";


    /**

     * Place company stationery

     * @throws Exception

     */

    static void create_stationery(pdflib p) throws Exception {

        String sender = "Kraxi Systems, Inc. • 17, " +

                        "Aviation Road • Paperfield";

        String stationeryfontname = "LuciduxSans-Oblique";


        double y_company_logo = 748;


        String senderfull = "17, Aviation Road\n"

            + "Paperfield<nextline leading=50%><nextparagraph leading=120%>"

            + "Phone 7079 4301\n"

            + "Fax 7079 4302<nextline leading=50%><nextparagraph leading=120%>"

            + "info@kraxi.com\n"

            + "www.kraxi.com\n";


        String salesrepfilename = "sales_rep4.jpg";

        String salesrepname = "Lucy Irwin";

        String salesrepcaption = "Local sales rep:";


        int salesrepimage;

        String optlist;

        int tf, id_p;


        /*

         * -----------------------------------

         * Print company logo and sender address

         *  -----------------------------------

         */


        if (run_sample_with_pdi) {

            int page, stationery;

            String stationeryfilename = "kraxi_logo2.pdf";


            stationery = p.open_pdi_document(stationeryfilename, "");

            page = p.open_pdi_page(stationery, 1, "");


            /* Check whether the page can be placed in the current situation */

            if ((int) p.info_pdi_page(page, "fittingpossible", "") == 0) {

                throw new Exception("Cannot place Tagged PDF page: "

                    + p.get_errmsg());

            }


            p.fit_pdi_page(page, 0, y_company_logo,

                "boxsize={595 85} position={65 center}");


            p.close_pdi_page(page);

            p.close_pdi_document(stationery);

        }


        optlist = basefontoptions + " fontsize=" + fontsizesmall + " fontname="

            + stationeryfontname + " charref=true tag={tagname=Artifact}";

        p.fit_textline(sender, x_table, y_address + fontsize, optlist);


        /*

         * -----------------------------------

         * Print full company contact details

         *  -----------------------------------

         */

        optlist = basefontoptions + " fontname=" + stationeryfontname

            + " leading=125% fillcolor={rgb 0.35 0.36 0.37}";

        tf = p.create_textflow(senderfull, optlist);


        optlist = "verticalalign=bottom " + basetagoptions;

        p.fit_textflow(tf, x_salesrep, y_address, x_salesrep + imagesize,

            y_address + 150, optlist);

        p.delete_textflow(tf);


        /*

         * -----------------------------------

         * Place name and image of local sales rep

         * -----------------------------------

         */

        id_p = p.begin_item("P", "");


        optlist = basefontoptions + " fontsize=" + fontsizesmall;

        p.fit_textline(salesrepcaption, x_salesrep, y_address - fontsizesmall,

            optlist);

        p.fit_textline(salesrepname, x_salesrep, y_address - 2 * fontsizesmall,

            optlist);


        salesrepimage = p.load_image("auto", salesrepfilename, "");


        optlist = "boxsize={" + imagesize + " " + imagesize

            + "} fitmethod=meet tag={tagname=Figure Alt={Image of sales rep.}}";

        p.fit_image(salesrepimage, x_salesrep, y_address - 3 * fontsizesmall

            - imagesize, optlist);

        p.close_image(salesrepimage);


        p.end_item(id_p);

    }


    /**

     * Print receiver address

     * @throws PDFlibException

     */

    static void create_address(pdflib p) throws PDFlibException {

        String address = "John Q. Doe\n"

            + "255 Customer Lane\n"

            + "Suite B\n"

            + "12345 User Town\n"

            + "Everland";


        String optlist = basefontoptions + " leading=120%";

        int tf = p.create_textflow(address, optlist);


        optlist = basetagoptions;

        p.fit_textflow(tf, x_table, y_address, x_table + tablewidth / 2,

            y_address - 100, optlist);

        p.delete_textflow(tf);

    }


    /*

     * -----------------------------------

     * Print the header and date

     * -----------------------------------

     */

    static void create_table_header(pdflib p, int id_div)

                throws PDFlibException {

        String invoiceheader = "INVOICE "

                + Calendar.getInstance().get(Calendar.YEAR) + "-03";


        /* Add a structured bookmark which references the Div element */

        String optlist = "item=" + id_div;

        p.create_bookmark(invoiceheader, optlist);


        optlist = basefontoptions + " tag={tagname=H1 Title={" + invoiceheader

            + "}}";

        p.fit_textline(invoiceheader, x_table, y_invoice, optlist);


        String date = DateFormat.getDateInstance(DateFormat.LONG, Locale.US)

            .format(new Date());


        optlist = "position {100 0} " + basefontoptions + " " + basetagoptions;

        p.fit_textline(date, x_table + tablewidth, y_invoice, optlist);

    }


    public static void main(String argv[]) {


        /* This is where font/image/PDF input files live. Adjust as necessary. */

        String searchpath = "../input";


        String tablesummary = "List of purchased articles";


        String closingtext =

            "Terms of payment: <fillcolor={rgb 1 0 0}>30 days net. "

            + "<fillcolor={gray 0}>90 days warranty starting at the day of sale. "

            + "This warranty covers defects in workmanship only. "

            + "Kraxi Systems, Inc. will, at its option, repair or replace the "

            + "product under the warranty. This warranty is not transferable. "

            + "No returns or exchanges will be accepted for wet products.";


        class articledata {

            articledata(String name, double price, int quantity) {

                this.name = name;

                this.price = price;

                this.quantity = quantity;

            }


            String name;

            double price;

            int quantity;

        }


        articledata[] data = {

            new articledata("Super Kite", 20, 2),

            new articledata("Turbo Flyer", 40, 5),

            new articledata("Giga Trash", 180, 1),

            new articledata("Bare Bone Kit", 50, 3),

            new articledata("Nitty Gritty", 20, 10),

            new articledata("Pretty Dark Flyer", 75, 1),

            new articledata("Free Gift", 0, 1)

        };


        String[] headers = { "ITEM", "DESCRIPTION", "QUANTITY", "PRICE",

            "AMOUNT" };


        String[] alignments = { "right", "left", "right", "right", "right" };


        final NumberFormat priceFormat = NumberFormat.getInstance(Locale.US);

        priceFormat.setMaximumFractionDigits(2);

        priceFormat.setMinimumFractionDigits(2);


        int i, pagecount = 0;

        int row, col, tbl;

        String result;

        double total;

        String optlist;

        String buf;

        int tf;

        int id_sect = 0, id_div = 0;

        pdflib p = null;


        try {

            p = new pdflib();


            optlist = "SearchPath=" + searchpath;

            p.set_option(optlist);


            /*

             * This mean we don't have to check error return values, but will

             * get an exception in case of runtime problems.

             */

            p.set_option("errorpolicy=exception");


            /* "autospace" improves Reflow */

            p.set_option("autospace=true");


            p.begin_document("pdfa2a_invoice.pdf",

                "pdfua=PDF/UA-1 pdfa=PDF/A-2a lang=en "

                    + "tag={tagname=Document "

                    + "Title={PDFlib PDF/UA and PDF/A-2a invoice demo}}");


            p.set_info("Creator", "starter_pdfua1.c");

            p.set_info("Author", "Thomas Merz");

            p.set_info("Title",

                "PDFlib PDF/UA and PDF/A-2a invoice demo (Java)");


            /* Use sRGB output intent so that we can use RGB color */

            p.load_iccprofile("sRGB", "usage=outputintent");


            /* Each Div element could contain a separate invoice */

            id_div = p.begin_item("Div", "Title={Invoice}");


            /*

             * -----------------------------------

             * Create and place table with article list

             * -----------------------------------

             */

            /* ---------- Header row */

            row = 1;

            tbl = -1;


            for (col = 1; col <= headers.length; col++) {

                optlist = "fittextline={position={" + alignments[col - 1]

                    + " center} " + basefontoptions + " " + basetagoptions

                    + "} margin=2";

                tbl = p

                    .add_table_cell(tbl, col, row, headers[col - 1], optlist);

            }

            row++;


            /* ---------- Data rows: one for each article */

            total = 0;


            for (i = 0; i < data.length; i++) {

                double sum = data[i].price * data[i].quantity;

                col = 1;


                /* column 1: ITEM */

                buf = "" + (i + 1);

                optlist = "fittextline={position={" + alignments[col - 1]

                    + " center} " + basefontoptions + " " + basetagoptions

                    + "} margin=2";

                tbl = p.add_table_cell(tbl, col++, row, buf, optlist);


                /* column 2: DESCRIPTION */

                optlist = "fittextline={position={" + alignments[col - 1]

                    + " center} " + basefontoptions + " " + basetagoptions

                    + "} colwidth=50% margin=2";

                tbl = p.add_table_cell(tbl, col++, row, data[i].name, optlist);


                /* column 3: QUANTITY */

                buf = "" + data[i].quantity;

                optlist = "fittextline={position={" + alignments[col - 1]

                    + " center} " + basefontoptions + " " + basetagoptions

                    + "} margin=2";

                tbl = p.add_table_cell(tbl, col++, row, buf, optlist);


                /* column 4: PRICE */

                buf = priceFormat.format(data[i].price);

                optlist = "fittextline={position={" + alignments[col - 1]

                    + " center} " + basefontoptions + " " + basetagoptions

                    + "} margin=2";

                tbl = p.add_table_cell(tbl, col++, row, buf, optlist);


                /* column 5: AMOUNT */

                buf = priceFormat.format(sum);

                optlist = "fittextline={position={" + alignments[col - 1]

                    + " center} " + basefontoptions + " " + basetagoptions

                    + "} margin=2";

                tbl = p.add_table_cell(tbl, col++, row, buf, optlist);


                total += sum;

                row++;

            }


            /* ---------- Print total in the rightmost column */

            buf = priceFormat.format(total);

            optlist = "fittextline={position={"

                + alignments[headers.length - 1] + " center} "

                + basefontoptions + " " + basetagoptions + "} margin=2";

            tbl = p.add_table_cell(tbl, headers.length, row++, buf, optlist);


            /* ---------- Footer row with terms of payment */

            optlist = basefontoptions + " alignment=justify leading=120%";

            tf = p.create_textflow(closingtext, optlist);


            optlist = "rowheight=1 margin=2 margintop=" + (2 * fontsize)

                + " colspan=" + headers.length + " textflow=" + tf

                + " fittextflow={" + basetagoptions + "}";

            tbl = p.add_table_cell(tbl, 1, row++, "", optlist);


            /*

             * ---------- Place the table instance(s), creating pages as

             * required

             */

            do {

                double top;


                p.begin_page_ext(0, 0, "width=a4.width height=a4.height");


                if (++pagecount == 1) {

                    id_sect = p.begin_item("Sect", "Title={Invoice header}");


                    create_stationery(p);

                    create_address(p);


                    p.end_item(id_sect);


                    top = y_invoice - 3 * fontsize;


                    id_sect = p.begin_item("Sect", "Title={Invoice body}");


                    create_table_header(p, id_div);

                }

                else {

                    top = y_invoice_p2;

                }

                /* Place the table on the page; Shade every other row. */

                optlist = "header=1 fill={{area=rowodd fillcolor={gray 0.9}}} "

                    + "tag={tagname=Table Summary={" + tablesummary + "}}";


                result = p.fit_table(tbl, x_table, bottom,

                    x_table + tablewidth, top, optlist);


                if (result.equals("_error")) {

                    throw new Exception("Couldn't place table: "

                        + p.get_errmsg());

                }


                p.end_page_ext("");

            }

            while (result.equals("_boxfull"));


            p.delete_table(tbl, "");


            p.end_item(id_sect);

            p.end_item(id_div);

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

            }

        }

    }

}