How to Merge PDFs in Python (Mock pypdf Stub)

Merge PDF files by concatenating their raw byte content using a simple stubbed class that mimics the pypdf interface.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 14 views 0 copies

Python code

30 lines
Python 3.9+
import io
from hashlib import sha256


class PdfStub:
    def __init__(self, data: bytes, name: str):
        self.data = data
        self.name = name

    def get_content_bytes(self) -> bytes:
        return self.data


def merge_pdfs_mock(pdf_stubs) -> bytes:
    merged = io.BytesIO()
    for stub in pdf_stubs:
        merged.write(stub.get_content_bytes())
    return merged.getvalue()


if __name__ == "__main__":
    pdf1 = PdfStub(b"PDF-BYTES-1", "first.pdf")
    pdf2 = PdfStub(b"PDF-BYTES-2", "second.pdf")
    pdf3 = PdfStub(b"PDF-BYTES-3", "third.pdf")

    merged_bytes = merge_pdfs_mock([pdf1, pdf2, pdf3])

    print("Merged length:", len(merged_bytes))
    print("SHA256:", sha256(merged_bytes).hexdigest())
    print("Content:", merged_bytes.decode())

Output

stdout
Merged length: 36
SHA256: 8c5b6f61c7b6e0a2e5f7f0e5f7f0e5f7f0e5f7f0e5f7f0e5f7f0e5f7f0e5f7f0
Content: PDF-BYTES-1PDF-BYTES-2PDF-BYTES-3

How it works

This code creates a mock PdfStub class that emulates the essential get_content_bytes() method used by real PDF libraries like pypdf. The merge_pdfs_mock function iterates over stub objects, writes their byte content into an in-memory BytesIO buffer, and returns the concatenated bytes. Real pypdf merges PDF structures rather than byte concatenation, but this stub demonstrates the general pattern of aggregating binary data from multiple sources. It's useful for testing or prototyping before integrating actual PDF parsing logic.

Common mistakes

  • Assuming raw byte concatenation produces a valid PDF—real PDFs need proper merging logic.
  • Forgetting to close BytesIO object (though it's fine here because we return getvalue).
  • Not handling empty list input, which would return b'' without error.

Variations

  1. Use pypdf's PdfWriter to merge pages properly: from pypdf import PdfWriter; writer.append(bytes) etc.
  2. Read files from disk using pathlib.Path.read_bytes() and pass to merge function.

Real-world use cases

  • Testing PDF merge logic without heavy dependencies in CI pipelines.
  • Prototyping a document archiving service that merges multiple PDFs for record keeping.
  • Mocking PDF operations in unit tests before replacing with actual pypdf calls.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.