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.
Python code
30 linesimport 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
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
- Use pypdf's PdfWriter to merge pages properly: from pypdf import PdfWriter; writer.append(bytes) etc.
- 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
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.