ReportLab Toolkit
The ReportLab Toolkit is an open-source Python library for generating high-quality PDF documents and graphics. It provides both low-level APIs for precise control over PDF elements and a higher-level framework (PLATYPUS) for creating complex, structured documents with flowables like paragraphs and tables. Currently at version 4.4.10, ReportLab is actively maintained with regular updates and is widely used for dynamic, data-driven report generation, including by Wikipedia for its 'Download as PDF' feature.
Warnings
- breaking ReportLab 3.0 (released 2014) introduced significant internal rewrites for Python 3 compatibility and consistent Unicode/bytes handling. While API changes were minimized, older code might encounter unexpected behavior related to string encoding.
- breaking Reusing flowable objects (e.g., `Paragraph`, `Table`) in multiple document builds or pages without re-instantiating them can lead to `LayoutError` exceptions. ReportLab modifies these objects in place during the layout process, which is not reset for subsequent uses.
- gotcha The default coordinate system in ReportLab's `canvas` module has its origin (0,0) at the bottom-left corner of the page. This is different from many other graphics libraries where the origin is top-left, and can lead to incorrect positioning if not accounted for.
- gotcha Optional C extensions (e.g., `rl_accel`, `rl_renderpm`) are crucial for optimal performance, especially with bitmap image processing and complex graphics. If these are not installed (often requiring a C compiler during `pip install`), ReportLab will fall back to slower pure-Python implementations or lack certain features.
Install
-
pip install reportlab
Imports
- SimpleDocTemplate
from reportlab.platypus import SimpleDocTemplate
- Paragraph
from reportlab.platypus import Paragraph
- getSampleStyleSheet
from reportlab.lib.styles import getSampleStyleSheet
- letter
from reportlab.lib.pagesizes import letter
- Canvas
from reportlab.pdfgen import canvas
- pdfgen
from reportlab.pdfgen import canvas
Quickstart
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter
def create_pdf(filename="hello_reportlab.pdf"):
doc = SimpleDocTemplate(filename, pagesize=letter)
styles = getSampleStyleSheet()
story = []
# Add a title
story.append(Paragraph("Hello, ReportLab!", styles['h1']))
story.append(Spacer(1, 0.2 * 25.4))
# Add a paragraph
long_text = "This is an example of a simple PDF document generated using the ReportLab Toolkit. It demonstrates how to use `SimpleDocTemplate` and `Paragraph` for basic text content. ReportLab provides extensive capabilities for layouts, tables, images, and graphics."
story.append(Paragraph(long_text, styles['Normal']))
# Build the PDF document
doc.build(story)
print(f"PDF created: {filename}")
if __name__ == "__main__":
create_pdf()