/* $Id: mail_merge.java,v 1.2 2007/11/30 17:05:27 katja Exp $
 * Mail merge:
 * Output an imported PDF page several times, with its blocks being filled with
 * with different personalized data
 * 
 * Import a PDF page representing a letter template. To create letters for
 * various persons, output the page several times with the contained blocks
 * being filled with personalized data related to the respective person. 
 * 
 * Required software: PPS 7
 * Required data: PDF document with blocks
 */
package com.pdflib.cookbook.pdflib.blocks;

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

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

    pdflib p = null;
    double width, height;
    String infile = "stationery_blocks.pdf";
    int i, j, inpage, indoc;
    String optlist;
    
    int nblocks = 3; // number of person-related blocks to be filled
    
    /* Names of the person-related blocks contained on the imported page */
    String blocknames[] = {
        "name", "business_address", "business_city" 
    };
    
    int npersons = 3; // number of persons
    
    /* Data related to various persons used for personalization */
    String persons[][] = {
        {"Mr Maurizio Moroni", "Strada Provinciale 124", "Reggio Emilia"},
        {"Ms Dominique Perrier", "25, rue Lauriston", "Paris"},
        {"Mr Liu Wong", "55 Grizzly Peak Rd.", "Butte"}
    };
    
    /* Static texts to output */
    final String intro = "Dear ";
    final String goodbye = "Yours sincerely Victor Kraxi";
    final String announcement =
        "Our BEST PRICE OFFER includes today:\n\n" +
        "Long Distance Glider\nWith this paper rocket you can send all your " +
        "messages even when sitting in a hall or in the cinema pretty near " +
        "the back.\n\n" +
        "Giant Wing\nAn unbelievable sailplane! It is amazingly robust and " +
        "can even do aerobatics. But it is best suited to gliding.\n\n" +
        "Cone Head Rocket\nThis paper arrow can be thrown with big swing. " +
        "We launched it from the roof of a hotel. It stayed in the air a " +
        "long time and covered a considerable distance.\n\n" +
        "Super Dart\nThe super dart can fly giant loops with a radius of 4 " +
        "or 5 meters and cover very long distances. Its heavy cone point is " +
        "slightly bowed upwards to get the lift required for loops.\n\n" +
        "Visit us on our Web site at www.kraxi.com!";
 
    try {
        p = new pdflib();

        p.set_parameter("SearchPath", searchpath);

        /* This means we must check return values of load_font() etc. */
        p.set_parameter("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.2 $");

        /* Open a PDF containing blocks */
        indoc = p.open_pdi_document(infile, "");
        if (indoc == -1)
            throw new Exception("Error: " + p.get_errmsg());
        
        /* Open the first page */
        inpage = p.open_pdi_page(indoc, 1, "");
        if (inpage == -1)
            throw new Exception("Error: " + p.get_errmsg());
        
        /* Get the width and height of the imported page */
        width = p.pcos_get_number(indoc, "pages[0]/width");
        height = p.pcos_get_number(indoc, "pages[0]/height");
        
        /* Based on the imported page output several pages with the blocks
         * being filled with data related to different persons
         */ 
        for (i = 0; i < npersons; i++)
        {
            /* Start the output page with the size given by the imported page */ 
            p.begin_page_ext(width, height, "");

            /* Place the imported page on the output page */
            p.fit_pdi_page(inpage, 0, 0, "");
        
            /* Option list for text blocks; the "bordercolor" and "linewidth"
             * options are only used to illustrate the block rectangles */
            optlist = "fontname=Helvetica encoding=unicode " +
                "bordercolor={gray 0.5} linewidth=0.25";

            /* Loop over all person related blocks. Fill the j-th block with the
             * corresponding entry of the persons array.
             */
            for (j = 0; j <  nblocks; j++) {
                if (p.fill_textblock(inpage, blocknames[j], persons[i][j],
                        optlist) == -1)
                    System.err.println("Warning: " + p.get_errmsg());
            }
        
            /* Output the "intro" block */
            if (p.fill_textblock(inpage, "intro", intro + persons[i][0],
                    optlist) == -1)
                System.err.println("Warning: " + p.get_errmsg());
  
            /* Output the "announcment" block */
            if (p.fill_textblock(inpage, "announcement", announcement,
                    optlist) == -1)
                System.err.println("Warning: " + p.get_errmsg());
        
            /* Output the "goodbye" block */
            if (p.fill_textblock(inpage, "goodbye", goodbye, optlist) == -1)
                System.err.println("Warning: " + p.get_errmsg());
        
            p.end_page_ext("");
        }
   
        p.close_pdi_page(inpage);

        p.end_document("");
        p.close_pdi_document(indoc);

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