1. Basics of Adding Text and Headers to a PDF
In ReportLab, text is added using the canvas
object, which provides methods for setting fonts, colors, sizes, and text positions.
Creating a simple PDF with a header and text
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
# Create a new PDF
pdf_file = canvas.Canvas("styled_text.pdf", pagesize=A4)
width, height = A4
# Add a header
pdf_file.setFont("Helvetica-Bold", 20)
pdf_file.drawString(100, height - 100, "Sales Report")
# Add main text
pdf_file.setFont("Helvetica", 12)
pdf_file.drawString(100, height - 130, "This document contains sales information for the last quarter.")
# Save the PDF
pdf_file.save()
This code creates a PDF file containing a header and main text. We set the font and text size using the setFont()
method.
2. Text Styling and Formatting
In ReportLab, you can change the color, font, and size of the text to create stylish headers and main content. This helps structure the document and makes it more reader-friendly.
Changing Font and Text Size
ReportLab supports standard fonts like Helvetica
, Times-Roman
, and Courier
. You can specify the font style (regular, bold, or italic) and size using setFont()
.
pdf_file.setFont("Helvetica-Bold", 18) # Bold header
pdf_file.drawString(100, height - 50, "Main Header")
pdf_file.setFont("Helvetica-Oblique", 14) # Italic subheader
pdf_file.drawString(100, height - 80, "Subheader: Quarterly Highlights")
Changing Text Color
You can change the text color using the setFillColorRGB()
method, which takes RGB values between 0 and 1.
pdf_file.setFillColorRGB(0.2, 0.4, 0.6) # Blue color
pdf_file.setFont("Helvetica", 12)
pdf_file.drawString(100, height - 110, "This text is blue.")
You can also use predefined colors from reportlab.lib.colors
.
from reportlab.lib import colors
pdf_file.setFillColor(colors.red)
pdf_file.drawString(100, height - 140, "Red text")
3. Text Alignment and Multi-Line Text
If the text is long, it's better to display it in multi-line format. ReportLab provides the TextObject
class, which supports automatic line wrapping.
Multi-Line Text with TextObject
text = """
The report contains analysis of sales over the last three months.
We examine changes and their impact on the overall company growth.
"""
text_object = pdf_file.beginText(100, height - 180)
text_object.setFont("Helvetica", 12)
text_object.setFillColor(colors.darkblue)
for line in text.split("\n"):
text_object.textLine(line)
pdf_file.drawText(text_object)
This code creates a text block with multiple lines, each added to the PDF. Using TextObject
is convenient for longer text as it provides auto-formatting.
4. Using Paragraphs to Style Text
The Paragraph
class from the reportlab.platypus
module allows you to add styled text with support for HTML tags like <b>
, <i>
, and <u>
. Paragraph
also supports alignment and indentation, making it perfect for creating formatted text.
Creating Paragraphs with Paragraph
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Paragraph
# Set up PDF
doc = SimpleDocTemplate("styled_paragraphs.pdf", pagesize=A4)
styles = getSampleStyleSheet()
elements = []
# Create a paragraph with bold and italic text
text = "Sales Report
Quarterly Report 2023"
paragraph = Paragraph(text, styles["Title"])
elements.append(paragraph)
# Add main text
main_text = """
This report contains key sales data for the last quarter,
as well as an analysis of sales impact on the overall company revenue.
"""
paragraph = Paragraph(main_text, styles["BodyText"])
elements.append(paragraph)
# Build PDF
doc.build(elements)
Here we use Paragraph
to add formatted text, including HTML tags for styling (bold and italic text). getSampleStyleSheet()
provides basic styles like Title
and BodyText
, which can be modified.
5. Applying Text Styles
ReportLab allows you to create and customize your own styles, which you can use to format text. This is especially useful when creating reports that use recurring styles for headers, subheaders, and main text.
Customizing Style
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.platypus import SimpleDocTemplate, Paragraph
# Set up PDF
doc = SimpleDocTemplate("custom_styles.pdf", pagesize=A4)
elements = []
# Create a custom style
custom_style = ParagraphStyle(
name="CustomStyle",
fontName="Helvetica-Bold",
fontSize=14,
leading=18,
textColor=colors.darkgreen,
spaceAfter=10,
)
# Create a paragraph with the custom style
paragraph = Paragraph("This is a header with a custom style", custom_style)
elements.append(paragraph)
# Add main text
default_style = ParagraphStyle(
name="Default",
fontName="Helvetica",
fontSize=12,
leading=14,
textColor=colors.black,
spaceAfter=10,
)
paragraph = Paragraph("This is main text using the default style.", default_style)
elements.append(paragraph)
# Build PDF
doc.build(elements)
In this example, we create a custom style CustomStyle
with green text and a larger font, which is applied to the header.
6. Creating a Document with Headers and Text
To make the PDF document more structured, you can create a multi-page report with sections, each having its own header and styled text.
Creating a Structured Multi-Page Report
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import SimpleDocTemplate, Paragraph, PageBreak
# Set up PDF
doc = SimpleDocTemplate("structured_report.pdf", pagesize=A4)
styles = getSampleStyleSheet()
elements = []
# Style for the title
title_style = ParagraphStyle("TitleStyle", parent=styles["Title"], fontSize=18, spaceAfter=12)
# Title for the first page
title = Paragraph("Sales Report for 2023", title_style)
elements.append(title)
# Main text
main_text = """
This report provides detailed sales information for the first quarter of 2023.
Data includes regions, product categories, and key metrics.
"""
elements.append(Paragraph(main_text, styles["BodyText"]))
# New page
elements.append(PageBreak())
# Title for the second page
subtitle = Paragraph("Sales Analysis by Category", title_style)
elements.append(subtitle)
# Text for the second page
category_text = """
The second page presents data on sales by product categories.
Each category is analyzed considering sales dynamics and market changes.
"""
elements.append(Paragraph(category_text, styles["BodyText"]))
7. Formatting Text Details
Choosing Fonts and Sizes
The world of PDFs isn't just about boring documents; it's a chance to express yourself in text. While reportlab
supports many font and style options, you should keep in mind some limitations. For example, some fonts may not be supported, especially if you don't have licensed copies of them.
To set a font, we used the setFont
method, which takes the font name and its size:
c.setFont("Times-Roman", 12)
Styling Headers
You might want to highlight headers and make them stand out. You can do this by increasing font size or making it bold. Notice how we used Helvetica-Bold
for header titles.
Text Alignment
In reportlab
, text is left-aligned by default, but you can change that by using methods to calculate text width and centering it. This is useful for creating more complex text layouts on a page.
8. Real-World Applications
Here are some scenarios where adding text and headers to PDFs can be useful:
- Automated Reports. You can generate reports with dynamic text pulled from your data analyses.
- Documents with Table of Contents. Adding headers and subheaders makes it easier to navigate documents, especially larger ones.
- Personalized Documents. If your project requires generating personalized documents for participants, like certificates or invitations, automating text in PDFs will be super helpful.
Common Mistakes
Sometimes when creating PDFs, you might run into issues. A common mistake is using unsupported fonts or incorrectly placing text due to unaccounted page dimensions. Test your script with several examples to make sure the text is displayed correctly across platforms and devices.
For more information and advanced examples, check out the ReportLab Documentation and PyPDF2 GitHub, where you’ll find tons of examples and tips for usage.
GO TO FULL VERSION