Generate PDF using Java from scratch without any library

This article provides a programmatic example of generating PDF using pure Java code without use of any external libraries. In general, preferred approach is always to use PDF generating libraries so that focus stays on PDF content rather than PDF structure & specification. This tutorial is just an example to showcase how low level PDF generation works.

Minimal PDF by hand

To get some heads up, its good to have a quick read of very easy, simple & well-written “Minimal PDF” article which shows how a basic human readable & hand-written PDF structure looks. Example from this link can be copied into a simple text file & that file can be opened with PDF reader to render as PDF. We will use the example give in this article for our example in this article.

As given in “Minimal PDF“, basic structure of PDF looks like this

To understand format in more depth you can also read Understanding the Portable Document Format (PDF)

Let’s Design PDF Object in Java

We will start  with designing PDF object structure first as its basic building block of PDF structure specification.

This is the generic structure of the pdf object as per PDF specification

So lets start with creating a class representing pdf object.

For sake of simplicity while creating objects, lets add few constructors

Now lets add few methods for cases where this pdf object is used inside another pdf object as a reference.

Now lets add method to add text stream as per specification

Now finally lets add methods to build object.


Let’s design PDF structure in java

The class to represent PDF structure in above description will look like this. For simplicity sake, we have excluded cross reference section as it is not mandatory to have. It is helpful to PDF reader to get to objects faster.

Header & trailer will be built directly so no need for separate variables for the same.


Finally, let’s generate PDF file

Now as given in minimal PDF example, we will create all PDF objects, PDF structure & then write it to a generatedPDF.pdf file.

Here is the complete source code .


Text version of generated file

PDF opened in PDF reader

Leave a Reply

Your email address will not be published. Required fields are marked *