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))); document.add(heading);
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); t.setSpacingBefore(25); t.setSpacingAfter(25);
Next I will be iterating CSV data and create the row/cell of the table with data. Finally I have closed the
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:
student_id,student_dob,student_email,student_address 1,01-01-1980,email@example.com,Garifa 2,01-01-1982,firstname.lastname@example.org,Garia 3,01-01-1982,email@example.com,Salt Lake 4,01-01-1992,firstname.lastname@example.org,Alipore 5,01-01-1990,email@example.com,Salt Lake
CSV to PDF Output
Executing the code will give you the following output.
That’s all about converting CSV to PDF using iText in Java.
Thanks for reading.