An Example Java itext Pdf Creator For a Table

Posted by dogukanhan on February 05, 2020 · 4 mins read

This is a simple example of creating pdf in java using itext. The PdfCreator class has one job, converting a list contains entities to table with adding header and footer text. Application.java shows how it can be used easly so you don’t need to worry about pdf creating, just add your list of entities and set how them will be sown.

</figure>

PdfCreator.java

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

public class PdfCreator<E> {

    private static final Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
            Font.BOLD);

    private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
            Font.BOLD);

    public Object[] getLastLines() {
        return lastLines;
    }

    public void setLastLines(Object[] lastLines) {
        if (lastLines.length != headers.length) {
            throw new RuntimeException("Last lines size doesn't equal to headers size");
        }
        this.lastLines = lastLines;
    }

    static class AbstractRow {

        private final int size;

        private final Map<Integer, Object> map;

        private AbstractRow(int size) {
            this.size = size;
            this.map = new HashMap<>();
        }

        public AbstractRow setCell(int cell, Object data) {
            if (map.containsKey(cell)) {
                throw new RuntimeException(cell + " is already filled, " +
                        "make sure setCell called ones per cell");
            }
            map.put(cell, data);
            return this;
        }

    }

    public interface ViewOnDemand<E> {
        void demand(AbstractRow row, E e);
    }

    private String title;

    private String headerDescription;

    private String footerDescription;

    private final String[] headers;

    private Object[] lastLines;

    private final int columnSize;

    private final ViewOnDemand<E> viewOnDemand;

    private final java.util.List<E> list;

    public PdfCreator(java.util.List<E> list, ViewOnDemand<E> viewOnDemand, String... headers) {
        this.headers = headers;
        this.columnSize = headers.length;
        this.viewOnDemand = viewOnDemand;
        this.list = list;
    }

    public void writePDF(String path) throws DocumentException, FileNotFoundException {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(path));
        document.open();

        Paragraph preface = new Paragraph();

        Paragraph title = new Paragraph(this.title, catFont);
        title.setAlignment(Element.ALIGN_CENTER);
        preface.add(title);

        addEmptyLine(preface, 1);
        // Will create: Report generated by: _name, _date
        preface.add(new Paragraph(
                this.headerDescription, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                smallBold));
        addEmptyLine(preface, 1);

        Chapter catPart = new Chapter(new Paragraph(preface), 1);
        createTable(catPart);
        document.add(catPart);

        Paragraph footer = new Paragraph(this.footerDescription);
        document.add(footer);
        document.close();
    }

    private void createTable(Section subCatPart)
            throws BadElementException {

        PdfPTable table = new PdfPTable(this.columnSize);

        for (String header : headers) {
            PdfPCell c1 = new PdfPCell(new Phrase(header));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);
        }

        table.setHeaderRows(1);
        for (E e : list) {
            final AbstractRow row = new AbstractRow(columnSize);
            viewOnDemand.demand(row, e);
            if (row.size != columnSize) {
                throw new RuntimeException("Row's element size doesn't match header's size");
            }

            for (int i = 0; i < columnSize; i++) {
                Object rowElement = row.map.get(i);
                if (rowElement != null)
                    table.addCell(rowElement.toString());
                else
                    table.addCell("");
            }
        }

        if (lastLines != null) {
            for (Object c : lastLines) {
                if (c == null) {
                    table.addCell("");
                } else {
                    table.addCell(c.toString());
                }
            }
        }

        subCatPart.add(table);
    }


    private static void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
            paragraph.add(new Paragraph(" "));
        }
    }

    public String getTitle() {
        return title;
    }

    public PdfCreator setTitle(String title) {
        this.title = title;
        return this;
    }

    public String getHeaderDescription() {
        return headerDescription;
    }

    public PdfCreator setHeaderDescription(String headerDescription) {
        this.headerDescription = headerDescription;
        return this;
    }

    public String getFooterDescription() {
        return footerDescription;
    }

    public PdfCreator setFooterDescription(String footerDescription) {
        this.footerDescription = footerDescription;
        return this;
    }

    public String[] getHeaders() {
        return headers;
    }

    public int getColumnSize() {
        return columnSize;
    }

}

Application.java

import com.itextpdf.text.DocumentException;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class Application {

    private static String FILE = "/home/dogukanhan/Desktop/delta/1.pdf";

    static class Customer{
        String name;
        String surname;
        int age;

        public Customer(String name, String surname, int age) {
            this.name = name;
            this.surname = surname;
            this.age = age;
        }
    }

    public static void main(String[] args) throws DocumentException, FileNotFoundException {
        List<Customer> customers = new ArrayList<>();
        customers.add(new Customer("onur","durkal",30));
        customers.add(new Customer("dogukan","han",22));

        new PdfCreator<>(customers,  new PdfCreator.ViewOnDemand<Customer>() {
            @Override
            public void demand(PdfCreator.AbstractRow row, Customer customer) {
                row.setCell(0,customer.name)
                        .setCell(1,customer.surname)
                        .setCell(2,customer.age);
            }
        },"Name","Surname","Age").setTitle("Test").setHeaderDescription("Dumbura").writePDF(FILE);


    }
}