DEV Community

Leon Davis
Leon Davis

Posted on

Easily Convert CSV to PDF in Python

Working with data often involves multiple formats, and sometimes you need to convert CSV files into more shareable formats like PDF. PDFs are ideal for reports because they preserve layout and formatting across different devices. Python, combined with Spire.XLS, makes this conversion simple, fast, and reliable.

Why Use Spire.XLS for Python?

Spire.XLS is a professional library for working with Excel files in Python. It supports reading and writing Excel formats, and it also provides a straightforward way to export spreadsheets to PDF without relying on Microsoft Excel. This makes it a perfect choice for automation and server-side applications.

Step-by-Step Guide

1. Install Spire.XLS for Python

Before you begin, make sure Spire.XLS is installed:

pip install spire.xls
Enter fullscreen mode Exit fullscreen mode

2. Load Your CSV File

Start by loading your CSV file into a workbook:

from spire.xls import Workbook

workbook = Workbook()
workbook.LoadFromFile("sample.csv", ",", 1, 1)
Enter fullscreen mode Exit fullscreen mode

Here, LoadFromFile automatically detects the CSV format and loads it as a workbook that can be manipulated just like an Excel file.

3. Convert CSV to PDF

Once the CSV is loaded, exporting it to PDF is as simple as calling the SaveToFile method:

workbook.SaveToFile("CSVToPDF.pdf", FileFormat.PDF)
Enter fullscreen mode Exit fullscreen mode

This command converts all sheets in the workbook into a PDF file, preserving the data layout and formatting.

4. Optional: Adjust Page Settings

You can customize the PDF layout if needed:

sheet = workbook.Worksheets[0]
sheet.PageSetup.Orientation = sheet.PageOrientation.Landscape
sheet.PageSetup.FitToPagesWide = 1
sheet.PageSetup.FitToPagesTall = 0
Enter fullscreen mode Exit fullscreen mode

This ensures that your CSV data fits nicely on the PDF page without getting cut off.

Benefits of Using Spire.XLS

  • No dependency on Excel: Spire.XLS works independently of Microsoft Office.
  • High fidelity: The PDF output keeps your table layout intact.
  • Easy automation: Ideal for converting multiple CSV files in batch operations.

Conclusion

Converting CSV files to PDF in Python is straightforward with Spire.XLS. Whether you need a quick report or an automated data pipeline, this library makes the process smooth and efficient. With just a few lines of code, you can transform your raw CSV data into professional-looking PDF documents ready for distribution or presentation.

Top comments (0)