Manipulating PDF Documents in Python
1 Introduction
PDF documents (.pdf files) are widely used for sharing formatted content that preserves
layout across devices. Python provides powerful libraries like PyPDF2 for basic ma-
nipulation, pdfplumber for extraction, and ReportLab for creation to programmatically
handle these documents. This allows automation of tasks like extracting data, merging
files, or generating reports without manual intervention.
This self-learning material covers basics to intermediate topics, including installation,
reading PDFs, extracting text and data, merging/splitting, creating new PDFs, and more.
Each section includes explanations, code examples, and exercises for practice.
2 Prerequisites
• Basic knowledge of Python programming.
• Python installed on your system (version 3.6 or later recommended).
3 Installation
To get started, install the necessary libraries using pip. Open your terminal or command
prompt and run:
1 pip install PyPDF2 pdfplumber reportlab
This command downloads and installs the libraries, making them available for import
in your Python scripts.
Exercise: Verify the installation by running import PyPDF2; import pdfplumber;
from [Link] import canvas in a Python interpreter. If no errors occur, youre
ready to proceed.
4 Opening and Reading PDFs
The core class in PyPDF2 is PdfReader for opening and reading existing PDFs.
4.1 Opening a PDF
1
1 import PyPDF2
2
3 # Open an existing PDF
4 with open ( ’ sample . pdf ’ , ’ rb ’) as file :
5 reader = PyPDF2 . PdfReader ( file )
6 print ( " Number of pages : " , len ( reader . pages ) )
This loads the PDF and allows access to its pages and metadata.
4.2 Extracting Metadata
1 print ( " Document info : " , reader . metadata )
Exercise: Open a sample PDF, print the number of pages and metadata, and confirm
by viewing the file properties in a PDF reader.
5 Extracting Text
Text extraction is a common task. PyPDF2 provides basic extraction, while pdfplumber
offers better layout preservation.
5.1 Basic Text Extraction with PyPDF2
1 import PyPDF2
2
3 with open ( ’ sample . pdf ’ , ’ rb ’) as file :
4 reader = PyPDF2 . PdfReader ( file )
5 page = reader . pages [0]
6 text = page . extract_text ()
7 print ( " Text from page 1: " , text [:200])
5.2 Advanced Extraction with pdfplumber
1 import pdfplumber
2
3 with pdfplumber . open ( ’ sample . pdf ’) as pdf :
4 first_page = pdf . pages [0]
5 text = first_page . extract_text ()
6 print ( " Extracted text : " , text [:200])
Exercise: Extract text from all pages of a PDF and save it to a .txt file using a loop.
6 Merging and Splitting PDFs
PyPDF2 is ideal for combining or dividing PDFs.
Page 2 of 5
6.1 Merging PDFs
1 import PyPDF2
2
3 merger = PyPDF2 . PdfMerger ()
4 merger . append ( ’ file1 . pdf ’)
5 merger . append ( ’ file2 . pdf ’)
6 with open ( ’ merged . pdf ’ , ’ wb ’) as output :
7 merger . write ( output )
8 merger . close ()
6.2 Splitting PDFs
1 import PyPDF2
2
3 with open ( ’ sample . pdf ’ , ’ rb ’) as file :
4 reader = PyPDF2 . PdfReader ( file )
5 for page_num in range ( len ( reader . pages ) ) :
6 writer = PyPDF2 . PdfWriter ()
7 writer . add_page ( reader . pages [ page_num ])
8 with open ( f ’ page_ { page_num + 1}. pdf ’ , ’ wb ’) as output :
9 writer . write ( output )
Exercise: Merge two sample PDFs and then split the result into individual pages.
7 Extracting Tables and Images
pdfplumber excels at extracting structured data.
7.1 Extracting Tables
1 import pdfplumber
2
3 with pdfplumber . open ( ’ sample . pdf ’) as pdf :
4 page = pdf . pages [0]
5 tables = page . extract_tables ()
6 if tables :
7 print ( " First table : " , tables [0])
7.2 Extracting Images
1 import pdfplumber
2 from PIL import Image
3
4 with pdfplumber . open ( ’ sample . pdf ’) as pdf :
5 page = pdf . pages [0]
6 images = page . images
7 for i , img in enumerate ( images ) :
8 cropped = page . crop (( img [ ’ x0 ’] , img [ ’ top ’] , img [ ’ x1 ’] , img [ ’
bottom ’ ]) )
9 image = cropped . to_image ( resolution =300)
10 image . save ( f ’ image_ { i }. png ’)
Page 3 of 5
Exercise: Extract tables from a PDF with data and save to CSV; extract images from
another PDF.
8 Creating New PDFs
Use ReportLab to generate PDFs from scratch.
8.1 Creating a Simple PDF
1 from reportlab . lib . pagesizes import letter
2 from reportlab . pdfgen import canvas
3
4 c = canvas . Canvas ( " new_pdf . pdf " , pagesize = letter )
5 c . drawString (100 , 750 , " Hello , World ! " )
6 c . save ()
8.2 Adding Images
1 c . drawInlineImage ( " image . png " , 100 , 600 , width =200 , height =200)
Exercise: Create a PDF with text and an inserted image, then open it to verify.
9 Advanced Topics - Encryption and Watermarks
9.1 Encrypting PDFs
1 import PyPDF2
2
3 with open ( ’ sample . pdf ’ , ’ rb ’) as file :
4 reader = PyPDF2 . PdfReader ( file )
5 writer = PyPDF2 . PdfWriter ()
6 for page in reader . pages :
7 writer . add_page ( page )
8 writer . encrypt ( ’ password ’)
9 with open ( ’ encrypted . pdf ’ , ’ wb ’) as output :
10 writer . write ( output )
9.2 Adding Watermarks
Use PyPDF2 to overlay a watermark PDF on another.
Exercise: Encrypt a PDF and try opening it with the password; add a simple water-
mark text using ReportLab and overlay.
10 Conclusion
Youve now learned the fundamentals of manipulating PDF documents in Python using
key libraries. Practice by automating tasks like data extraction or report generation.
For more advanced features, refer to the official documentation.
Page 4 of 5
11 References
This material is compiled from reliable sources for educational purposes. Experiment
with the examples and build upon them!
• PyPDF2 Documentation
• pdfplumber GitHub
• ReportLab
Page 5 of 5