laitimes

Software Testing|Generate PDF files using Python

author:Tester: Mueller
Software Testing|Generate PDF files using Python

Brief introduction

PDF (Portable Document Format) is a commonly used document format with cross-platform compatibility, fidelity, security, and interactivity. Contracts, reports, papers, etc., which we work in our daily lives, are often in PDF format to ensure that documents maintain a consistent appearance when viewed across different operating systems (e.g., Windows, Mac, Linux) and devices. This article will introduce the most basic operations of PDF: Create a PDF document with Python and insert a table.

Environment preparation

Before you can begin, you need to install the Python library for generating PDF files. The two main libraries are PyPDF2 and reportlab. We can use pip to install them:

pythonpip install PyPDF2
pip install reportlab
           

Use PyPDF2 to generate PDF files

PyPDF2 is a library for working with PDF files, including merging, splitting, and creating PDF files. Here's an example of how to create a simple PDF file and add text using PyPDF2:

pythonimport PyPDF2

# 创建一个PDF文件
pdf = PyPDF2.PdfFileWriter()

# 创建一个页面
page = pdf.addPage(PyPDF2.PdfFileReader("blank.pdf").getPage(0))

# 添加文本
page.mergeTranslatedPage(PyPDF2.PdfFileReader("source.pdf").getPage(0), tx=100, ty=300)

# 保存生成的PDF文件
with open("output.pdf", "wb") as output_pdf:
    pdf.write(output_pdf)
           

In this example, we first create a PDF file object, then add a page and add text to that page.

Use reportlab to generate PDF files

reportlab is a library for creating complex PDF documents, adding text, images, tables, and more. Here's an example of how to use reportlab to create a PDF file with text and images:

pythonfrom reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

# 创建PDF文件
c = canvas.Canvas("reportlab_example.pdf", pagesize=letter)

# 添加文本
c.drawString(100, 750, "Hello, World!")

# 添加图像
c.drawImage("德甲.png", 100, 600, width=200, height=100)

# 保存生成的PDF文件
c.save()

           

The generated PDF file is shown in the following figure:

Software Testing|Generate PDF files using Python

In this example, we use reportlab to create a PDF file and add text and images. We can customize the layout and content of the document as needed.

Use ReportLab to create a table

reportlab can also help us create tables in PDFs, here is an example of how to create a simple form:

pythonfrom reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from reportlab.lib import colors

# 创建PDF文件
doc = SimpleDocTemplate("table_example.pdf", pagesize=letter)

# 创建数据
data = [['Name', 'Age', 'Country'],
        ['Alice', 25, 'USA'],
        ['Bob', 30, 'Canada'],
        ['Charlie', 22, 'UK']]

# 创建表格
table = Table(data)

# 添加样式
style = TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.grey),
                    ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
                    ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
                    ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
                    ('GRID', (0, 0), (-1, -1), 1, colors.black)])

table.setStyle(style)

# 构建PDF文件
elements = []
elements.append(table)
doc.build(elements)

           

The generated PDF is shown in the figure below:

Software Testing|Generate PDF files using Python

summary

This article mainly introduces the steps to use Python to generate PDF files, if we want to add more content to PDFs, we recommend using reportlab to create PDF files.

Hogwarts Test & Development Academy|Free learning materials to help you get twice the result with half the effort! - Official Account - A community of testers

Read on