Python PyPDF2 – Write PDF metadata

In this post we will be creating a Python script that will write metadata to a PDF file, to do this we will be using the PDF reader from the PyPDF2 library. The PyPDF2 is a Python library that enables users to perform various operations on PDF documents. It provides a range of functions for reading, editing, and manipulating PDF files, such as merging and splitting PDFs, extracting text and images, and encrypting and decrypting content.

See the sample of Python code below where we utilize the PyPDF2 module to write metadata. We start by reading the contents of the PDF file and write it to a new, along with our metadata included. In this example we are adding an ‘Author’ and ‘Title’.

from PyPDF2 import PdfReader,PdfWriter

reader = PdfReader("file.pdf")
writer = PdfWriter()

for page in reader.pages:
    writer.add_page(page)

writer.add_metadata(
    {
        "/Author": "Scriptopia",
        "/Title": "SomePDFTitle",
    }
)

with open("meta_file.pdf", "wb") as f:
    writer.write(f)

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply