Creating PDFs in Java with iText

So you hear your boss or client say, I want my reports in “Excel and/or PDF,” and you think, “crap, now I gotta go find a library for my language.” And the requester isn’t often thinking about how much $$$ when they mention they want pdfs. So I had this same experience at UALR and I didn’t know the first thing about constructing pdf files. Thankfully, I found a free (with open source projects) Pdf library for Java called iText and within a day was able to construct a decent looking pdf file.

Here are some examples which enabled me to rapidly create my pdf reports. Specifically these two (1) (2) were helpful to me. You can see my PdfHelper here in subversion. The coolest part I think is the percentage bars I made without having to create images - I just use spaces and two contrasting colors to keep it simple.

public static Paragraph getPercentAndBar(double percent, Paragraph paragraph)
{
        Chunk spacer;
        Chunk negative_spacer;
        Integer divider = 1;
        Integer number_of_spaces = (int) (percent / divider);
        Integer max_number_of_spaces = (int) (100 / divider);

        DecimalFormat df = new DecimalFormat("#.#");
        df.setMinimumFractionDigits(0);
        df.setMaximumFractionDigits(1);

        Font small = new Font();
        small.setSize(4);

        StringBuffer spaces = new StringBuffer("");
        for(int i = 0; i < number_of_spaces; i++) spaces.append(" ");
        spacer = new Chunk(spaces.toString(), small);
        spacer.setBackground(new BaseColor(0x7a, 0x7a, 0x7a));

        StringBuffer filler_spaces = new StringBuffer("");
        for(int i = 0; i < max_number_of_spaces - number_of_spaces; i++) filler_spaces.append(" ");
        negative_spacer = new Chunk(filler_spaces.toString(), small);
        negative_spacer.setBackground(new BaseColor(0xAa, 0xAa, 0xAa));

        paragraph.add(spacer);
        paragraph.add(negative_spacer);
        paragraph.add(getSpaces(2));
        paragraph.add(getSpacing(df.format(percent), 5) + df.format(percent) + "%");

        return paragraph;
}
post by K.D. on 02/06/2012