DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How to Convert Between PDF and TIFF in Java
  • How to Split PDF Files into Separate Documents Using Java
  • How to Get Plain Text From Common Documents in Java
  • How to Change PDF Paper Sizes With an API in Java

Trending

  • No More Cheap Claude: 4 First Principles of Token Economics in 2026
  • AWS Kiro: The Agentic IDE That Makes Specs the Unit of Work
  • Solving the Mystery: Why Java RSS Grows in Docker on M1 Macs
  • The Cost of Knowing: When Observability Becomes the Outage
  1. DZone
  2. Coding
  3. Java
  4. PDF Creation With Java

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.

By 
Arun Pandey user avatar
Arun Pandey
DZone Core CORE ·
Jul. 14, 17 · Tutorial
Likes (29)
Comment
Save
Tweet
Share
75.6K Views

Join the DZone community and get the full member experience.

Join For Free

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!

PDF Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert Between PDF and TIFF in Java
  • How to Split PDF Files into Separate Documents Using Java
  • How to Get Plain Text From Common Documents in Java
  • How to Change PDF Paper Sizes With an API in Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook