Python: Merge Multiple PDFs into One
Merge several PDF files into one with Python in a few lines — keep the page order you choose.
Read the text out of any PDF with Python — the first step for search, summaries and automation.
15 lines · Updated Nov 26, 2026
from pypdf import PdfReader
def extract_text(pdf_path, txt_path):
reader = PdfReader(pdf_path)
pages = []
for page in reader.pages:
pages.append(page.extract_text() or "")
text = "\n".join(pages)
with open(txt_path, "w", encoding="utf-8") as f:
f.write(text)
return text
if __name__ == "__main__":
text = extract_text("report.pdf", "report.txt")
print(f"Extracted {len(text)} characters from the PDF.")
Getting text out of PDFs is the first step for many automations: searching contracts, reading invoice totals, feeding documents to an AI summariser or importing data into a spreadsheet. This snippet extracts the text from every page of a PDF with Python and pypdf, in just a few lines.
.txt file, page by page.pip install pypdf.Text extraction only works when the PDF contains real text. A scanned document is just an image of text, so extraction returns nothing. For scans, use OCR — for example Tesseract with the pytesseract package, or an OCR-enabled PDF tool.
pdfplumber for tables.Can it extract tables? Basic text yes; for structured tables, pdfplumber or Camelot give better results.
Related: Merge PDFs · 10 Python automation projects
Install with pip install pypdf. Run the script with your PDF path. Scanned PDFs (images of text) need OCR first — this works on text-based PDFs.
Share this snippet
Merge several PDF files into one with Python in a few lines — keep the page order you choose.
Send yourself a Telegram message from Python — free alerts for scripts, servers and price trackers.
Generate a strong random password with Python using the secrets module — never use random() for passwords.