Convert Text to PDF in Python

The ‘reportlab‘ library can be used to convert text to PDF in Python.

If you haven’t already done so, install the reportlab library using this command:

pip install reportlab

Examples of Converting Text to PDF in Python

Example#1: Single SHORT Sentence to PDF

The following script can be used to convert a single short sentence to a PDF file:

from reportlab.pdfgen import canvas

# Example of a sentence
input_text = "This is an example of a simple sentence."

# Output PDF file
file_name = "example.pdf"

# Create a PDF document
pdf_canvas = canvas.Canvas(file_name)

# Set font and size
pdf_canvas.setFont("Courier", 12)

# Define the position of the text in the PDF
pdf_canvas.drawString(100, 750, input_text)

# Save the PDF
pdf_canvas.save()

This above script creates a simple PDF with the specified text and saves it as “example.pdf“. You can customize the font, size, and position of the text based on your needs.

The result:

This is an example of a simple sentence.

Example#2: Single LONG and Formatted Sentence to PDF

For a longer sentence that is greater than a single line, you may use the reportlab.lib.styles and reportlab.platypus modules in ReportLab to format the text using HTML-like tags:

from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Paragraph

# Example text using HTML-like tags
input_text = """<b>Hello,</b> this is an <font color='red'>example text</font>  
that will be <i>converted to PDF.</i> 
This sentence is quite long, and we want it to wrap to the next line."""

# Output PDF file
file_name = "example.pdf"

# Create a PDF document
pdf_document = SimpleDocTemplate(file_name)
pdf_elements = []

# Create a stylesheet for styling
styles = getSampleStyleSheet()

# Parse the HTML-like text into a Paragraph
paragraph = Paragraph(input_text, styles["Normal"])

# Add the Paragraph to the PDF elements
pdf_elements.append(paragraph)

# Build the PDF document
pdf_document.build(pdf_elements)

In this example, the input text includes HTML-like tags such as “<b>“, “<i>“, and “<font>“. The Paragraph class interprets these tags and applies the corresponding styling to the text when rendered in the PDF.

Adjust the HTML-like tags and styles in the input text according to your needs.

The result:

Hello, this is an example text that will be converted to PDF. This sentence is quite long, and we want it to wrap to the next line

Example#3: Multiple Paragraphs to PDF

Here is an example of a script to convert multiple paragraphs to a PDF file:

from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer

# Example text using HTML-like tags
input_text = """
<b>Paragraph 1:</b> This is the first paragraph of text.<br/>
<b>Paragraph 2:</b> Here is the second paragraph, and it continues on multiple lines as captured here. 
This part <i>is italicized.</i><br/>
<b>Paragraph 3:</b> Finally, the third paragraph completes the example.
"""

# Output PDF file
file_name = "example.pdf"

# Create a PDF document
pdf_document = SimpleDocTemplate(file_name)
pdf_elements = []

# Create a stylesheet for styling
styles = getSampleStyleSheet()

# Parse the HTML-like text into Paragraphs
paragraphs = [Paragraph(text, styles["Normal"]) for text in input_text.split("<br/>")]

# Add Paragraphs and Spacer (for spacing) to the PDF elements
for paragraph in paragraphs:
    pdf_elements.append(paragraph)
    pdf_elements.append(
        Spacer(1, 24)
    )  # Adjust the second parameter for the desired spacing

# Build the PDF document
pdf_document.build(pdf_elements)

This script creates a separate Paragraph instance for each paragraph of text separated by “<br/>“. The Spacer is used to add some space between paragraphs for better readability.

The result:

Paragraph 1: This is the first paragraph of text.

Paragraph 2: Here is the second paragraph, and it continues on multiple lines as captured here. This part is italicized.

Paragraph 3: Finally, the third paragraph completes the example.

Example#4: Add a Table

You can add a table to the PDF. Here’s an example:

from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle

# Table data
table_data = [
    ["Header 1", "Header 2", "Header 3"],
    ["Row 1, Col 1", "Row 1, Col 2", "Row 1, Col 3"],
    ["Row 2, Col 1", "Row 2, Col 2", "Row 2, Col 3"],
    ["Row 3, Col 1", "Row 3, Col 2", "Row 3, Col 3"],
]

# Output PDF file
file_name = "example.pdf"

# Create a PDF document
pdf_document = SimpleDocTemplate(file_name)
pdf_elements = []

# Create a stylesheet for styling
styles = getSampleStyleSheet()

# Add a table to the PDF elements
table = Table(table_data)
style = TableStyle([("BACKGROUND", (0, 0), (-1, 0), "#a7c7f2"),
                    ("TEXTCOLOR", (0, 0), (-1, 0), (0, 0, 0)),
                    ("ALIGN", (0, 0), (-1, -1), "CENTER"),
                    ("BOTTOMPADDING", (0, 0), (-1, 0), 12),
                    ("BACKGROUND", (0, 1), (-1, -1), "#d3e3f6"),
                    ("GRID", (0, 0), (-1, -1), 1, "#000000")])
table.setStyle(style)
pdf_elements.append(table)

# Build the PDF document
pdf_document.build(pdf_elements)

The resulted table:

Header 1Header 2Header 3
Row 1, Col 1Row 1, Col 2Row 1, Col 3
Row 2, Col 1Row 2, Col 2Row 2, Col 3
Row 3, Col 1Row 3, Col 2Row 3, Col 3

Example#5: Add a chart

This script creates a Matplotlib line chart with sample data, and saves it to a PDF file using the ReportLab library:

import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from reportlab.platypus import SimpleDocTemplate, Image
from io import BytesIO

# Line chart data
categories = ["Category 1", "Category 2", "Category 3", "Category 4", "Category 5"]
values = [0, 10, 5, 15, 8]

# Output PDF file
file_name = "example.pdf"

# Create a PDF document
pdf_document = SimpleDocTemplate(file_name)
pdf_elements = []

# Create a Matplotlib figure for the line chart
fig, ax = plt.subplots()
ax.plot(categories, values, label="Line Chart")
ax.set_xlabel("Categories")
ax.set_ylabel("Values")
ax.legend()

# Save the Matplotlib figure to a buffer
buffer = BytesIO()
FigureCanvas(fig).print_png(buffer)
plt.close()

# Convert the buffer to a ReportLab Image and embed it into the PDF
image = Image(buffer)
pdf_elements.append(image)

# Build the PDF document
pdf_document.build(pdf_elements)

Leave a Comment