Python: Convert CSV to PDF

2023-09-04 01:28:28 Written by  support iceblue
Rate this item
(0 votes)

A CSV (Comma-Separated Values) file is a plain text file used to store tabular data. Although CSV files are widely supported by spreadsheet programs, there may still be times when you need to convert them to PDF files to ensure broader accessibility and also enable security features. This article will demonstrate how to convert CSV to PDF in Python using Spire.XLS for Python.

Install Spire.XLS for Python

This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.XLS

If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows

Convert CSV to PDF in Python

The Workbook.SaveToFile() method provided by Spire.XLS for Python allows to save a CSV file as a PDF file. The following are the detailed steps.

  • Create a Workbook object.
  • Load a CSV file using Workbook.LoadFromFile() method.
  • Set the Workbook.ConverterSetting.SheetFitToPage property as true to ensure the worksheet is rendered to one PDF page.
  • Get the first worksheet in the Workbook using Workbook.Worksheets[] property.
  • Loop through the columns in the worksheet and auto-fit the width of each column using Worksheet.AutoFitColumn() method.
  • Convert the CSV file to PDF using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load a CSV file
workbook.LoadFromFile("sample.csv", ",", 1, 1)

# Set the SheetFitToPage property as true
workbook.ConverterSetting.SheetFitToPage = True

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Autofit columns in the worksheet
i = 1
while i < sheet.Columns.Length:
    sheet.AutoFitColumn(i)
    i += 1

# Save the CSV file to PDF
workbook.SaveToFile("CSVToPDF.pdf", FileFormat.PDF)
workbook.Dispose()

Python: Convert CSV to PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Thursday, 25 April 2024 02:12