"""Carry original invisible PDF text objects onto reviewed reading pages.""" from collections import Counter, defaultdict import ctypes from io import BytesIO from contextlib import closing import math import pypdfium2 as pdfium from pypdfium2 import raw def displayed_matrix(page): """PDF user coordinates to the upright cropped page, with a bottom-left origin.""" left, bottom, right, top = page.get_bbox() transforms = { 0: (1, 0, 0, 1, -left, -bottom), 90: (0, -1, 1, 0, -bottom, right), 180: (-1, 0, 0, -1, right, top), 270: (0, 1, -1, 0, top, -left), } return pdfium.PdfMatrix(*transforms[page.get_rotation()]) def destination(points, size, raster, decision): width, height = size if not all( math.isfinite(x) and math.isfinite(y) and 0 <= x <= width and 0 <= y <= height for x, y in points ): return "outside_crop" if decision["state"] == "whole": return "whole" # Match the raster cutter. A box within one raster pixel of the fold is ambiguous. top, bottom = decision["top_x"], decision["bottom_x"] differences = [ (x / width - (bottom + (top - bottom) * y / height)) * raster[0] for x, y in points ] tolerance = 0.5 + abs(top - bottom) * raster[0] / (2 * raster[1]) if max(differences) < -tolerance: return "left" if min(differences) > tolerance: return "right" return "at_cut" def key(obj): return ctypes.cast(obj, ctypes.c_void_p).value def character_runs(page): """Actual decoded characters and their selection boxes, grouped by source text object.""" runs = defaultdict(list) with closing(page.get_textpage()) as tp: for i in range(tp.count_chars()): if raw.FPDFText_IsGenerated(tp, i) == 1: continue obj = raw.FPDFText_GetTextObject(tp, i) if obj: runs[key(obj)].append( (raw.FPDFText_GetUnicode(tp, i), tp.get_charbox(i)) ) return runs def matches(expected, actual): return ( bool(expected) and len(expected) == len(actual) and all( a == b and max(abs(x - y) for x, y in zip(box_a, box_b)) <= 0.25 for (a, box_a), (b, box_b) in zip(expected, actual) ) ) def checked_layer(output, scratch, index, expected, omitted): """Reopen serialized text before accepting its Unicode and placement.""" # Font widths, character spacing and TJ arrays may change when PDFium # regenerates text. Checking live objects before serialization misses this. with pdfium.PdfDocument.new() as clean: clean.import_pages(scratch, pages=[index]) buffer = BytesIO() clean.save(buffer) for attempt in range(2): buffer.seek(0) with pdfium.PdfDocument(buffer) as serialized, closing(serialized[0]) as page: objects = list( page.get_objects(filter=[raw.FPDF_PAGEOBJ_TEXT], max_depth=1) ) if len(objects) != len(expected): break runs = character_runs(page) keep = [ matches(chars, runs[key(obj)]) for obj, chars in zip(objects, expected) ] if all(keep): output.import_pages(serialized, pages=[0]) return len(expected) if attempt or not any(keep): break omitted["serialization_mismatch"] += keep.count(False) for obj, ok in zip(objects, keep): if not ok: page.remove_obj(obj) obj.close() page.gen_content() expected = [chars for chars, ok in zip(expected, keep) if ok] buffer = BytesIO() serialized.save(buffer) omitted["serialization_mismatch"] += len(expected) return 0 def append_searchable( output, book, index, sides, raster, right_origin, unit, decision, append_image ): # Copy the page so the caller's input and all shared font objects remain intact. omitted = Counter() kept = {} with pdfium.PdfDocument.new() as scratch: scratch.import_pages(book, pages=[index]) with closing(scratch[0]) as source: size = source.get_size() view = displayed_matrix(source) runs = character_runs(source) objects = {side: [] for side, _ in sides} for obj in source.get_objects(filter=[raw.FPDF_PAGEOBJ_TEXT]): if ( raw.FPDFTextObj_GetTextRenderMode(obj) != raw.FPDF_TEXTRENDERMODE_INVISIBLE ): omitted["other_render_mode"] += 1 continue if obj.level: omitted["inside_form"] += 1 continue if raw.FPDFClipPath_CountPaths(raw.FPDFPageObj_GetClipPath(obj)) > 0: omitted["clipped"] += 1 continue chars = runs[key(obj)] if not chars: omitted["unmapped"] += 1 continue # Include the glyph selection boxes as well as the painted run bounds. points = list(obj.get_quad_points()) for _, (left, bottom, right, top) in chars: points.extend( ((left, bottom), (left, top), (right, top), (right, bottom)) ) side = destination( [view.on_point(x, y) for x, y in points], size, raster, decision ) if side in objects: objects[side].append((obj, chars)) else: omitted[side] += 1 for side, image in sides: width_pt = size[0] * unit * image.width / raster[0] height_pt = size[1] * unit dx = ( -right_origin * size[0] * unit / raster[0] if side == "right" else 0 ) transform = view.scale(unit, unit).translate(dx, 0) kept[side] = 0 if objects[side]: expected = [] with closing(scratch.new_page(width_pt, height_pt)) as target: for obj, chars in objects[side]: source.remove_obj(obj) obj.transform(transform) target.insert_obj(obj) expected.append( [(code, transform.on_rect(*box)) for code, box in chars] ) target.gen_content() kept[side] = checked_layer( output, scratch, len(scratch) - 1, expected, omitted ) append_image( output, image, width_pt, height_pt, use_last_page=bool(kept[side]) ) return {"retained_by_side": kept, "omitted_by_reason": dict(omitted)}