Here I am going to tell you how to convert CSV to PDF file using PyFPDF library in Java programming language. CSV is a comma separated value and it can be opened as a plain text file or in Microsoft excel file.
There are few advantages of CSV data:
- CSV format is considered to be standard format
- CSV is smaller in size and faster to handle
- CSV is simple to implement and easy to parse
- CSV is human readable and easy to edit manually
- CSV is processed by almost all applications
Prerequisites
Python 3.8.5, PyDPDF 1.7.2
Convert CSV to PDF File
Now I will show you how to convert CSV file to PDF file using PyFPDF. The first step would be is to read the CSV file. For reading CSV file you don’t need any extra module or package to be installed on your system. Python provides already built-in library to read or write to CSV files.
There are number of ways to read CSV data and you can check the examples for reading CSV file.
The first thing is you need to import csv
module which is already there in the Python installation.
It is assumed that I will read the CSV file from the same directory where this Python script is kept.
I am using the below code snippets for reading the CSV file using Python:
import csv
with open('sample.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
print(row)
The following code snippets are used to generate the PDF file. You need to import the required module PyPDF as from fpdf import FPDF
.
Next I have created PyPDF object, set font type/size.I have determined the column width. Then for each row in the CSV file I write to the PDF file.
I have put the data into the PDF file in tabular format.
Later –end of report– is written with different font type.
pdf = FPDF()
pdf.add_page()
page_width = pdf.w - 2 * pdf.l_margin
pdf.set_font('Times','B',14.0)
pdf.cell(page_width, 0.0, 'Students Data', align='C')
pdf.ln(10)
pdf.set_font('Courier', '', 12)
col_width = page_width/4
pdf.ln(1)
th = pdf.font_size
for row in reader:
#print(row)
pdf.cell(col_width, th, str(row[0]), border=1)
pdf.cell(col_width, th, row[1], border=1)
pdf.cell(col_width, th, row[2], border=1)
pdf.cell(col_width, th, row[3], border=1)
pdf.ln(th)
pdf.ln(10)
pdf.set_font('Times','',10.0)
pdf.cell(page_width, 0.0, '- end of report -', align='C')
pdf.output('student.pdf', 'F')
Finally the PDF file student.pdf is generated under the same directory where your Python script is kept.
Testing the Application
Now executing the above script will give you the following output in the file.

Source Code
Thanks for reading.