tags:

views:

550

answers:

1

We have pdf templates of the following nature that need to be generated by a web application:

Sample Paragraph:

Dear {customer.name},

Your lawyer, {customer.lawyer.name} has contacted us about your account, {customer.account.number} requesting immediate closure of the account.

...

The {...} fields mentioned above are to accommodate the various acro fields that would be put in as placeholders, so that they can be populated with data.

But the problem is that the {customer.lawyer.name} field can be of varying lengths, 10 characters to 50 characters,

Using iText, how can we generate a pdf for the above template such that varying lengths of the variable can be accommodated? Maybe even wrap the text around appropriately?

+1  A: 

I used iText columns to layout letters. Here is an example from my work. Note that I've only just typed this into Stack Overflow, I've not compiled or tested it.

Imagine a file where two newlines in a row indicate a paragraph, the text is otherwise wrapped by the text editor. The following class has a method named generate that reads the file and emits a US Letter sized PDF with a 1 inch margin at top and bottom and 1 1/2 inch margins on each side.

/** Generates a letter. */
public class LetterGenerator
{
    /** One inch is 72 points. */
    private final static int INCH = 72;

    /** Generate a letter. */
    public void generate() throws DocumentException, IOException
    {
        BufferedReader in = new BufferedReader(new FileReader("letter.txt"));
        Document document = new Document(PageSize.LETTER);
        PdfWriter.getInstance(document, new FileOutputStream("letter.pdf"));
        PdfContentByte cb = writer.getDirectContent();
        ColumnText ct = new ColumnText(cb);
        String para;
        int spacingBefore = 0;
        while ((para = in.readLine()) != null)
        {
            line = line.trim();
            if (line.length() != 0)
            {
                // Shekhar, do your place-holder replacement here.
                Paragraph p = new Paragraph(line);
                p.setSpacingBefore(spacingBefore);
                ct.addElement(p);
                spacingBefore = 8;
            }
        }
        ct.setSimpleColumn(INCH, INCH * 1.5f, 7.5f * INCH, 9.5f * INCH);
        int status = ColumnText.START_COLUMN;
        while ((status & ColumnText.NO_MORE_TEXT) == 0)
        {   
            status = ct.go();
            ct.setYLine(PageSize.LETTER.getHeight() - INCH);
            ct.setSimpleColumn(INCH, INCH * 1.5f, 7.5f * INCH, 9.5f * INCH);
            document.newPage();
        }
        document.close();
    }
}

For the life of me, I can't remember why I reset the Y line.

iText is a nice library. I learned most of what I know about it form reading through the tutorials from the iText in Action book.

http://www.1t3xt.info/examples/itext-in-action.php

Unfortunately, I never did get around to buying the book.

Alan Gutierrez