reportlab
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReportLab PDF Generation
ReportLab PDF生成
Overview
概述
ReportLab is a powerful Python library for programmatic PDF generation. Create anything from simple documents to complex reports with tables, charts, images, and interactive forms.
Two main approaches:
- Canvas API (low-level): Direct drawing with coordinate-based positioning - use for precise layouts
- Platypus (high-level): Flowing document layout with automatic page breaks - use for multi-page documents
Core capabilities:
- Text with rich formatting and custom fonts
- Tables with complex styling and cell spanning
- Charts (bar, line, pie, area, scatter)
- Barcodes and QR codes (Code128, EAN, QR, etc.)
- Images with transparency
- PDF features (links, bookmarks, forms, encryption)
ReportLab是一个功能强大的Python库,用于以编程方式生成PDF。你可以创建从简单文档到包含表格、图表、图片和交互式表单的复杂报告等各类文档。
两种主要使用方式:
- Canvas API(底层):基于坐标定位的直接绘图方式——适用于精准布局
- Platypus(高层):支持自动分页的流式文档布局——适用于多页文档
核心功能:
- 支持富格式文本与自定义字体
- 具备复杂样式和单元格合并功能的表格
- 图表(柱状图、折线图、饼图、面积图、散点图)
- 条形码与二维码(Code128、EAN、QR等)
- 支持透明效果的图片
- PDF高级功能(链接、书签、表单、加密)
Choosing the Right Approach
选择合适的使用方式
Use Canvas API when:
当以下情况时使用Canvas API:
- Creating labels, business cards, certificates
- Precise positioning is critical (x, y coordinates)
- Single-page documents or simple layouts
- Drawing graphics, shapes, and custom designs
- Adding barcodes or QR codes at specific locations
- 创建标签、名片、证书
- 精准定位至关重要(使用x、y坐标)
- 单页文档或简单布局
- 绘制图形、形状和自定义设计
- 在特定位置添加条形码或二维码
Use Platypus when:
当以下情况时使用Platypus:
- Creating multi-page documents (reports, articles, books)
- Content should flow automatically across pages
- Need headers/footers that repeat on each page
- Working with paragraphs that can split across pages
- Building complex documents with table of contents
- 创建多页文档(报告、文章、书籍)
- 内容需要自动跨页流式排列
- 需要在每页重复显示页眉/页脚
- 处理可跨页拆分的段落
- 构建包含目录的复杂文档
Use Both when:
当以下情况时结合使用两者:
- Complex reports need both flowing content AND precise positioning
- Adding headers/footers to Platypus documents (use callback with Canvas)
onPage - Embedding custom graphics (Canvas) within flowing documents (Platypus)
- 复杂报告既需要流式内容,又需要精准定位
- 为Platypus文档添加页眉/页脚(结合回调与Canvas)
onPage - 在流式文档(Platypus)中嵌入自定义图形(Canvas)
Quick Start Examples
快速入门示例
Simple Canvas Document
简单Canvas文档
python
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch
c = canvas.Canvas("output.pdf", pagesize=letter)
width, height = letterpython
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch
c = canvas.Canvas("output.pdf", pagesize=letter)
width, height = letterDraw text
Draw text
c.setFont("Helvetica-Bold", 24)
c.drawString(inch, height - inch, "Hello ReportLab!")
c.setFont("Helvetica-Bold", 24)
c.drawString(inch, height - inch, "Hello ReportLab!")
Draw a rectangle
Draw a rectangle
c.setFillColorRGB(0.2, 0.4, 0.8)
c.rect(inch, 5inch, 4inch, 2*inch, fill=1)
c.setFillColorRGB(0.2, 0.4, 0.8)
c.rect(inch, 5inch, 4inch, 2*inch, fill=1)
Save
Save
c.showPage()
c.save()
undefinedc.showPage()
c.save()
undefinedSimple Platypus Document
简单Platypus文档
python
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
doc = SimpleDocTemplate("output.pdf", pagesize=letter)
story = []
styles = getSampleStyleSheet()python
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
doc = SimpleDocTemplate("output.pdf", pagesize=letter)
story = []
styles = getSampleStyleSheet()Add content
Add content
story.append(Paragraph("Document Title", styles['Title']))
story.append(Spacer(1, 0.2*inch))
story.append(Paragraph("This is body text with <b>bold</b> and <i>italic</i>.", styles['BodyText']))
story.append(Paragraph("Document Title", styles['Title']))
story.append(Spacer(1, 0.2*inch))
story.append(Paragraph("This is body text with <b>bold</b> and <i>italic</i>.", styles['BodyText']))
Build PDF
Build PDF
doc.build(story)
undefineddoc.build(story)
undefinedCommon Tasks
常见任务
Creating Tables
创建表格
Tables work with both Canvas (via Drawing) and Platypus (as Flowables):
python
from reportlab.platypus import Table, TableStyle
from reportlab.lib import colors
from reportlab.lib.units import inch表格可同时用于Canvas(通过Drawing)和Platypus(作为Flowables):
python
from reportlab.platypus import Table, TableStyle
from reportlab.lib import colors
from reportlab.lib.units import inchDefine data
Define data
data = [
['Product', 'Q1', 'Q2', 'Q3', 'Q4'],
['Widget A', '100', '150', '130', '180'],
['Widget B', '80', '120', '110', '160'],
]
data = [
['Product', 'Q1', 'Q2', 'Q3', 'Q4'],
['Widget A', '100', '150', '130', '180'],
['Widget B', '80', '120', '110', '160'],
]
Create table
Create table
table = Table(data, colWidths=[2inch, 1inch, 1inch, 1inch, 1*inch])
table = Table(data, colWidths=[2inch, 1inch, 1inch, 1inch, 1*inch])
Apply styling
Apply styling
style = TableStyle([
# Header row
('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
# Data rows
('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.lightgrey]),
('GRID', (0, 0), (-1, -1), 1, colors.black),])
table.setStyle(style)
style = TableStyle([
# Header row
('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
# Data rows
('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.lightgrey]),
('GRID', (0, 0), (-1, -1), 1, colors.black),])
table.setStyle(style)
Add to Platypus story
Add to Platypus story
story.append(table)
story.append(table)
Or draw on Canvas
Or draw on Canvas
table.wrapOn(c, width, height)
table.drawOn(c, x, y)
**Detailed table reference:** See `references/tables_reference.md` for cell spanning, borders, alignment, and advanced styling.table.wrapOn(c, width, height)
table.drawOn(c, x, y)
**详细表格参考:** 有关单元格合并、边框、对齐方式和高级样式,请查看`references/tables_reference.md`。Creating Charts
创建图表
Charts use the graphics framework and can be added to both Canvas and Platypus:
python
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.lib import colors图表使用图形框架,可添加到Canvas和Platypus中:
python
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.lib import colorsCreate drawing
Create drawing
drawing = Drawing(400, 200)
drawing = Drawing(400, 200)
Create chart
Create chart
chart = VerticalBarChart()
chart.x = 50
chart.y = 50
chart.width = 300
chart.height = 125
chart = VerticalBarChart()
chart.x = 50
chart.y = 50
chart.width = 300
chart.height = 125
Set data
Set data
chart.data = [[100, 150, 130, 180, 140]]
chart.categoryAxis.categoryNames = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5']
chart.data = [[100, 150, 130, 180, 140]]
chart.categoryAxis.categoryNames = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5']
Style
Style
chart.bars[0].fillColor = colors.blue
chart.valueAxis.valueMin = 0
chart.valueAxis.valueMax = 200
chart.bars[0].fillColor = colors.blue
chart.valueAxis.valueMin = 0
chart.valueAxis.valueMax = 200
Add to drawing
Add to drawing
drawing.add(chart)
drawing.add(chart)
Use in Platypus
Use in Platypus
story.append(drawing)
story.append(drawing)
Or render directly to PDF
Or render directly to PDF
from reportlab.graphics import renderPDF
renderPDF.drawToFile(drawing, 'chart.pdf', 'Chart Title')
**Available chart types:** Bar (vertical/horizontal), Line, Pie, Area, Scatter
**Detailed charts reference:** See `references/charts_reference.md` for all chart types, styling, legends, and customization.from reportlab.graphics import renderPDF
renderPDF.drawToFile(drawing, 'chart.pdf', 'Chart Title')
**支持的图表类型:** 柱状图(垂直/水平)、折线图、饼图、面积图、散点图
**详细图表参考:** 有关所有图表类型、样式、图例和自定义设置,请查看`references/charts_reference.md`。Adding Barcodes and QR Codes
添加条形码和二维码
python
from reportlab.graphics.barcode import code128
from reportlab.graphics.barcode.qr import QrCodeWidget
from reportlab.graphics.shapes import Drawing
from reportlab.graphics import renderPDFpython
from reportlab.graphics.barcode import code128
from reportlab.graphics.barcode.qr import QrCodeWidget
from reportlab.graphics.shapes import Drawing
from reportlab.graphics import renderPDFCode128 barcode (general purpose)
Code128 barcode (general purpose)
barcode = code128.Code128("ABC123456789", barHeight=0.5*inch)
barcode = code128.Code128("ABC123456789", barHeight=0.5*inch)
On Canvas
On Canvas
barcode.drawOn(c, x, y)
barcode.drawOn(c, x, y)
QR Code
QR Code
qr = QrCodeWidget("https://example.com")
qr.barWidth = 2inch
qr.barHeight = 2inch
qr = QrCodeWidget("https://example.com")
qr.barWidth = 2inch
qr.barHeight = 2inch
Wrap in Drawing for Platypus
Wrap in Drawing for Platypus
d = Drawing()
d.add(qr)
story.append(d)
**Supported formats:** Code128, Code39, EAN-13, EAN-8, UPC-A, ISBN, QR, Data Matrix, and 20+ more
**Detailed barcode reference:** See `references/barcodes_reference.md` for all formats and usage examples.d = Drawing()
d.add(qr)
story.append(d)
**支持的格式:** Code128、Code39、EAN-13、EAN-8、UPC-A、ISBN、QR码、Data Matrix等20余种格式
**详细条形码参考:** 有关所有格式和使用示例,请查看`references/barcodes_reference.md`。Working with Text and Fonts
文本与字体处理
python
from reportlab.platypus import Paragraph
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_JUSTIFYpython
from reportlab.platypus import Paragraph
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_JUSTIFYCreate custom style
Create custom style
custom_style = ParagraphStyle(
'CustomStyle',
fontSize=12,
leading=14, # Line spacing
alignment=TA_JUSTIFY,
spaceAfter=10,
textColor=colors.black,
)
custom_style = ParagraphStyle(
'CustomStyle',
fontSize=12,
leading=14, # Line spacing
alignment=TA_JUSTIFY,
spaceAfter=10,
textColor=colors.black,
)
Paragraph with inline formatting
Paragraph with inline formatting
text = """
This paragraph has <b>bold</b>, <i>italic</i>, and <u>underlined</u> text.
You can also use <font color="blue">colors</font> and <font size="14">different sizes</font>.
Chemical formula: H<sub>2</sub>O, Einstein: E=mc<sup>2</sup>
"""
para = Paragraph(text, custom_style)
story.append(para)
**Using custom fonts:**
```python
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFonttext = """
This paragraph has <b>bold</b>, <i>italic</i>, and <u>underlined</u> text.
You can also use <font color="blue">colors</font> and <font size="14">different sizes</font>.
Chemical formula: H<sub>2</sub>O, Einstein: E=mc<sup>2</sup>
"""
para = Paragraph(text, custom_style)
story.append(para)
**使用自定义字体:**
```python
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFontRegister TrueType font
Register TrueType font
pdfmetrics.registerFont(TTFont('CustomFont', 'CustomFont.ttf'))
pdfmetrics.registerFont(TTFont('CustomFont', 'CustomFont.ttf'))
Use in Canvas
Use in Canvas
c.setFont('CustomFont', 12)
c.setFont('CustomFont', 12)
Use in Paragraph style
Use in Paragraph style
style = ParagraphStyle('Custom', fontName='CustomFont', fontSize=12)
**Detailed text reference:** See `references/text_and_fonts.md` for paragraph styles, font families, Asian languages, Greek letters, and formatting.style = ParagraphStyle('Custom', fontName='CustomFont', fontSize=12)
**详细文本参考:** 有关段落样式、字体族、亚洲语言、希腊字母和格式设置,请查看`references/text_and_fonts.md`。Adding Images
添加图片
python
from reportlab.platypus import Image
from reportlab.lib.units import inchpython
from reportlab.platypus import Image
from reportlab.lib.units import inchIn Platypus
In Platypus
img = Image('photo.jpg', width=4inch, height=3inch)
story.append(img)
img = Image('photo.jpg', width=4inch, height=3inch)
story.append(img)
Maintain aspect ratio
Maintain aspect ratio
img = Image('photo.jpg', width=4inch, height=3inch, kind='proportional')
img = Image('photo.jpg', width=4inch, height=3inch, kind='proportional')
In Canvas
In Canvas
c.drawImage('photo.jpg', x, y, width=4inch, height=3inch)
c.drawImage('photo.jpg', x, y, width=4inch, height=3inch)
With transparency (mask white background)
With transparency (mask white background)
c.drawImage('logo.png', x, y, mask=[255,255,255,255,255,255])
undefinedc.drawImage('logo.png', x, y, mask=[255,255,255,255,255,255])
undefinedCreating Forms
创建表单
python
from reportlab.pdfgen import canvas
from reportlab.lib.colors import black, white, lightgrey
c = canvas.Canvas("form.pdf")python
from reportlab.pdfgen import canvas
from reportlab.lib.colors import black, white, lightgrey
c = canvas.Canvas("form.pdf")Text field
Text field
c.acroForm.textfield(
name="name",
tooltip="Enter your name",
x=100, y=700,
width=200, height=20,
borderColor=black,
fillColor=lightgrey,
forceBorder=True
)
c.acroForm.textfield(
name="name",
tooltip="Enter your name",
x=100, y=700,
width=200, height=20,
borderColor=black,
fillColor=lightgrey,
forceBorder=True
)
Checkbox
Checkbox
c.acroForm.checkbox(
name="agree",
x=100, y=650,
size=20,
buttonStyle='check',
checked=False
)
c.acroForm.checkbox(
name="agree",
x=100, y=650,
size=20,
buttonStyle='check',
checked=False
)
Dropdown
Dropdown
c.acroForm.choice(
name="country",
x=100, y=600,
width=150, height=20,
options=[("United States", "US"), ("Canada", "CA")],
forceBorder=True
)
c.save()
**Detailed PDF features reference:** See `references/pdf_features.md` for forms, links, bookmarks, encryption, and metadata.c.acroForm.choice(
name="country",
x=100, y=600,
width=150, height=20,
options=[("United States", "US"), ("Canada", "CA")],
forceBorder=True
)
c.save()
**详细PDF功能参考:** 有关表单、链接、书签、加密和元数据,请查看`references/pdf_features.md`。Headers and Footers
页眉与页脚
For Platypus documents, use page callbacks:
python
from reportlab.platypus import BaseDocTemplate, PageTemplate, Frame
def add_header_footer(canvas, doc):
"""Called on each page"""
canvas.saveState()
# Header
canvas.setFont('Helvetica', 9)
canvas.drawString(inch, height - 0.5*inch, "Document Title")
# Footer
canvas.drawRightString(width - inch, 0.5*inch, f"Page {doc.page}")
canvas.restoreState()对于Platypus文档,使用页面回调函数:
python
from reportlab.platypus import BaseDocTemplate, PageTemplate, Frame
def add_header_footer(canvas, doc):
"""Called on each page"""
canvas.saveState()
# Header
canvas.setFont('Helvetica', 9)
canvas.drawString(inch, height - 0.5*inch, "Document Title")
# Footer
canvas.drawRightString(width - inch, 0.5*inch, f"Page {doc.page}")
canvas.restoreState()Set up document
Set up document
doc = BaseDocTemplate("output.pdf")
frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal')
template = PageTemplate(id='normal', frames=[frame], onPage=add_header_footer)
doc.addPageTemplates([template])
doc = BaseDocTemplate("output.pdf")
frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal')
template = PageTemplate(id='normal', frames=[frame], onPage=add_header_footer)
doc.addPageTemplates([template])
Build with story
Build with story
doc.build(story)
undefineddoc.build(story)
undefinedHelper Scripts
辅助脚本
This skill includes helper scripts for common tasks:
本技能包含用于常见任务的辅助脚本:
Quick Document Generator
快速文档生成器
Use for rapid document creation:
scripts/quick_document.pypython
from scripts.quick_document import create_simple_document, create_styled_table使用快速创建文档:
scripts/quick_document.pypython
from scripts.quick_document import create_simple_document, create_styled_tableSimple document from content blocks
Simple document from content blocks
content = [
{'type': 'heading', 'content': 'Introduction'},
{'type': 'paragraph', 'content': 'Your text here...'},
{'type': 'bullet', 'content': 'Bullet point'},
]
create_simple_document("output.pdf", "My Document", content_blocks=content)
content = [
{'type': 'heading', 'content': 'Introduction'},
{'type': 'paragraph', 'content': 'Your text here...'},
{'type': 'bullet', 'content': 'Bullet point'},
]
create_simple_document("output.pdf", "My Document", content_blocks=content)
Styled tables with presets
Styled tables with presets
data = [['Header1', 'Header2'], ['Data1', 'Data2']]
table = create_styled_table(data, style_name='striped') # 'default', 'striped', 'minimal', 'report'
undefineddata = [['Header1', 'Header2'], ['Data1', 'Data2']]
table = create_styled_table(data, style_name='striped') # 'default', 'striped', 'minimal', 'report'
undefinedTemplate Examples
模板示例
Complete working examples in :
assets/assets/Invoice Template
发票模板
assets/invoice_template.py- Company and client information
- Itemized table with calculations
- Tax and totals
- Terms and notes
- Logo placement
python
from assets.invoice_template import create_invoice
create_invoice(
filename="invoice.pdf",
invoice_number="INV-2024-001",
invoice_date="January 15, 2024",
due_date="February 15, 2024",
company_info={'name': 'Acme Corp', 'address': '...', 'phone': '...', 'email': '...'},
client_info={'name': 'Client Name', ...},
items=[
{'description': 'Service', 'quantity': 1, 'unit_price': 500.00},
...
],
tax_rate=0.08,
notes="Thank you for your business!",
)assets/invoice_template.py- 公司与客户信息
- 带计算功能的明细表格
- 税费与总计
- 条款与备注
- Logo放置
python
from assets.invoice_template import create_invoice
create_invoice(
filename="invoice.pdf",
invoice_number="INV-2024-001",
invoice_date="January 15, 2024",
due_date="February 15, 2024",
company_info={'name': 'Acme Corp', 'address': '...', 'phone': '...', 'email': '...'},
client_info={'name': 'Client Name', ...},
items=[
{'description': 'Service', 'quantity': 1, 'unit_price': 500.00},
...
],
tax_rate=0.08,
notes="Thank you for your business!",
)Report Template
报告模板
assets/report_template.py- Cover page
- Table of contents
- Multiple sections with subsections
- Charts and tables
- Headers and footers
python
from assets.report_template import create_report
report_data = {
'title': 'Quarterly Report',
'subtitle': 'Q4 2023',
'author': 'Analytics Team',
'sections': [
{
'title': 'Executive Summary',
'content': 'Report content...',
'table_data': {...},
'chart_data': {...}
},
...
]
}
create_report("report.pdf", report_data)assets/report_template.py- 封面
- 目录
- 带小节的多个章节
- 图表与表格
- 页眉与页脚
python
from assets.report_template import create_report
report_data = {
'title': 'Quarterly Report',
'subtitle': 'Q4 2023',
'author': 'Analytics Team',
'sections': [
{
'title': 'Executive Summary',
'content': 'Report content...',
'table_data': {...},
'chart_data': {...}
},
...
]
}
create_report("report.pdf", report_data)Reference Documentation
参考文档
Comprehensive API references organized by feature:
- - Low-level Canvas: drawing primitives, coordinates, transformations, state management, images, paths
references/canvas_api.md - - High-level Platypus: document templates, frames, flowables, page layouts, TOC
references/platypus_guide.md - - Text formatting: paragraph styles, inline markup, custom fonts, Asian languages, bullets, sequences
references/text_and_fonts.md - - Tables: creation, styling, cell spanning, borders, alignment, colors, gradients
references/tables_reference.md - - Charts: all chart types, data handling, axes, legends, colors, rendering
references/charts_reference.md - - Barcodes: Code128, QR codes, EAN, UPC, postal codes, and 20+ formats
references/barcodes_reference.md - - PDF features: links, bookmarks, forms, encryption, metadata, page transitions
references/pdf_features.md
按功能分类的全面API参考:
- - 底层Canvas:绘图原语、坐标、变换、状态管理、图片、路径
references/canvas_api.md - - 高层Platypus:文档模板、框架、Flowables、页面布局、目录
references/platypus_guide.md - - 文本格式:段落样式、内联标记、自定义字体、亚洲语言、项目符号、序列
references/text_and_fonts.md - - 表格:创建、样式、单元格合并、边框、对齐方式、颜色、渐变
references/tables_reference.md - - 图表:所有图表类型、数据处理、坐标轴、图例、颜色、渲染
references/charts_reference.md - - 条形码:Code128、二维码、EAN、UPC、邮政编码等20余种格式
references/barcodes_reference.md - - PDF功能:链接、书签、表单、加密、元数据、页面过渡
references/pdf_features.md
Best Practices
最佳实践
Coordinate System (Canvas)
坐标系(Canvas)
- Origin (0, 0) is lower-left corner (not top-left)
- Y-axis points upward
- Units are in points (72 points = 1 inch)
- Always specify page size explicitly
python
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch
width, height = letter
margin = inch- 原点(0, 0)位于左下角(而非左上角)
- Y轴向上延伸
- 单位为点(72点=1英寸)
- 始终显式指定页面尺寸
python
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch
width, height = letter
margin = inchTop of page
Top of page
y_top = height - margin
y_top = height - margin
Bottom of page
Bottom of page
y_bottom = margin
undefinedy_bottom = margin
undefinedChoosing Page Size
页面尺寸选择
python
from reportlab.lib.pagesizes import letter, A4, landscapepython
from reportlab.lib.pagesizes import letter, A4, landscapeUS Letter (8.5" x 11")
US Letter (8.5" x 11")
pagesize=letter
pagesize=letter
ISO A4 (210mm x 297mm)
ISO A4 (210mm x 297mm)
pagesize=A4
pagesize=A4
Landscape
Landscape
pagesize=landscape(letter)
pagesize=landscape(letter)
Custom
Custom
pagesize=(6inch, 9inch)
undefinedpagesize=(6inch, 9inch)
undefinedPerformance Tips
性能优化技巧
- Use over
drawImage()- caches images for reusedrawInlineImage() - Enable compression for large files:
canvas.Canvas("file.pdf", pageCompression=1) - Reuse styles - create once, use throughout document
- Use Forms/XObjects for repeated graphics
- 优先使用而非
drawImage()- 可缓存图片以便重复使用drawInlineImage() - 大文件启用压缩:
canvas.Canvas("file.pdf", pageCompression=1) - 复用样式 - 一次性创建,在整个文档中复用
- 使用Forms/XObjects处理重复图形
Common Patterns
常见模式
Centering text on Canvas:
python
text = "Centered Text"
text_width = c.stringWidth(text, "Helvetica", 12)
x = (width - text_width) / 2
c.drawString(x, y, text)在Canvas上居中显示文本:
python
text = "Centered Text"
text_width = c.stringWidth(text, "Helvetica", 12)
x = (width - text_width) / 2
c.drawString(x, y, text)Or use built-in
Or use built-in
c.drawCentredString(width/2, y, text)
**Page breaks in Platypus:**
```python
from reportlab.platypus import PageBreak
story.append(PageBreak())Keep content together (no split):
python
from reportlab.platypus import KeepTogether
story.append(KeepTogether([
heading,
paragraph1,
paragraph2,
]))Alternate row colors:
python
style = TableStyle([
('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.lightgrey]),
])c.drawCentredString(width/2, y, text)
**Platypus中的分页:**
```python
from reportlab.platypus import PageBreak
story.append(PageBreak())保持内容连续(不拆分):
python
from reportlab.platypus import KeepTogether
story.append(KeepTogether([
heading,
paragraph1,
paragraph2,
]))交替行颜色:
python
style = TableStyle([
('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.lightgrey]),
])Troubleshooting
故障排除
Text overlaps or disappears:
- Check Y-coordinates - remember origin is bottom-left
- Ensure text fits within page bounds
- Verify (line spacing) is greater than
leadingfontSize
Table doesn't fit on page:
- Reduce column widths
- Decrease font size
- Use landscape orientation
- Enable table splitting with
repeatRows
Barcode not scanning:
- Increase (try 0.5 inch minimum)
barHeight - Set for quiet zones
quiet=1 - Test print quality (300+ DPI recommended)
- Validate data format for barcode type
Font not found:
- Register TrueType fonts with
pdfmetrics.registerFont() - Use font family name exactly as registered
- Check font file path is correct
Images have white background:
- Use parameter to make white transparent
mask - Provide RGB range to mask:
mask=[255,255,255,255,255,255] - Or use PNG with alpha channel
文本重叠或消失:
- 检查Y坐标——记住原点在左下角
- 确保文本在页面边界内
- 验证(行间距)大于
leadingfontSize
表格无法适配页面:
- 减小列宽
- 缩小字体大小
- 使用横向布局
- 通过启用表格拆分
repeatRows
条形码无法扫描:
- 增大(建议至少0.5英寸)
barHeight - 设置添加静区
quiet=1 - 测试打印质量(推荐300+ DPI)
- 验证条形码类型对应的数据格式
字体未找到:
- 使用注册TrueType字体
pdfmetrics.registerFont() - 严格使用注册时的字体族名称
- 检查字体文件路径是否正确
图片带有白色背景:
- 使用参数将白色设为透明
mask - 提供RGB范围作为掩码:
mask=[255,255,255,255,255,255] - 或使用带Alpha通道的PNG图片
Example Workflows
示例工作流
Creating an Invoice
创建发票
- Start with invoice template from
assets/invoice_template.py - Customize company info, logo path
- Add items with descriptions, quantities, prices
- Set tax rate if applicable
- Add notes and payment terms
- Generate PDF
- 从获取发票模板
assets/invoice_template.py - 自定义公司信息、Logo路径
- 添加包含描述、数量、价格的项目
- 如有需要设置税率
- 添加备注与付款条款
- 生成PDF
Creating a Report
创建报告
- Start with report template from
assets/report_template.py - Define sections with titles and content
- Add tables for data using
create_styled_table() - Add charts using graphics framework
- Build with for TOC
doc.multiBuild(story)
- 从获取报告模板
assets/report_template.py - 定义包含标题和内容的章节
- 使用添加数据表格
create_styled_table() - 使用图形框架添加图表
- 调用生成带目录的文档
doc.multiBuild(story)
Creating a Certificate
创建证书
- Use Canvas API for precise positioning
- Load custom fonts for elegant typography
- Add border graphics or image background
- Position text elements (name, date, achievement)
- Optional: Add QR code for verification
- 使用Canvas API实现精准定位
- 加载自定义字体以实现优雅排版
- 添加边框图形或图片背景
- 定位文本元素(姓名、日期、成就)
- 可选:添加用于验证的二维码
Creating Labels with Barcodes
创建带条形码的标签
- Use Canvas with custom page size (label dimensions)
- Calculate grid positions for multiple labels per page
- Draw label content (text, images)
- Add barcode at specific position
- Use between labels or grids
showPage()
- 使用Canvas设置自定义页面尺寸(标签尺寸)
- 计算每页多个标签的网格位置
- 绘制标签内容(文本、图片)
- 在指定位置添加条形码
- 在标签或网格之间使用
showPage()
Installation
安装
bash
uv pip install reportlabbash
uv pip install reportlabFor image support
For image support
uv pip install pillow
uv pip install pillow
For charts
For charts
uv pip install reportlab[renderPM]
uv pip install reportlab[renderPM]
For barcode support (included in reportlab)
For barcode support (included in reportlab)
QR codes require: uv pip install qrcode
QR codes require: uv pip install qrcode
undefinedundefinedWhen to Use This Skill
何时使用本技能
This skill should be used when:
- Generating PDF documents programmatically
- Creating invoices, receipts, or billing documents
- Building reports with tables and charts
- Generating certificates, badges, or credentials
- Creating shipping labels or product labels with barcodes
- Designing forms or fillable PDFs
- Producing multi-page documents with consistent formatting
- Converting data to PDF format for archival or distribution
- Creating custom layouts that require precise positioning
This skill provides comprehensive guidance for all ReportLab capabilities, from simple documents to complex multi-page reports with charts, tables, and interactive elements.
当以下情况时使用本技能:
- 以编程方式生成PDF文档
- 创建发票、收据或账单文档
- 构建包含表格和图表的报告
- 生成证书、徽章或凭证
- 创建带条形码的运单或产品标签
- 设计表单或可填写PDF
- 生成格式一致的多页文档
- 将数据转换为PDF格式用于存档或分发
- 创建需要精准定位的自定义布局
本技能提供了ReportLab所有功能的全面指南,从简单文档到包含图表、表格和交互式元素的复杂多页报告均有覆盖。