Convert a CSV table to PDF with Python and ReportLab
Run this on your own computer using Python 3. Save a UTF-8, comma-delimited input.csv in the same folder as the script. The first record must contain unique, nonempty headers; quoted commas and line breaks are parsed as fields.
Before you start
- Python 3 installed. Package commands below use a local virtual environment on macOS/Linux; on Windows use .venv\Scripts\python.exe in place of .venv/bin/python.
- Keep the original CSV. These examples read the complete table into memory and create separate output files.
- Save the Python code as convert_csv.py beside input.csv.
- Install the listed package when required, then run the script. Check the generated output before using it elsewhere.
python3 -m venv .venv
.venv/bin/python -m pip install reportlabimport csv
from pathlib import Path
with open("input.csv", encoding="utf-8-sig", newline="") as source:
reader = csv.reader(source, strict=True)
headers = next(reader)
rows = list(reader)
if not headers or any(not h for h in headers) or len(set(headers)) != len(headers):
raise ValueError("Use unique, nonempty column headers")
if any(len(row) != len(headers) for row in rows):
raise ValueError("Every record must have the same number of fields as the header")
from html import escape
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, LongTable, Paragraph, TableStyle
style = getSampleStyleSheet()["BodyText"]
page = landscape(A4)
width = (page[0] - 72) / len(headers)
if width < 40:
raise ValueError("Select fewer columns for a readable PDF")
cells = [[Paragraph(escape(value).replace("\n", "<br/>"), style) for value in row] for row in [headers, *rows]]
table = LongTable(cells, colWidths=[width] * len(headers), repeatRows=1)
table.setStyle(TableStyle([("GRID", (0, 0), (-1, -1), 0.4, colors.grey), ("VALIGN", (0, 0), (-1, -1), "TOP")]))
SimpleDocTemplate("output.pdf", pagesize=page, leftMargin=36, rightMargin=36).build([table]).venv/bin/python convert_csv.pyLimits and output
- Creates a landscape A4 table with repeated headers, wrapped cells and multiple pages. The built-in font does not cover all Unicode; register a suitable licensed TrueType font for your language. Very tall rows may not fit a page. PDF is a visual report, not a lossless table storage format.
Documentation: Python CSV reader and writer; ReportLab documentation