DEV Community

jelizaveta
jelizaveta

Posted on

Convert CSV to PDF with Python with Beautiful Table Formatting

CSV files store tabular data in plain text and are highly versatile, but in formal settings—such as delivering data reports to clients, archiving project documents, or printing materials—their shortcomings become apparent: no formatting, uneven column widths, messy pagination, and a poor reading experience.

PDF perfectly compensates for these deficiencies. It has fixed layout and displays consistently across platforms, making it the preferred format for formal documents. This article introduces a straightforward approach: using the Spire.XLS for Python library to load a CSV file as a workbook, adjust table styling, and export it as a well-formatted PDF document. The entire process requires just a dozen lines of code, with no need to install Microsoft Excel.

Preparations

Before you start coding, install the required dependency library:

pip install Spire.XLS
Enter fullscreen mode Exit fullscreen mode

Spire.XLS for Python is a powerful Excel manipulation library that supports reading, writing, conversion, and many other operations, without relying on any local Excel components.

Complete Code Implementation

Below is a complete conversion script covering the three core steps: loading, styling, and exporting:

from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load the CSV file (parameters: file path, delimiter, start row, start column)
workbook.LoadFromFile("sample.csv", ",", 1, 1)

# Set page scaling to ensure content fits on one page
workbook.ConverterSetting.SheetFitToPage = True

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

# Auto-fit each column to prevent content from being truncated
i = 1
while i < sheet.Columns.Length:
    sheet.AutoFitColumn(i)
    i += 1

# Export to PDF
workbook.SaveToFile("CSVToPDF.pdf", FileFormat.PDF)
workbook.Dispose()
Enter fullscreen mode Exit fullscreen mode

Key Steps Explained

1. Loading the CSV File

Workbook is the core class for operations. The LoadFromFile method not only takes the file path but also allows you to specify the delimiter, starting row, and starting column for reading. For example, ",", 1, 1 means using a comma as the delimiter and starting reading from the first row and first column. If your CSV file uses tabs or semicolons as delimiters, simply replace with "\t" or ";".

2. Fitting Everything on One Page

workbook.ConverterSetting.SheetFitToPage = True is an easily overlooked yet critical setting. Without this, when the table has many columns, the exported PDF may split the content across multiple pages, requiring you to flip back and forth while reading—which is quite inconvenient. When enabled, the PDF page automatically scales to ensure all columns are fully displayed on a single page.

3. Auto-Fitting Column Widths

By calling sheet.AutoFitColumn(i) in a loop, each column's width is automatically adjusted based on the longest text content in that column. This prevents text from overlapping or displaying as "####", and makes the table look cleaner and more professional.

4. Exporting to PDF

Finally, call SaveToFile with FileFormat.PDF specified to generate the PDF file. The Dispose method is used to release resources—a good habit to cultivate.

Further Styling the Table

The example above already meets basic needs, but if you want the PDF to look more polished, Spire.XLS offers additional customization options. For example, you can set fonts, font sizes, alignment, or adjust page orientation:

# Set global font and font size
sheet.AllocatedRange.Style.Font.FontName = "Arial"
sheet.AllocatedRange.Style.Font.Size = 14

# Set horizontal center alignment
sheet.AllocatedRange.Style.HorizontalAlignment = HorizontalAlignType.Center

# Adjust page orientation to landscape
sheet.PageSetup.Orientation = PageOrientationType.Landscape
Enter fullscreen mode Exit fullscreen mode

These settings make the exported PDF more suitable for formal documentation requirements.

Use Cases

This solution is particularly well-suited for the following scenarios:

  • Batch report generation : Periodically export CSVs from databases and automatically convert them to PDFs for archiving.
  • Data delivery : Provide clients or partners with fixed-format data documents to avoid layout issues caused by different software versions.
  • Servers without Excel : Spire.XLS does not depend on local Excel and can run stably on Linux servers.

Summary

With Spire.XLS for Python, you can convert CSV to PDF in just a dozen lines of code while maintaining flexible control over table styling. The combination of SheetFitToPage and AutoFitColumn is key to ensuring a clean and polished output page. If you're troubled by CSV's "plain" appearance, give this solution a try.

Top comments (0)