PDF Split — Python source
Split a PDF by page, chunk size, or custom ranges — entirely in your browser. Nothing uploads.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
# pdf-split — split one PDF into many by page plan with pypdf
# (PdfReader/PdfWriter). Authored snippet mirroring src/lib/pdf-split.ts:
# the planner (parse_page_ranges + plan_names) is a pure port of the TS
# grammar — 'all', 'N/chunk', or comma-separated 'a-b' ranges and single
# pages (1-based, inclusive) — and split_pdf writes one PDF per planned
# group with the same naming rules.
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import List, Literal
from pypdf import PdfReader, PdfWriter
ErrorKind = Literal["encrypted", "invalid"]
_CHUNK_RE = re.compile(r"^(\d+)/chunk$")
_SINGLE_RE = re.compile(r"^\d+$")
_SPAN_RE = re.compile(r"^(\d+)-(\d+)$")
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:
kind = classify_load_error(str(e))
if kind == "encrypted":
return PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.")
return PdfToolError("invalid", "Not a readable PDF file.")
def _range(a: int, b: int) -> List[int]:
"""The 1-based pages [a..b], inclusive."""
return list(range(a, b + 1))
@dataclass
class SplitOutput:
name: str
bytes: bytes
page_count: int
def parse_page_ranges(spec: str, page_count: int) -> List[List[int]]:
"""Pure planner — no pypdf on this path. Grammar (mirrors the TS lib):
'all' -> [[1], [2], ..., [page_count]]
'N/chunk' -> groups of N pages in order (last group may be short)
'a-b,c-d,e' -> [[a..b], [c..d], [e]] (1-based, inclusive)
Raises PdfToolError('invalid') on empty specs, unparseable tokens,
descending ranges, and any page outside 1..page_count.
"""
trimmed = spec.strip()
if not trimmed:
raise PdfToolError("invalid", "Enter a page range first.")
if trimmed == "all":
return [[i + 1] for i in range(page_count)]
chunk = _CHUNK_RE.match(trimmed)
if chunk:
size = int(chunk.group(1))
if size < 1 or size > page_count:
raise PdfToolError("invalid", f"Chunk size must be between 1 and {page_count}.")
return [
_range(start, min(start + size - 1, page_count))
for start in range(1, page_count + 1, size)
]
groups: List[List[int]] = []
for token in trimmed.split(","):
t = token.strip()
if _SINGLE_RE.match(t):
page = int(t)
if page < 1 or page > page_count:
raise PdfToolError("invalid", f"Page {page} is out of range (1–{page_count}).")
groups.append([page])
elif span := _SPAN_RE.match(t):
a, b = int(span.group(1)), int(span.group(2))
if b < a:
raise PdfToolError("invalid", f"Range {a}-{b} descends — use a-b with a ≤ b.")
if a < 1 or b > page_count:
raise PdfToolError("invalid", f"Range {a}-{b} is out of range (1–{page_count}).")
groups.append(_range(a, b))
else:
raise PdfToolError(
"invalid", f'"{t}" is not a page, a-b range, "all", or "N/chunk".'
)
return groups
def _chunk_shaped(groups: List[List[int]]) -> bool:
"""Partition of 1..n into equal runs of ≥2 pages (last may be short)."""
if len(groups) < 2:
return False
size = len(groups[0])
if size < 2: # size-1 "chunks" are indistinguishable from 'all'
return False
nxt = 1
for i, group in enumerate(groups):
if group[0] != nxt:
return False
nxt = group[-1] + 1
if i < len(groups) - 1 and len(group) != size:
return False
if i == len(groups) - 1 and len(group) > size:
return False
return True
def plan_names(groups: List[List[int]]) -> List[str]:
"""Pure naming pass: single page -> 'page-N.pdf'; chunk-shaped plan ->
'chunk-K.pdf'; contiguous group -> 'pages-A-B.pdf'; else 'pages-A,B.pdf'."""
chunk = _chunk_shaped(groups)
names: List[str] = []
for i, group in enumerate(groups):
if chunk:
names.append(f"chunk-{i + 1}.pdf")
elif len(group) == 1:
names.append(f"page-{group[0]}.pdf")
elif group[-1] - group[0] + 1 == len(group):
names.append(f"pages-{group[0]}-{group[-1]}.pdf")
else:
names.append("pages-" + ",".join(str(p) for p in group) + ".pdf")
return names
def split_pdf(data: bytes, groups: List[List[int]]) -> List[SplitOutput]:
"""One output PDF per group: each planned page is copied from the shared
reader into a fresh writer (the pypdf analogue of pdf-lib's copyPages)."""
if not groups:
raise PdfToolError("invalid", "Nothing to split — plan at least one page.")
try:
reader = PdfReader(data)
if reader.is_encrypted:
raise PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.")
total = len(reader.pages)
names = plan_names(groups)
outs: List[SplitOutput] = []
for i, group in enumerate(groups):
for page in group:
if page < 1 or page > total:
raise PdfToolError("invalid", f"Page {page} is out of range (1–{total}).")
writer = PdfWriter()
for page in group:
writer.add_page(reader.pages[page - 1])
outs.append(
SplitOutput(
name=names[i],
bytes=writer.write_to_buffer(),
page_count=len(writer.pages),
)
)
return outs
except PdfToolError:
raise
except Exception as e:
raise _map_error(e) from e
def count_pages(data: bytes) -> int:
"""Page count for UI display — the tool's only other pypdf need."""
try:
reader = PdfReader(data)
if reader.is_encrypted:
raise PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.")
return len(reader.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 →