Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

Merge Multiple PDF Files into One Document in Python

Combines multiple PDF files into a single PDF document using the PyPDF2 library's PdfMerger class.

Easy Python 3.9+ Jun 27, 2026 Files & data 1 views 0 copies

Requires third-party packages — install first
pip install PyPDF2

Python code

13 lines
Python 3.9+
import PyPDF2

def merge_pdfs(input_paths, output_path):
    merger = PyPDF2.PdfMerger()
    for path in input_paths:
        merger.append(path)
    merger.write(output_path)
    merger.close()
    print(f"Merged {len(input_paths)} PDFs into '{output_path}'.")

if __name__ == "__main__":
    files = ["file1.pdf", "file2.pdf", "file3.pdf"]
    merge_pdfs(files, "merged_output.pdf")

Output

stdout
Merged 3 PDFs into 'merged_output.pdf'.

How it works

The PdfMerger object collects pages from each input PDF by calling .append(). After all files are added, .write() saves the combined document to the specified output path. Closing the merger with .close() ensures all file handles are released and resources are cleaned up. This approach works with any number of PDFs and preserves the original page order.

Common mistakes

  • Using `PyPDF2.PdfFileMerger` which is the old, deprecated class name in recent versions.
  • Forgetting to close the merger object after writing, which can leave file handles open.
  • Passing non-existent or corrupted PDF file paths without error handling.

Variations

  1. Use `pypdf` (the successor of PyPDF2) with `from pypdf import PdfMerger` for continued support.
  2. Add page range selection with `merger.append(path, pages=(0, 10))` to merge only specific pages.

Real-world use cases

  • Combining scanned invoice PDFs into a single bundle before sending to accounting.
  • Aggregating chapter PDFs into a full e-book or report for distribution.
  • Merging multiple form submissions received as separate PDFs into one archive.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Files & data

Related tutorials and quizzes for this topic.