Python Python Free

Python: Merge Multiple PDFs into One

Merge several PDF files into one with Python in a few lines — keep the page order you choose.

15 lines · Updated Nov 26, 2026

Preview of Python: Merge Multiple PDFs into One
python-merge-pdfs.py
from pypdf import PdfWriter

def merge_pdfs(files, output):
    writer = PdfWriter()
    for path in files:
        writer.append(path)
    with open(output, "wb") as f:
        writer.write(f)
    print(f"Merged {len(files)} files into {output}")

if __name__ == "__main__":
    merge_pdfs(
        ["chapter1.pdf", "chapter2.pdf", "chapter3.pdf"],
        "complete-book.pdf",
    )

About this snippet

Combining PDFs is a daily task in many offices — monthly invoices, scanned pages, report chapters — and online PDF tools mean uploading private documents to someone else's server. This snippet merges any number of PDFs into one file locally with Python and the pypdf library, in the order you choose.

How it works

  1. It collects the PDF files to merge, usually from a folder, sorted by name.
  2. A PDF writer object appends the pages of each file in turn.
  3. The combined document is written to a new output file; the originals stay untouched.

How to use it

  1. Install the library: pip install pypdf.
  2. Put the files in one folder and name them so they sort in the right order (01-cover.pdf, 02-report.pdf…).
  3. Run the script and open the merged file to check the page order.

Customize it

  • Merge only certain pages by specifying page ranges.
  • Add bookmarks (outline items) for each original file so readers can jump between sections.
  • Process sub-folders to create one merged PDF per client or per month.

Common problems

  • Encrypted PDFs: files with a password must be decrypted first with the correct password.
  • Huge output file: scanned PDFs are large images; compress them separately if needed.
  • Wrong order: 10.pdf sorts before 2.pdf as text — use zero-padded numbers.

FAQ

Is my data uploaded anywhere? No — everything runs on your own computer.

Related: Extract text from a PDF · 10 Python automation projects

How to install

Install with pip install pypdf. List the files in the order you want them merged, then run the script. For very large PDFs, merge in smaller batches.

Share this snippet

See all
Chat with us