How to convert CSV File to PDF File using Python?

How to convert CSV File to PDF File using Python?

Converting a CSV file to a PDF file involves two main steps:

  1. Reading the CSV data.
  2. Writing that data into a PDF format.

For this, we can use pandas for reading the CSV file and reportlab for creating a PDF. Here's a step-by-step guide:

Step 1: Install the required libraries:

If you haven't already, you need to install pandas and reportlab:

pip install pandas reportlab 

Step 2: Convert CSV to PDF:

import pandas as pd from reportlab.lib.pagesizes import letter, landscape from reportlab.lib import colors from reportlab.platypus import SimpleDocTemplate, Table, TableStyle def csv_to_pdf(input_csv, output_pdf): # Read CSV file using pandas data_frame = pd.read_csv(input_csv) # Convert dataframe to list and add the header data = [data_frame.columns.to_list()] + data_frame.values.tolist() # Create a new PDF with Reportlab pdf = SimpleDocTemplate(output_pdf, pagesize=landscape(letter)) # Create a table with the data table = Table(data) # Add some style to the table (borders, background, etc.) style = TableStyle([ ('BACKGROUND', (0, 0), (-1, 0), colors.grey), ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, 0), 14), ('BOTTOMPADDING', (0, 0), (-1, 0), 12), ('BACKGROUND', (0, 1), (-1, -1), colors.beige), ('GRID', (0, 0), (-1, -1), 1, colors.black) ]) table.setStyle(style) # Add the table to the PDF pdf.build([table]) # Use the function csv_to_pdf("path_to_input.csv", "path_to_output.pdf") 

Replace path_to_input.csv with the path to your CSV file and path_to_output.pdf with the desired path for the output PDF.

After running this script, you'll have your CSV data presented in a table format inside a PDF document.


More Tags

math tdd listener reactstrap pointer-arithmetic session firebase-hosting validation resolution doctrine-orm

More Programming Guides

Other Guides

More Programming Examples