SPB Git

Repository Public License

pdf-engine.md 7.5 KB

# PDF engine

PDF work uses Core Graphics, Core Text and PDFKit. The code is in Packages/ORIXKit/Sources/ORIXKit/PDF/ and in DocumentProcessor.exportPDF (Storage/DocumentProcessor.swift).

# Building a PDF

SearchablePDFBuilder.build(pageCount:to:options:page:progress:) pulls pages one at a time through a closure that returns a PDFPageInput:

  • .image(jpeg:pixelWidth:pixelHeight:text:): a rendered page and, optionally, its OCRPage;
  • .pdf(url:pageIndex:quarterTurns:): a page copied from an existing PDF.
flowchart TD
    Pages["page(index) closure"] --> Kind{"input kind"}
    Kind -- image --> Draw["Pass 1: draw into rendered.pdf<br/>CGContext PDF page: JPEG + invisible text"]
    Kind -- pdf --> Note["remember source URL, index, turns"]
    Draw --> Close["closePDF"]
    Note --> Assemble
    Close --> Assemble["Pass 2: PDFDocument assembly in page order<br/>rendered pages inserted, source pages copied, rotation applied"]
    Assemble --> Attr["documentAttributes: title, author, subject, keywords, creator"]
    Attr --> Write["write(to:withOptions:) in a temp directory<br/>user and owner password when set"]
    Write --> Move["replaceItemAt / moveItem to the destination"]

Two passes. Image pages are drawn sequentially into one intermediate PDF file with a Core Graphics PDF context, inside an autorelease pool, so memory does not grow with the page count. PDFKit then assembles the final document in order: pages from the intermediate file and pages copied from imported PDFs, which keep their vector content and their own text. The output is written in a temporary directory and moved into place, so a failed or cancelled build never leaves a partial file at the destination. The builder checks for task cancellation before each page.

JPEG pass-through. The page image is created with CGImage(jpegDataProviderSource:…) from the JPEG bytes the renderer produced, and drawn into the PDF context. The quality chosen by the export preset is therefore the quality embedded in the file.

# Page size

SearchablePDFBuilder.pageSize(pixelWidth:pixelHeight:mode:):

PageSizeMode Rule
.a4 595.28 × 841.89 pt, oriented like the image
.letter 612 × 792 pt, oriented like the image
.automatic A4 when the aspect ratio is within 0.035 of A4, US Letter when within 0.035 of Letter, otherwise the image's own proportions with the long side at 841.89 pt (receipts, cards, spreads)

The image is scaled to fit inside the page and centered; fixed paper sizes can leave margins.

# Invisible text layer

drawTextLayer sets the text drawing mode to .invisible and draws each recognized line:

  • Per word. For an unedited line, every OCRWord is drawn at its own box. The font size comes from the line height (0.78 of it), and the run is scaled horizontally so its natural width equals the width of the word box.
  • Trailing space. Every word but the last is drawn with a trailing space, so text extraction and search see word boundaries.
  • Line break. A zero-width "\n" run is drawn at the end of each line, which separates lines in extracted text.
  • Edited lines. A line the user corrected is drawn as a single run stretched over the line box.
  • Direction. The baseline angle is taken from the bottom edge of the box, so text on a slightly tilted page still sits on its words.

Coordinates. OCR boxes are normalized with a top-left origin. pagePoint maps a point into the frame where the image was drawn: x = frame.minX + p.x × frame.width, y = frame.minY + (1 − p.y) × frame.height. Each run is placed by translating to the bottom-left corner of its box, rotating by the baseline angle, lifting by an estimated descender (0.2 of the line height) and scaling horizontally. Text is laid out by Core Text (CTLine), which embeds the fonts and handles Unicode.

# How it is validated

The package tests (Packages/ORIXKit/Tests/ORIXKitTests/PipelineTests.swift, suite SearchablePDFTests and ProcessorTests) build PDFs from rendered pages recognized by the real engine, then read them back with PDFKit, the same framework PDF readers on Apple platforms use:

  • PDFPage.string is compared with the ground truth by character error rate;
  • PDFDocument.findString must find phrases that are present and must not find absent ones, including accented French with and without diacritic-insensitive matching;
  • the bounds of the selection returned for a word are compared with the recognized word box, for overlap and horizontal alignment;
  • page order, page sizes, metadata, password behaviour and the absence of text when no layer is requested are checked;
  • after compression, the exported page is rasterized and recognized again to confirm it is still readable.

The app applies the same check interactively: PDFPreviewView (App/Sources/Document/ExportSheet.swift) opens the exported file in a PDFView and searches it with findString.

# Export and compression

DocumentProcessor.exportPDF(_:options:pages:progress:) decides, page by page, what the builder receives:

Page maximum balanced small
Image page Full resolution, JPEG quality 0.9 Longest side 2200 px, quality 0.6 Longest side 1500 px, quality 0.4
Imported PDF page with text or vector content Copied untouched Copied untouched Copied untouched
Imported PDF page without text (a scan) Copied untouched Rasterized at 150 dpi, quality 0.6 Rasterized at 110 dpi, quality 0.4

Pages that carry text are never rasterized, because that would destroy their text. A re-rasterized scan page receives a text layer when it has been recognized. ExportResult reports what was actually produced: byteSize read from the file, pagesRecompressed, pagesPassedThrough, pagesWithTextLayer. The export sheet shows these values and never an estimate; a smaller preset is not guaranteed to produce a smaller file.

# Import, inspection and unlocking

PDFTools.open(_:password:) throws passwordRequired, wrongPassword or unreadablePDF (including a document with no page). PDFTools.inspect returns page count, encryption state, metadata and displayed page sizes.

PDFTools.writeUnlockedCopy(of:password:to:) stores the PDF inside the document directory. An unencrypted file is copied as it is. An encrypted file the user unlocked is redrawn page by page into a new Core Graphics PDF context, because PDFKit alone would keep the encryption dictionary; the copy is then reopened to check its page count and that it is not locked. The password is used for that call and is not stored.

# Password protection and metadata

When PDFBuildOptions.password is set, the document is written with userPasswordOption and ownerPasswordOption set to that password; encryption is performed by PDFKit. Title, author, subject and keywords come from the manifest (DocumentMetadata); creator and producer are set to "ORIX Scan".

# Known limits

  • The text layer uses Helvetica metrics stretched to each word box; selection highlights approximate the glyph shapes, they do not trace them.
  • Text is placed along a straight baseline per word; strongly curved lines (the gutter of a thick book) are not modelled.
  • Redrawing an unlocked PDF keeps page content but not interactive features of the original such as form fields, links or outlines.
  • Pages with vector text are not compressed by any preset.
  • The app prints from the exported file and disables printing when a password is set for the export.
Files main
Menu

Theme