Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Managing a MongoDB deployment? Take a load off and live migrate to MongoDB Atlas, the official automated service, with little to no downtime.

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

DataObject.java:

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;
    }
}


HeaderFooter.java:

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.setLockedWidth(true);
            table.getDefaultCell().setBorder(Rectangle.SUBJECT);
            table.addCell(header);
            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);
    }
}  


PdfCreater.java:

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,
            Font.BOLD);
    public final static Font NORMAL_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 8,
            Font.NORMAL);

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

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

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

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

        if(null == dataObjList){
            paragraph.add(new Chunk("No data to display."));
            return;
        }
        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());
            count++;
        }
        paragraph.add(table);
    }

    /** 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);
        preface.setAlignment(Element.ALIGN_CENTER);
        document.add(preface);
        document.newPage();
    }

    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));
            c1.setBackgroundColor(BaseColor.GREEN);
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);
        }
        table.setHeaderRows(1);
    }

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

    public static Paragraph getParagraph(){        
        Paragraph paragraph = new Paragraph();
        paragraph.setFont(PDFCreator.NORMAL_FONT);
        addEmptyLine(paragraph, 1);
        return paragraph;
    }
} 


Client.java:

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");
            writer.setPageEvent(event);
            document.open();
            PDFCreator.addMetaData(document, TITLE);
            PDFCreator.addTitlePage(document, TITLE);
            PDFCreator.addContent(document, dataObjList);
        }catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("FileNotFoundException occurs.." + e.getMessage());
        }finally{
            if(null != document){
                document.close();
            }
        }
    }

    public static List<DataObject> getDataObjectList(){

        List<DataObject> dataObjList = new ArrayList<DataObject>();
        DataObject d1 = new DataObject();
        d1.setComanyName("ABC");
        d1.setIncome("20000");
        d1.setYear("2017");

        DataObject d2 = new DataObject();
        d2.setComanyName("XYZ");
        d2.setIncome("30000");
        d2.setYear("2017");

        dataObjList.add(d1);
        dataObjList.add(d2);
        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!

MongoDB Atlas is the easiest way to run the fastest-growing database for modern applications — no installation, setup, or configuration required. Easily live migrate an existing workload or start with 512MB of storage for free.

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

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}