PDF Creation With Java

DZone 's Guide to

PDF Creation With Java

Need to make some PDFs with Java? If you're not familiar with iText library, here's your chance to see this piece of open source software generate PDFs.

· Java Zone ·
Free Resource

PDF creation is required in some of Java-based applications, as PDF is one of the most popular document types due to its read-only and platform-independent attributes. iText is an open source library that helps integrate the PDF functionalities (create/manipulate) in your application.

iText has classes as Document objects, which are basically the main containers, and other classes are residing within them. Paragraph is a content type that can be written to the Document object. Other content types are Anchor, Chapter,  Phrase,  PdfpTable, Section, List, etc. These classes help create a PDF document.

Let's look at the working example.

Required JAR: itextpdf-5.1.0.jar


package com.test.pdf;

public class DataObject {
    private String year;
    private String income;
    private String comanyName;

    public String getYear() {
        return year;
    public void setYear(String year) {
        this.year = year;
    public String getIncome() {
        return income;
    public void setIncome(String income) {
        this.income = income;
    public String getComanyName() {
        return comanyName;
    public void setComanyName(String comanyName) {
        this.comanyName = comanyName;


package com.test.pdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

class HeaderFooter extends PdfPageEventHelper {

    /** The header/footer text. */
    String header;

    /** The template with the total number of pages. */
    PdfTemplate total;

     * Allows us to change the content of the header.
     * @param header The new header String
    public void setHeader(String header) {
        this.header = header;

     * Creates the PdfTemplate that will hold the total number of pages
    public void onOpenDocument(PdfWriter writer, Document document) {
        total = writer.getDirectContent().createTemplate(25, 16);

     * Adds a header to every page
    public void onEndPage(PdfWriter writer, Document document) {
        PdfPTable table = new PdfPTable(2);
        try {
            table.setWidths(new int[]{200, 30});
            table.addCell(String.format("Page %d ", writer.getPageNumber()));

            Rectangle page = document.getPageSize();

            table.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
            table.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - document.topMargin()
                    + table.getTotalHeight()+5, writer.getDirectContent());          
        catch(DocumentException de) {
            throw new ExceptionConverter(de);

     * Fills out the total number of pages before the document is closed
    public void onCloseDocument(PdfWriter writer, Document document) {
        ColumnText.showTextAligned(total, Element.ALIGN_LEFT,
                new Phrase(String.valueOf(writer.getPageNumber() - 1)), 2, 2, 0);


package com.test.pdf;

import java.util.Date;
import java.util.List;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;

 * This is to create a PDF file.
public class PDFCreator {

    private final static String[] HEADER_ARRAY = {"S.No.", "CompanyName", "Income", "Year"};
    public final static Font SMALL_BOLD = new Font(Font.FontFamily.TIMES_ROMAN, 8,
    public final static Font NORMAL_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 8,

    public static void addMetaData(Document document, String sqlXMLFileName) {
        document.addTitle("Sample Report");
        document.addSubject("Using iText");

    public static void addContent(Document document, List<DataObject> dataObjList) throws DocumentException {
        Paragraph paragraph = new Paragraph();
        createReportTable(paragraph, dataObjList);

    private static void createReportTable(Paragraph paragraph, List<DataObject> dataObjList)
    throws BadElementException {

        PdfPTable table = new PdfPTable(4);
        paragraph.add(new Chunk("Report Table :- ", SMALL_BOLD));

        if(null == dataObjList){
            paragraph.add(new Chunk("No data to display."));
        addHeaderInTable(HEADER_ARRAY, table);

        int count = 1;

        for(DataObject dataObject : dataObjList){
            addToTable(table, String.valueOf(count)+".");
            addToTable(table, dataObject.getComanyName());
            addToTable(table, dataObject.getIncome());
            addToTable(table, dataObject.getYear());

    /** Helper methods start here **/  
    public static void addTitlePage(Document document, String title) throws DocumentException {

        Paragraph preface = new Paragraph();
        addEmptyLine(preface, 3);
        preface.add(new Phrase("Test Report: ", NORMAL_FONT));
        preface.add(new Phrase(title, PDFCreator.NORMAL_FONT));

        addEmptyLine(preface, 1);
        preface.add(new Phrase("Date: ", PDFCreator.SMALL_BOLD));
        preface.add(new Phrase(new Date().toString(), PDFCreator.NORMAL_FONT));
        addEmptyLine(preface, 1);
        preface.add(new Phrase("Report generated by: ", PDFCreator.SMALL_BOLD));
        preface.add(new Phrase("Arun", PDFCreator.NORMAL_FONT));
        addEmptyLine(preface, 2);
        preface.add(new Phrase("This is basically a sample report.", PDFCreator.NORMAL_FONT));

        document.addSubject("PDF : " + title);

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

    public static void addHeaderInTable(String[] headerArray, PdfPTable table){

        PdfPCell c1 = null;
        for(String header : headerArray) {
            c1 = new PdfPCell(new Phrase(header, PDFCreator.SMALL_BOLD));

    public static void addToTable(PdfPTable table, String data){        
        table.addCell(new Phrase(data, PDFCreator.NORMAL_FONT));

    public static Paragraph getParagraph(){        
        Paragraph paragraph = new Paragraph();
        addEmptyLine(paragraph, 1);
        return paragraph;


package com.test.pdf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;

public class Client {
    private static final String TITLE = "TestReport";
    public static final String PDF_EXTENSION = ".pdf";

    public static void main(String[] args) {          

        List<DataObject> dataObjList = getDataObjectList();
        Document document = null;
        try {
        //Document is not auto-closable hence need to close it separately
            document = new Document(PageSize.A4);            

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(
                    new File(TITLE + PDF_EXTENSION)));
            HeaderFooter event = new HeaderFooter();
            event.setHeader("Test Report");
            PDFCreator.addMetaData(document, TITLE);
            PDFCreator.addTitlePage(document, TITLE);
            PDFCreator.addContent(document, dataObjList);
        }catch (DocumentException | FileNotFoundException e) {
            System.out.println("FileNotFoundException occurs.." + e.getMessage());
            if(null != document){

    public static List<DataObject> getDataObjectList(){

        List<DataObject> dataObjList = new ArrayList<DataObject>();
        DataObject d1 = new DataObject();

        DataObject d2 = new DataObject();

        return dataObjList;    

Now we are all set; simply run Client.java and you can see the generated PDF file named as 'TestReport.pdf'.

Happy Learning!

java ,itext ,pdf in java ,open source ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}