How to convert CSV file to PDF file using iText API in Java

Here I am going to tell you how to convert CSV to PDF file using iText library in Java programming language. I am going to use Java 7 or later version’s new feature Path API to read the CSV file and Java 8’s Stream API to split the comma separated line or record.

I am going to show you how to read file content into byte array and how to convert byte array into String. Then I am converting the array of String into a list of String. Finally from a list of String I am going to write to a PDF file using iText library in Java.


At least Java 1.8, Gradle 6.5.1, Maven 3.6.3, iText library 5.3.13..1

Convert CSV to PDF

The first step is to create a document which is the container for containing all elements of a pdf document.

Document document = new Document(PageSize.A4, 25, 25, 25, 25);

The first argument is size of the page and next arguments are left, right, top and bottom margins, respectively.

We need to define the type of this document, for example, for PDF we need PdfWriter. So we are going to define a writer for the document.

PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("student.pdf"));

The first argument is the reference to the document object, and the second argument is the absolute name of the file in which output will be written.

Next, we open the document for writing using;.;

Next I have created a paragraph that will be displayed as a title or heading of the content:

Paragraph heading = new Paragraph("~: Student Details :~",
				FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD, new BaseColor(0, 255, 0)));


Next I am going to create PdfPTable object that will help you to create a table where the CSV data will be kept in tabular format. I have put space before and after the table.

PdfPTable t = new PdfPTable(4);

Next I will be iterating CSV data and create the row/cell of the table with data. Finally I have closed the document and pdfWrite object.

You can download the full source code with sample CSV input file and the generated PDF file from the Source Code section from the bottom of this tutorial.

The content of the CSV file is shown below:

3,01-01-1982,,Salt Lake
5,01-01-1990,,Salt Lake

CSV to PDF Output

Executing the code will give you the following output.

convert csv to pdf file using itext in java

That’s all about converting CSV to PDF using iText in Java.

Source Code


Thanks for reading.

Leave a Reply

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