The PdfFileWriter Class: PyPDF2 documentation

Working with PDF files in Python is a common task, especially when dealing with reports, invoices, or legal documents. I’ve found the PdfFileWriter class from the PyPDF2 library to be a powerful tool for creating and modifying PDF files programmatically.

In this article, I’ll walk you through practical examples of using PdfFileWriter in Python. Whether you want to create a new PDF, merge pages, or add attachments, I’ll show you how with clear, concise code you can use right away.

What is PdfFileWriter?

PdfFileWriter is a class in PyPDF2 that allows you to create new PDF files or modify existing ones by writing pages, adding metadata, or encrypting files. It acts as a container to collect pages and save them as a new PDF.

While working on projects like generating customized invoices for clients in the US or compiling reports, I often use PdfFileWriter to automate PDF creation and manipulation. It saves time and reduces manual errors.

How to Install PyPDF2

Before we dive into examples, make sure you have PyPDF2 installed:

pip install PyPDF2

This library supports Python 3 and is actively maintained.

Example 1: Create a Simple PDF from Scratch

Let me start with the most basic example, creating a new PDF and adding a blank page.

from PyPDF2 import PdfWriter

# Create a PdfWriter object
pdf_writer = PdfWriter()

# Add a blank page (width=612, height=792 points, which is standard letter size)
pdf_writer.add_blank_page(width=612, height=792)

# Save the PDF to a file
with open("blank_page.pdf", "wb") as out_file:
    pdf_writer.write(out_file)

print("Blank PDF created successfully!")

You can refer to the screenshot below to see the output.

The PdfFileWriter Class

This script creates a single blank page PDF, which you can use as a template.

Example 2: Merge Pages from Existing PDFs

Often, you need to combine multiple PDFs into one. Here’s how I do it using PdfFileWriter along with PdfFileReader:

from PyPDF2 import PdfFileReader, PdfFileWriter

pdf_writer = PdfFileWriter()

# List of PDF files to merge
pdf_files = ["report_part1.pdf", "report_part2.pdf"]

for pdf_file in pdf_files:
    pdf_reader = PdfFileReader(pdf_file)
    # Add all pages from each PDF
    for page_num in range(pdf_reader.getNumPages()):
        page = pdf_reader.getPage(page_num)
        pdf_writer.addPage(page)

# Write merged PDF to a new file
with open("merged_report.pdf", "wb") as out_file:
    pdf_writer.write(out_file)

print("PDF files merged successfully!")

You can refer to the screenshot below to see the output.

The PdfFileWriter in Python

This approach comes in handy when compiling multi-part reports, for example, combining quarterly sales reports for US-based clients.

Check out Interfaces in Python

Example 3: Add Metadata to a PDF

Adding metadata like title, author, and subject helps organize and search your PDFs. Here’s how to add metadata using PdfFileWriter:

from PyPDF2 import PdfFileWriter, PdfFileReader

input_pdf = "merged_report.pdf"
output_pdf = "merged_report_with_metadata.pdf"

pdf_reader = PdfFileReader(input_pdf)
pdf_writer = PdfFileWriter()

# Copy all pages
for page_num in range(pdf_reader.getNumPages()):
    pdf_writer.addPage(pdf_reader.getPage(page_num))

# Add metadata
pdf_writer.addMetadata({
    '/Title': 'Annual Sales Report 2025',
    '/Author': 'John Doe',
    '/Subject': 'Q1-Q2 Sales Data',
    '/Creator': 'Python PdfFileWriter',
})

with open(output_pdf, "wb") as out_file:
    pdf_writer.write(out_file)

print("Metadata added to PDF successfully!")

This is useful when sharing PDFs with colleagues or clients, making your documents professional and easy to identify.

Example 4: Encrypt PDF with a Password

Security is vital when sharing sensitive documents. You can encrypt a PDF with a password like this:

from PyPDF2 import PdfFileWriter, PdfFileReader

input_pdf = "merged_report_with_metadata.pdf"
output_pdf = "encrypted_report.pdf"
password = "SecurePass123"

pdf_reader = PdfFileReader(input_pdf)
pdf_writer = PdfFileWriter()

# Copy pages
for page_num in range(pdf_reader.getNumPages()):
    pdf_writer.addPage(pdf_reader.getPage(page_num))

# Encrypt PDF
pdf_writer.encrypt(user_pwd=password, owner_pwd=None, use_128bit=True)

with open(output_pdf, "wb") as out_file:
    pdf_writer.write(out_file)

print(f"PDF encrypted successfully with password: {password}")

This method ensures only authorized users in your organization can open the PDF.

Example 5: Add an Attachment to a PDF

Sometimes, you might want to attach files like spreadsheets or images inside a PDF. Here’s a VBA-free way I use to add attachments:

from PyPDF2 import PdfFileWriter, PdfFileReader

pdf_writer = PdfFileWriter()
pdf_reader = PdfFileReader("blank_page.pdf")

# Copy existing pages
for page_num in range(pdf_reader.getNumPages()):
    pdf_writer.addPage(pdf_reader.getPage(page_num))

# Note: PyPDF2 doesn't support adding file attachments directly.
# However, you can add attachments using other libraries like pikepdf or PyMuPDF.
# For simplicity, here’s a placeholder to explain this step.

print("Adding attachments requires other libraries such as pikepdf or PyMuPDF.")

While PdfFileWriter doesn’t natively support attachments, but combining it with other libraries can achieve this.

Read Command Errored Out with Exit Status 1 in Python

Tips from My Experience

  • Always open PDF files in binary mode ("rb" or "wb") to avoid corruption.
  • Use PdfFileReader to inspect existing PDFs before modifying.
  • Save your work frequently, especially when working with large PDFs.
  • Test your PDFs on multiple readers to ensure compatibility.
  • For complex manipulations like annotations or attachments, consider complementing PyPDF2 with other libraries.

Using PdfFileWriter has streamlined many workflows in my projects involving US-based clients, from generating contracts to compiling financial reports. The flexibility it offers makes it a go-to tool in my Python toolkit.

I hope these examples help you get started with PDF manipulation in Python.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.