Programming by Example: Generating PDFs in Java

KonfHub
3 min readOct 29, 2019
We learn programming by looking at example code!

We learn programming by doing and by looking at sample code. In this blog post, I’m going to show how write a simple program to generate PDF documents / reports.

Sample Data

What content to use as part of the PDF document? Just for sample data and show how to create tables, let’s try out this simple code:

Arrays.stream(ChronoUnit.values())
.forEach(val ->
System.out.printf("%40s %s \n", val, val.getDuration()));

This prints:

The ChronoUnit values and the corresponding duration (“Period of Time” — PT)

PT stands for “Period of Time”. For example, Weeks is PT168H — i.e., duration of period of time 168 hours.

ChronoUnit is “A standard set of date periods units. This set of units provide unit-based access to manipulate a date, time or date-time.” This enum is defined in java.time.temporal.

Now, let’s generate data in a table in a PDF document.

Generating PDF Document

For the PDF document generation, we are going to use the iText Java library.

How do we include the itext dependency? By adding the dependency from the IntelliJ IDEA (I am using CE version 2019.2). Press “Command + ;” (I am using a Mac) to pop-up the Project Structure window. Go to Project Structure -> Libraries -> “+” -> Maven.

From the popup, enter “com.itextpdf.maven:itextdoc:2.0.0” and press OK and you are good to go!

Now, in the program, let’s first create a document and a output stream to write the PDF:

var doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream("ChronoUnits.pdf"));
doc.open();

We need to create a title first:

var bold = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
var paragraph = new Paragraph("Duration of ChronoUnits");

And now to create the table:

var table = new PdfPTable(2);

And it has header title:

Stream.of("Chrono Unit", "Duration").forEach(table::addCell);

Traverse over ChronoUnit.values() by converting it into a stream of values, print the chrono unit name in the first column and then the chronounit duration in the second column.

Arrays.stream(ChronoUnit.values())
.forEach(val -> {
table.addCell(val.toString());
table.addCell(val.getDuration().toString());
});

We’re almost done — just add this table to the paragraph and the paragraph to the document and close it:

paragraph.add(table);
doc.add(paragraph);
doc.close();

Here is the whole program if you want to try it on your own:

package com.company;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.stream.Stream;

public class Main {

public static void main(String[] args) throws DocumentException, FileNotFoundException {
var doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream("ChronoUnits.pdf"));
doc.open();

var bold = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
var paragraph = new Paragraph("Duration of ChronoUnits");

var table = new PdfPTable(2);
Stream.of("Chrono Unit", "Duration").forEach(table::addCell);

Arrays.stream(ChronoUnit.values())
.forEach(val -> {
table.addCell(val.toString());
table.addCell(val.getDuration().toString());
});

paragraph.add(table);
doc.add(paragraph);
doc.close();
}
}

From your “Project” window, you’ll see the “ChronoUnits.pdf” generated that looks like this:

The PDF document generated from this program

Here is the YouTube video that shows this coding in action that was covered in this blog post: https://youtu.be/LWqduyt1ck0. Have fun coding — Bye for now!

--

--

KonfHub

KonfHub is the one-stop platform to create and host tech events. Create the event in under 30 seconds, gamify & amplify for audience engagement!