PDF Merge — Python source
Combine PDF files in order, entirely in your browser — reorder, merge, download. Nothing uploads.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
# pdf-merge — merge many PDFs into one with pypdf (PdfReader/PdfWriter).
# Authored snippet mirroring src/lib/pdf-merge.ts: empty input rejected,
# encrypted vs invalid classified from the raw parse error, page count
# returned for UI display. Every page of every input is copied, in order,
# into one fresh writer — the pypdf analogue of pdf-lib's copyPages.
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import List, Literal
from pypdf import PdfReader, PdfWriter
ErrorKind = Literal["encrypted", "invalid"]
class PdfToolError(Exception):
"""Load failure: encrypted (password-protected) or invalid (unparseable)."""
def __init__(self, code: ErrorKind, message: str) -> None:
super().__init__(message)
self.code = code
def classify_load_error(msg: str | None) -> ErrorKind:
"""Pure classifier — encrypted vs invalid, from the raw error message."""
if msg and re.search(r"encrypt|password", msg, re.IGNORECASE):
return "encrypted"
return "invalid"
def _map_error(e: BaseException) -> PdfToolError:
msg = str(e)
kind = classify_load_error(msg)
if kind == "encrypted":
return PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.")
return PdfToolError("invalid", "Not a readable PDF file.")
@dataclass
class MergeResult:
bytes: bytes
page_count: int
def _load(data: bytes) -> PdfReader:
"""Parse + validate one input, refusing encrypted files (the TS
ignoreEncryption: false path)."""
reader = PdfReader(data)
if reader.is_encrypted:
raise PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.")
return reader
def merge_pdfs(docs: List[bytes]) -> MergeResult:
"""Copy every page of every input, in order, into one fresh PDF."""
if not docs:
raise PdfToolError("invalid", "Nothing to merge.")
writer = PdfWriter()
try:
for data in docs:
src = _load(data)
for page in src.pages:
writer.add_page(page)
out = writer.write_to_buffer()
except PdfToolError:
raise
except Exception as e: # parse failures -> the shared error mapping
raise _map_error(e) from e
return MergeResult(bytes=out, page_count=len(writer.pages))
def count_pages(data: bytes) -> int:
"""Page count for UI display — the tool's only other pypdf need."""
try:
return len(_load(data).pages)
except PdfToolError:
raise
except Exception as e:
raise _map_error(e) from e
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →