"""Merging of chunk PDFs and reading of basic page geometry.""" from __future__ import annotations import logging from pathlib import Path logger = logging.getLogger(__name__) def merge(paths: list[Path], output_path: Path) -> int: """Concatenate chunk PDFs into one file. PdfWriter.append is used on purpose, it carries over bookmarks and internal links and shifts their page references by the running offset. """ from pypdf import PdfWriter if not paths: raise ValueError("Neni co slucovat, seznam PDF je prazdny.") if len(paths) == 1: paths[0].replace(output_path) return page_count(output_path) writer = PdfWriter() try: for path in paths: writer.append(str(path)) with output_path.open("wb") as handle: writer.write(handle) finally: writer.close() total = page_count(output_path) logger.info("Chunks merged", extra={"chunks": len(paths), "pages": total}) return total def page_count(path: Path) -> int: from pypdf import PdfReader with path.open("rb") as handle: return len(PdfReader(handle).pages) def first_page_size(path: Path) -> tuple[float, float]: """Width and height of the first page in points.""" from pypdf import PdfReader with path.open("rb") as handle: box = PdfReader(handle).pages[0].mediabox return float(box.width), float(box.height)