Repository Public License
1<!--2ORIX Scan3File: docs/architecture/pdf-engine.md4Author: Simon-Pierre Boucher5Contact: contact@spboucher.ai6-->78# PDF engine910PDF work uses Core Graphics, Core Text and PDFKit. The code is in `Packages/ORIXKit/Sources/ORIXKit/PDF/` and in11`DocumentProcessor.exportPDF` (`Storage/DocumentProcessor.swift`).1213## Building a PDF1415`SearchablePDFBuilder.build(pageCount:to:options:page:progress:)` pulls pages one at a time through a closure that returns a16`PDFPageInput`:1718- `.image(jpeg:pixelWidth:pixelHeight:text:)`: a rendered page and, optionally, its `OCRPage`;19- `.pdf(url:pageIndex:quarterTurns:)`: a page copied from an existing PDF.2021```mermaid22flowchart TD23 Pages["page(index) closure"] --> Kind{"input kind"}24 Kind -- image --> Draw["Pass 1: draw into rendered.pdf<br/>CGContext PDF page: JPEG + invisible text"]25 Kind -- pdf --> Note["remember source URL, index, turns"]26 Draw --> Close["closePDF"]27 Note --> Assemble28 Close --> Assemble["Pass 2: PDFDocument assembly in page order<br/>rendered pages inserted, source pages copied, rotation applied"]29 Assemble --> Attr["documentAttributes: title, author, subject, keywords, creator"]30 Attr --> Write["write(to:withOptions:) in a temp directory<br/>user and owner password when set"]31 Write --> Move["replaceItemAt / moveItem to the destination"]32```3334**Two passes.** Image pages are drawn sequentially into one intermediate PDF file with a Core Graphics PDF context, inside35an autorelease pool, so memory does not grow with the page count. PDFKit then assembles the final document in order: pages36from the intermediate file and pages copied from imported PDFs, which keep their vector content and their own text. The37output is written in a temporary directory and moved into place, so a failed or cancelled build never leaves a partial file38at the destination. The builder checks for task cancellation before each page.3940**JPEG pass-through.** The page image is created with `CGImage(jpegDataProviderSource:…)` from the JPEG bytes the renderer41produced, and drawn into the PDF context. The quality chosen by the export preset is therefore the quality embedded in the42file.4344## Page size4546`SearchablePDFBuilder.pageSize(pixelWidth:pixelHeight:mode:)`:4748| `PageSizeMode` | Rule |49|---|---|50| `.a4` | 595.28 × 841.89 pt, oriented like the image |51| `.letter` | 612 × 792 pt, oriented like the image |52| `.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) |5354The image is scaled to fit inside the page and centered; fixed paper sizes can leave margins.5556## Invisible text layer5758`drawTextLayer` sets the text drawing mode to `.invisible` and draws each recognized line:5960- **Per word.** For an unedited line, every `OCRWord` is drawn at its own box. The font size comes from the line height61 (0.78 of it), and the run is scaled horizontally so its natural width equals the width of the word box.62- **Trailing space.** Every word but the last is drawn with a trailing space, so text extraction and search see word63 boundaries.64- **Line break.** A zero-width `"\n"` run is drawn at the end of each line, which separates lines in extracted text.65- **Edited lines.** A line the user corrected is drawn as a single run stretched over the line box.66- **Direction.** The baseline angle is taken from the bottom edge of the box, so text on a slightly tilted page still sits67 on its words.6869**Coordinates.** OCR boxes are normalized with a top-left origin. `pagePoint` maps a point into the frame where the image70was drawn: `x = frame.minX + p.x × frame.width`, `y = frame.minY + (1 − p.y) × frame.height`. Each run is placed by71translating to the bottom-left corner of its box, rotating by the baseline angle, lifting by an estimated descender (0.2 of72the line height) and scaling horizontally. Text is laid out by Core Text (`CTLine`), which embeds the fonts and handles73Unicode.7475## How it is validated7677The package tests (`Packages/ORIXKit/Tests/ORIXKitTests/PipelineTests.swift`, suite `SearchablePDFTests` and78`ProcessorTests`) build PDFs from rendered pages recognized by the real engine, then read them back with PDFKit, the same79framework PDF readers on Apple platforms use:8081- `PDFPage.string` is compared with the ground truth by character error rate;82- `PDFDocument.findString` must find phrases that are present and must not find absent ones, including accented French83 with and without diacritic-insensitive matching;84- the bounds of the selection returned for a word are compared with the recognized word box, for overlap and horizontal85 alignment;86- page order, page sizes, metadata, password behaviour and the absence of text when no layer is requested are checked;87- after compression, the exported page is rasterized and recognized again to confirm it is still readable.8889The app applies the same check interactively: `PDFPreviewView` (`App/Sources/Document/ExportSheet.swift`) opens the90exported file in a `PDFView` and searches it with `findString`.9192## Export and compression9394`DocumentProcessor.exportPDF(_:options:pages:progress:)` decides, page by page, what the builder receives:9596| Page | `maximum` | `balanced` | `small` |97|---|---|---|---|98| Image page | Full resolution, JPEG quality 0.9 | Longest side 2200 px, quality 0.6 | Longest side 1500 px, quality 0.4 |99| Imported PDF page with text or vector content | Copied untouched | Copied untouched | Copied untouched |100| Imported PDF page without text (a scan) | Copied untouched | Rasterized at 150 dpi, quality 0.6 | Rasterized at 110 dpi, quality 0.4 |101102Pages that carry text are never rasterized, because that would destroy their text. A re-rasterized scan page receives a text103layer when it has been recognized. `ExportResult` reports what was actually produced: `byteSize` read from the file,104`pagesRecompressed`, `pagesPassedThrough`, `pagesWithTextLayer`. The export sheet shows these values and never an estimate; a105smaller preset is not guaranteed to produce a smaller file.106107## Import, inspection and unlocking108109`PDFTools.open(_:password:)` throws `passwordRequired`, `wrongPassword` or `unreadablePDF` (including a document with no110page). `PDFTools.inspect` returns page count, encryption state, metadata and displayed page sizes.111112`PDFTools.writeUnlockedCopy(of:password:to:)` stores the PDF inside the document directory. An unencrypted file is copied113as it is. An encrypted file the user unlocked is redrawn page by page into a new Core Graphics PDF context, because PDFKit114alone would keep the encryption dictionary; the copy is then reopened to check its page count and that it is not locked.115The password is used for that call and is not stored.116117## Password protection and metadata118119When `PDFBuildOptions.password` is set, the document is written with `userPasswordOption` and `ownerPasswordOption` set to120that password; encryption is performed by PDFKit. Title, author, subject and keywords come from the manifest121(`DocumentMetadata`); creator and producer are set to "ORIX Scan".122123## Known limits124125- The text layer uses Helvetica metrics stretched to each word box; selection highlights approximate the glyph shapes, they126 do not trace them.127- Text is placed along a straight baseline per word; strongly curved lines (the gutter of a thick book) are not modelled.128- Redrawing an unlocked PDF keeps page content but not interactive features of the original such as form fields, links129 or outlines.130- Pages with vector text are not compressed by any preset.131- The app prints from the exported file and disables printing when a password is set for the export.132