How to set up a table display?

Tags: tablesInvoicespublish databaseiText 5

I have an application that I want to print an invoice like document in a table setup. Each line in the table will be from a separate document from a database. The iteration through the Db is not an issue but I want it to display something like this:

Rough table layout

I can determine the total number of lines in the table in advance if that makes any difference. Does anyone have a piece of code to use as a starting point?

Posted on StackOverflow on Jun 30, 2015 by Bill F

Please take a look at the SimpleTable11 example and the PDF that is created when you run that code: simple_table11.pdf

Database query rendered to PDF table
Database query rendered to PDF table

As you need different types of PdfPCell instance (without/with thick border, with/without, colspan, left/right aligned), you will benefit from writing a helper method:

public PdfPCell createCell(String content, float borderWidth, int colspan, int alignment) {
    PdfPCell cell = new PdfPCell(new Phrase(content));
    return cell;

Using this method will make your code easier to read and maintain.

This is how we create the document and add the table:

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(dest));;
    PdfPTable table = new PdfPTable(5);
    table.setWidths(new int[]{1, 2, 1, 1, 1});
    table.addCell(createCell("SKU", 2, 1, Element.ALIGN_LEFT));
    table.addCell(createCell("Description", 2, 1, Element.ALIGN_LEFT));
    table.addCell(createCell("Unit Price", 2, 1, Element.ALIGN_LEFT));
    table.addCell(createCell("Quantity", 2, 1, Element.ALIGN_LEFT));
    table.addCell(createCell("Extension", 2, 1, Element.ALIGN_LEFT));
    String[][] data = {
        {"ABC123", "The descriptive text may be more than one line and the text should wrap automatically", "$5.00", "10", "$50.00"},
        {"QRS557", "Another description", "$100.00", "15", "$1,500.00"},
        {"XYZ999", "Some stuff", "$1.00", "2", "$2.00"}
    for (String[] row : data) {
        table.addCell(createCell(row[0], 1, 1, Element.ALIGN_LEFT));
        table.addCell(createCell(row[1], 1, 1, Element.ALIGN_LEFT));
        table.addCell(createCell(row[2], 1, 1, Element.ALIGN_RIGHT));
        table.addCell(createCell(row[3], 1, 1, Element.ALIGN_RIGHT));
        table.addCell(createCell(row[4], 1, 1, Element.ALIGN_RIGHT));
    table.addCell(createCell("Totals", 2, 4, Element.ALIGN_LEFT));
    table.addCell(createCell("$1,552.00", 2, 1, Element.ALIGN_RIGHT));

As you indicated that you already have the code to loop over the records in a database, I mimicked those records using a two-dimensional String array.