Repository Public License
1# PDF engine (`pdf`) — compatibility notes23Package `Packages/EnginePDF` (module `EnginePDF`, factory `makeEngines()`), engine id `pdf`.4Apple frameworks only: PDFKit, Core Graphics (CGPDF object and scanner APIs), Quartz (`QuartzFilter`), Vision,5Core Text, ImageIO, AppKit (`NSAttributedString` document writing). No third-party code, no helper executable,6no network.78Everything below was implemented, tested and measured on **macOS 27.0 (26A5425a), Apple M5 Max (18 cores, 48 GB),9Swift 6.4.2, debug build (`swift test`)**. The deployment target is macOS 15.0, but **nothing here was run on10macOS 15 or 26**: several behaviours of PDFKit this engine relies on (listed in “PDFKit behaviours relied on”) were11observed on macOS 27 only and must be re-checked on the older systems before release.1213Tests: `swift test` from `Packages/EnginePDF` — 58 tests in 13 suites, all passing (`✔ Test run with 58 tests in1413 suites passed after 13.790 seconds`, 2026-11-21; two of them are the benchmark15tests, which only run with `ORIX_PDF_BENCH=1`). Fixtures are generated in code (Core Graphics / Core Text / PDFKit /16ImageIO, plus hand-written PDF objects for the features PDFKit cannot author); the only embedded binary is a 34-byte171 × 1 WebP given as base64.1819## Declared paths (24)2021Suites are nested in `PDFEngineTests`. “Keeps” is the `preserves` set of the path.2223| Source | Destination | Operation | Status | Fidelity | Keeps | Main limitations | Tests |24|---|---|---|---|---|---|---|---|25| pdf | png | — | supported | lossy | dimensions | flat images; several pages → folder; pixel cap | `Rendering/singlePageToPNG`, `severalPagesGoToAFolder`, `transparentBackground`, `annotationsCanBeLeftOut`, `cropBoxVersusMediaBox`, `stripRenderingIsSeamless` |26| pdf | jpeg | — | supported | lossy | dimensions | same + no transparency, lossy | `Rendering/pageSelectionWidthAndGreyJPEG` |27| pdf | tiff | — | supported | lossy | dimensions | same; optional multi-page TIFF (memory grows with pages, capped at 1.5 gigapixels) | `Rendering/multiPageTIFFAndPerPageTIFF` |28| pdf | txt | — | supported | partial | — | text only, PDFKit order; OCR for pages without text | `TextExport/plainTextWithSeparators`, `hyphenationRepair`, `positionalOrderSortsTopToBottom`, `scannedDocumentIsReportedAndReadWithOCR` |29| pdf | markdown | — | supported | partial | — | only `## Page N` headings are added; nothing is escaped or detected | `TextExport/markdownAddsOnlyPageHeadings`, `scannedDocumentIsReportedAndReadWithOCR` |30| pdf | pdf | `pdf.ocr` | supported | structural | vectorGeometry, images, links, metadata, dimensions, chapters | recognition errors; tags, attachments, JavaScript, signatures dropped | `SearchablePDF/invisibleLayerMatchesTheScan` (150 and 300 dpi), `outlineLinksAnnotationsAndFormsSurvive`, `documentsWithTextAreReturnedUnchanged`, `everyPageOnRequest` |31| pdf | docx | — | **experimental** | partial | textStyles | text reconstruction only: no layout, columns, tables, images, vectors | `RichText/rebuildsParagraphsAndStyles(docx)`, `scannedDocumentsAreRefusedWithAdvice` |32| pdf | rtf | — | **experimental** | partial | textStyles | same | `RichText/rebuildsParagraphsAndStyles(rtf)` |33| png, jpeg, heic, tiff, gif, bmp, webp | pdf | — (multiple sources) | supported | lossless | dimensions (+ transparency for png, tiff) | one image per page; metadata not copied; first frame of animations; lossy only on request | `ImagesIntoPDF/everySourceFormat` (7 cases), `jpegIsEmbeddedWithoutRecompression`, `losslessByDefaultAndJPEGOnRequest`, `exifOrientationIsApplied` (4 cases), `pageSizesMarginsOrderAndPasswords`, `optionalTextLayer`, `rejectsWhatIsNotAnImage` |34| pdf | pdf | `pdf.merge` (multiple sources) | supported | lossless | vectorGeometry, images, links, chapters, dimensions, metadata | tags, attachments, XMP, JavaScript, AcroForm dictionary, signatures dropped | `PageOperations/mergeKeepsOrderOutlineAndAnnotations` |35| pdf | folder | `pdf.split` | supported | lossless | same | same | `PageOperations/splitModes` |36| pdf | pdf | `pdf.extract-pages` | supported | lossless | same | same; links to removed pages break (warned) | `PageOperations/extractDeleteReorder` |37| pdf | pdf | `pdf.delete-pages` | supported | lossless | same | same | `PageOperations/extractDeleteReorder` |38| pdf | pdf | `pdf.reorder-pages` | supported | lossless | same | same | `PageOperations/extractDeleteReorder` |39| pdf | pdf | `pdf.rotate` | supported | lossless | same | 90° steps, stored as page rotation; a signature does not stay valid | `PageOperations/rotationIsWrittenAsPageRotation` |40| pdf | pdf | `pdf.compress` | supported | lossy | vectorGeometry, links, metadata, dimensions, chapters | images only; images with transparency stay lossless; tags, attachments, JavaScript, signatures dropped | `Compression/imageHeavyDocumentShrinks`, `neverReturnsABiggerFile`, `structureSurvivesCompression` |41| pdf | folder | `pdf.extract-images` | supported | partial | images, transparency | CCITT / JBIG2 / Separation / DeviceN / Lab / inline images not extracted (counted) | `ImageExtraction/jpegBytesAndLosslessPixels`, `handWrittenColourSpaces`, `unsupportedFiltersAndInlineImagesAreCounted` |42| pdf | pdf | `pdf.set-metadata` | supported | lossless | vectorGeometry, images, links, chapters, dimensions | Info dictionary only; XMP is reported, not rewritten | `PageOperations/metadataCanBeSetAndStripped` |4344Cross-cutting tests: `PageLists/*` (range syntax), `Protection/*` (passwords and permission flags on every path),45`Robustness/malformedAndTruncatedFiles`, `cancellationStopsTheWork`, `twoThousandPages`,46`inspectionReportsWhatIsInTheFile`, `everyDeclaredPathIsListedOnceWithSettings` (the 24 ids above are asserted),47`undeclaredRequestsAreRefused`, `PageOperations/featureRetentionMatchesThePreflightWarnings`.4849### Output shape5051- One selected page → one file. Several pages → **one directory** in the work directory, returned as the single52 entry of `ConversionOutput.files`, holding `<name>-001.png` … (zero-padded page numbers of the source).53 A multi-page TIFF is one file. `pdf.split` and `pdf.extract-images` return one directory.54- Folder outputs are obtained with `context.outputURL(for:extension: "")`.5556### Page-list syntax (`PageList`, public)5758`1-3,7,10-` — items separated by commas: `N`, `A-B` (descending allowed), `A-` (to the end), `-B` (from the59start). Order and duplicates are kept for extraction and reordering. Out-of-range, empty items, non-ASCII digits60and lists expanding to more than 200 000 entries are rejected with `invalidOption` / `limitExceeded`.61Split by ranges: each comma-separated range is a file; with `;` the files are separated by `;` and each file can62combine several ranges (`1-3,7;8-`).6364## How each part works6566### Rendering (PDF → PNG / JPEG / TIFF, thumbnails)6768Pages are drawn into one malloc'd buffer strip by strip (about 12 megapixels per strip), so Core Graphics never69needs a second full-size surface and cancellation is checked between strips. With annotations: `PDFPage.draw`;70without: `CGContext.drawPDFPage` with the engine's own box / rotation transform (both routes are tested on rotated71pages). Options: DPI or pixel width, sRGB / grey, white / transparent background (PNG and TIFF, colour only),72page list, annotations on / off, crop box / media box, JPEG quality, TIFF compression, multi-page TIFF.73Caps: 32 000 px per side and 256 megapixels per page; a larger request is rendered at a lower scale with a74`pixel-cap` warning. **The cap is unit-tested on the size computation only** — no test renders a 256-megapixel page.7576Public API: `PDFPreview.pageCount(of:password:)` and `PDFPreview.thumbnail(of:pageIndex:maxPixelSize:password:annotations:)`77(longest side 16…4096 px, white background, sRGB).7879### Text (PDF → TXT / Markdown)8081`PDFPage.string` per page (PDFKit reading order) or, on request, lines sorted by position (top to bottom, pieces of82one baseline left to right — for single-column pages only). Options: page separator (blank line, marker line, form83feed, nothing), hyphenation repair, page list. Markdown adds `## Page N` headings and nothing else.84A page counts as having a text layer when it yields at least three letters or digits. Pages without one are read85with Vision by default (`ocr` = “Pages without text”), with an `ocr-used` warning; with OCR off a document without86any text fails with a message saying it is a scanned document and how to turn OCR on. `preflight` reports87`scanned-no-text` (“… scanned document — use OCR …”) or `scanned-ocr`.8889### Searchable PDF (`pdf.ocr`) — approach chosen and alternatives9091**Chosen: keep the original `PDFDocument` and add the text from a `PDFPage` subclass while PDFKit writes.**92The document is opened with a `PDFDocumentDelegate` returning `OverlayPage` from `classForPage()`. When93`PDFDocument.write(to:)` runs, PDFKit calls `draw(with:to:)` on every page with a PDF context: the override calls94`super` (the original page content goes through Quartz: vector stays vector, text stays text, JPEG streams are95copied byte for byte — tested) and then draws the recognised words with `CGTextDrawingMode.invisible`.96Each word is one Core Text run in Helvetica, sized to the height of Vision's word box and stretched horizontally to97its width; the gaps between words receive a stretched space; all runs of a line follow the line's baseline (an98earlier version that followed each gap's own direction made PDFKit split lines, see the tests).99Recognition: `VNRecognizeTextRequest` on the page rendered at 300 dpi (option, 72–600; capped at 10 000 px a side),100accurate or fast, automatic language detection or a list checked against `supportedRecognitionLanguages()`.101Pages that already have text are skipped unless “Every page” is chosen (then a `ocr-duplicate-text` warning).102If nothing is recognised or needed, the **original bytes** are returned (`result = unchanged`).103104Measured result of this approach (test `outlineLinksAnnotationsAndFormsSurvive` and the retention test):105106- kept: outline (same entries and nesting), link annotations (URL and internal), form widget and its value, square107 annotation (still an annotation, not painted into the page), Info metadata, XMP packet, AcroForm dictionary,108 page sizes and rotation, the scan image itself (same pixel size and filter; a JPEG stream is byte-identical);109- lost: tag structure (tagged PDF), file attachments, document JavaScript; a digital signature cannot stay valid;110- changed: a media box that does not start at (0, 0) is moved to the origin by PDFKit (same size; the crop box111 moves with it; the text layer follows — tested with a hand-written `[50 50 662 842]` page);112- accuracy on the fixtures (Helvetica 14–18 pt rendered at 150 and 300 dpi; upright page, `/Rotate 90` page,113 cropped page, offset media box): every probe word found by `PDFDocument.findString`, selection box covering114 more than 60 % of the drawn word, centre within 1.87 pt (150 dpi) and 1.71 pt (300 dpi) of the true position.115116Alternatives evaluated:117118| Alternative | Result | Verdict |119|---|---|---|120| Redraw every page into a new `CGPDFContext` (`drawPDFPage` + invisible text) | Text layer fine, but the experiment output had 0 annotations and no outline: links, form fields, outline and all catalog data are gone | rejected |121| `PDFDocumentWriteOption.saveTextFromOCROption` (PDFKit's own OCR on save) | On macOS 27 the write returned in under a millisecond and the image-only page still had no text; no control over language or accuracy either | rejected |122| Vision `RecognizeDocumentsRequest` (macOS 26+) | Ran on macOS 27 and returned the same three lines as `VNRecognizeTextRequest` on the sample, with one accent wrong (“eté”) where the older request was right; it needs macOS 26 and brings nothing for a word-level layer | not used; `VNRecognizeTextRequest` works from macOS 15 |123| Appending a content stream to each page by an incremental update written by our own PDF object writer | Would leave every existing byte untouched (tags, attachments, signatures' byte ranges). Needs our own parser for cross-reference tables / streams and object streams, cannot handle encrypted files without implementing the security handlers | not implemented (see “Not implemented”) |124125### PDF → DOCX / RTF (experimental)126127`PDFSelection.selectionsByLine()` gives each line with its attributed string (font, size, colour) and bounds.128Lines are grouped into paragraphs: a new paragraph starts on a font-size change, a vertical gap above 0.7 line129heights, a jump upwards, a first-line indent, or after a line that stops more than 15 % short of the right edge.130Lines are joined with a space; a hyphen at a line end followed by a lower-case letter is removed (option).131Fonts: family kept when installed, otherwise Helvetica / Times New Roman / Courier New chosen from the font name;132size, bold, italic and colour kept. Paragraphs at least 15 % larger than the body size count as headings (they keep133their size and get spacing; **no Word heading style is written** — `NSAttributedString` cannot express one).134Page breaks are form feeds (they round-trip through the DOCX writer — tested). Title / author / subject are carried.135Tested on one synthetic two-page layout only, hence `.experimental`.136Placing page images was evaluated and dropped: AppKit's OOXML writer discards attachments (a round-trip of an137attributed string with an image attachment produced a DOCX without any media part).138139### Images → PDF140141One page per image or TIFF frame, written with `CGPDFContext`. JPEG sources are embedded through142`CGImage(jpegDataProviderSource:)`: the PDF holds the original DCT stream (2 406 125-byte JPEG → 2 410 078-byte PDF,143and extracting the image returns the source file byte for byte — tested). Other formats are stored losslessly144(pixel-exact, alpha kept as a soft mask — tested); “Recompress as JPEG” re-encodes opaque images at the chosen145quality. EXIF orientation is applied by the drawing transform (orientations 1, 3, 6, 8 tested; 2, 4, 5, 7 are146implemented from the same derivation but **not tested**). Page size: fit to image (pixels × 72 / dpi, dpi from147the file or the option, 72 when absent), A4, Letter, custom (mm), automatic or forced orientation, margins, fit or148fill. Optional OCR layer in the same pass, output passwords, title / author.149Animated GIF / WebP / APNG: first frame, with an `animation-first-frame` warning (GIF tested; the WebP fixture is a1501 × 1 still image, animated WebP and APNG are untested).151152### Merge, split, extract, delete, reorder153154A new `PDFDocument` receives the page objects of the sources (copies when a page is used twice); annotations travel155with their pages; the outline is rebuilt for the pages that survive (an entry whose page is gone is kept only if a156child survives, and then points to it). Merge nests each file's outline under an entry named after the file.157Split modes: every page, every N pages, ranges, top-level outline entries (files named `001-<title>.pdf`, pages158before the first entry go to `001-Front matter.pdf`).159Embedded images are not re-encoded (JPEG extracted from a merged file is byte-identical — tested).160161`pdf.rotate` and `pdf.set-metadata` modify the opened document and let PDFKit rewrite it.162163### What each PDF-producing operation keeps (measured)164165Fixture: hand-written PDF with an attachment, `/MarkInfo` + `/StructTreeRoot`, XMP, an AcroForm text field,166document JavaScript (test `featureRetentionMatchesThePreflightWarnings`; the `feature-dropped` preflight warnings167are asserted to match this table exactly).168169| Operation | Attachments | Tag structure | XMP | AcroForm dictionary | JavaScript | Widget annotation |170|---|---|---|---|---|---|---|171| `pdf.rotate`, `pdf.set-metadata` | kept | kept | kept | kept | kept | kept |172| `pdf.compress`, `pdf.ocr` (page subclass rewrite) | lost | lost | kept | kept | lost | kept |173| `pdf.merge`, `pdf.extract-pages`, `pdf.reorder-pages` (and `pdf.split`, `pdf.delete-pages`: same code path, not measured separately) | lost | lost | lost | lost | lost | kept |174175A field created with PDFKit (`rich.pdf` fixture) has no AcroForm dictionary in the first place; its widget and176value (`FieldValue42`) survive merge, split and extraction. Outline, URL links, internal links (retargeted to the177right page), square annotation: kept by merge, reorder, rotate, set-metadata, OCR and compression (structure178compared before / after in the tests).179180### Compression (`pdf.compress`) — approach chosen and alternatives181182**Chosen: a Quartz filter applied inside the page subclass while PDFKit rewrites the document.**183`QuartzFilter(properties:)` (public, Quartz framework) is built from a dictionary in the ColorSync `.qfilter`184format (`ImageSettings`: `ImageCompression = ImageJPEGCompress`, `Compression Quality`, `ImageScaleSettings /185ImageResolution`). `OverlayPage.draw` calls `filter.apply(to:)`, `super.draw`, `filter.remove(from:)`.186Measured: images are resampled to the requested resolution **at their drawn size** (a 3000-px JPEG drawn 6 in wide187becomes 1800 / 900 / 431 px at 300 / 150 / 72 dpi), images below the threshold are not upsampled, opaque Flate188images become JPEG, text stays extractable, the outline / links / form field / annotations are kept, the page189still has exactly one image XObject (it is not rasterised).190If the result is not smaller than the source, it is deleted and the **source bytes are copied** to the output191(`result = already optimised`, `already-optimised` warning). When an output password is requested the source bytes192cannot be returned: a protected copy is written and reported as *not compressed*.193194Caveats: the dictionary keys are those of `.qfilter` files (ColorSync Utility), which Apple does not document195formally; the behaviour was verified on macOS 27.0 only. Images with a soft mask are downsampled but stay196Flate-encoded (measured in the feasibility experiment). The JPEG quality scale is Quartz's, not ImageIO's.197198| Alternative | Result | Verdict |199|---|---|---|200| `PDFDocumentWriteOption.saveImagesAsJPEGOption` + `optimizeImagesForScreenOption` | 2 910 077 → 2 910 076 bytes on a document holding a 3000 × 2000 JPEG: no effect, and no resolution or quality control | rejected |201| Quartz filter on a plain `CGPDFContext` redraw | 2.9 MB → 23 kB at 72 dpi, text kept, but annotations and outline lost (0 annotations in the output) | rejected in favour of the same filter inside PDFKit's write |202| Undocumented `"QuartzFilter"` key of `PDFDocument.write(to:withOptions:)` | not a public constant | not used |203| Own object rewriter replacing image XObject streams (full rewrite of the cross-reference data) | would keep tags, attachments and every other object byte for byte; needs a robust parser for cross-reference streams, object streams, incremental updates and hybrid files, plus the security handlers for encrypted files | not implemented: not something that could be made robust in this pass |204205Measured ratios (fixtures are synthetic: gradients with pixel noise, which JPEG compresses poorly at high quality206and very well at low quality — real photographs will differ):207208| Fixture | Settings | Before | After | Ratio |209|---|---|---|---|---|210| `images.pdf` (2 pages: 3000 × 2000 JPEG q 0.9 at 500 dpi + 1600 × 1200 lossless RGB at 267 dpi) | 300 dpi, q 0.8 | 8 222 126 | 2 210 800 | 3.7× |211| same | 150 dpi, q 0.6 (default) | 8 222 126 | 364 207 | 22.6× |212| same | 72 dpi, q 0.3 | 8 222 126 | 48 070 | 171× |213| `office.pdf` (40 text pages, each with a 1200 × 800 JPEG at 300 dpi) | 150 dpi, q 0.6 | 613 871 | 178 384 | 3.4× |214| same | 100 dpi, q 0.4 | 613 871 | 119 484 | 5.1× |215| `scan.pdf` (10 image-only pages, 2550 × 3300 lossless) | 150 dpi, q 0.6 | 8 368 339 | 6 247 794 | 1.3× |216| same | 100 dpi, q 0.4 | 8 368 339 | 3 187 750 | 2.6× |217| text-only PDF, 3 pages | default | 12 450 | attempt 12 483 → original returned (12 450) | 1.0× (already optimised) |218219### Image extraction (`pdf.extract-images`)220221Image XObjects are collected from page resources (inherited resources and nested form XObjects included; the same222stream referenced from several pages is written once). `CGPDFStreamCopyData` returns DCT data as is → `.jpg`223(byte-exact, tested) and JPX data as is → `.jp2` / `.j2k` (**no JPX fixture: untested**). Everything else is224rebuilt from the decoded samples: DeviceGray / RGB / CMYK, CalGray / CalRGB (treated as device), ICCBased (profile225used when valid), Indexed, 1–16 bits, `Decode` arrays, soft masks → alpha; written as PNG (CMYK → sRGB with a226warning). Tested by hand-written objects: Indexed RGB, CMYK, 4-bit grey, RGB + soft mask, plus a Separation image227and a truncated image that must be skipped. Not extracted, counted in `images-skipped` (severity data loss):228CCITTFax and JBIG2 (not attempted — whether Core Graphics would decode them was not tested), Separation / DeviceN /229Lab / Pattern colour spaces, images whose data is shorter than declared. Inline images (`BI … EI`) are counted on230the first 500 selected pages and reported, not extracted. Stencil and colour-key masks are not applied (warning).231Images inside patterns and annotation appearance streams are not looked at.232233A PDF from which no image file can be produced is refused with a clear error instead of an empty folder (fixed2342026-11-21 — the empty folder was rejected further on by the core with a generic “contains no file”):235“This PDF contains no embedded image that can be extracted (…)”, followed by the count of every image that was seen236and left out (unsupported encodings by name, images below the minimum size, inline images) and, when the pages hold237only text and vector drawings, the advice to convert the PDF to PNG or JPEG instead. `preflight` says the same before238converting (`no-images`, from a quick scan of the image objects of the first 300 pages; no warning when the document239is longer than that or when a page selection is set). Tests: `unsupportedFiltersAndInlineImagesAreCounted`,240`pdfWithoutImagesIsRefusedClearlyAndAnnouncedByPreflight`.241242### Metadata and inspection243244`pdf.set-metadata` edits or clears the Info dictionary through `PDFDocument.documentAttributes` (title, author,245subject, keywords, creator, producer, creation and modification dates; ISO 8601 input). After “Remove existing246metadata” the Info dictionary of the test output had **no keys left**; the output is re-read and anything247remaining, or a retained XMP packet, is reported as a warning. XMP is detected, never rewritten.248Merge and images → PDF accept a title (and author for images).249250`inspect` (PDF): page count, PDF version, first page size, number of distinct page sizes and rotated pages (first2515 000 pages), encryption and each permission flag, linearisation flag (looks for `/Linearized` in the first 2 kB),252text layer / images drawn / highest image resolution at drawn size / fonts with embedded status (on at most 12253evenly spread pages — the fields say how many were sampled), outline entries, top-level form fields, annotation254count, attachments, tagged flag, XMP, JavaScript presence, every string of the Info dictionary.255A locked document reports only “encrypted” and that a password is needed (`pageCount` stays `nil`).256The image resolution ignores `/UserUnit` and clipping.257258`inspectableFormats` is `[.pdf]` only (fixed 2026-11-21). The raster formats accepted by images → PDF were listed259too, so — depending on the order in which the engines are registered — the PDF engine could be the one asked to260inspect a PNG / JPEG / HEIC / TIFF / GIF / BMP / WebP file instead of the image engine. `inspect` still answers for261those formats when called directly (pixel size, frame count, alpha, colour model, depth, DPI and orientation from262ImageIO), and `preflight` of images → PDF reads the image facts it needs itself. Test:263`everyDeclaredPathIsListedOnceWithSettings` asserts `inspectableFormats == [.pdf]`.264265### Protected PDFs266267- `password` opens a locked file, or lifts the restrictions when it is the owner password.268- Opened without owner rights, the permission flags are enforced before anything is read or written:269 text / DOCX / image extraction need *copying*; PNG / JPEG / TIFF export needs *printing*; merge, split, extract,270 delete, reorder and rotate need *document assembly* (or *changes*); OCR, compression and metadata need *changes*.271 Refusals are `ConversionError.encryptedInput` with the name of the missing permission (tested for every path).272- A restricted source never yields a less protected PDF: `rotate` / `set-metadata` keep the original encryption273 (PDFKit carries it; the original owner password still works — tested); assembled results are encrypted again with274 the same open password, a random owner password and the source's permission flags. PDFKit does not read back275 exactly the flags it is asked to write (asking for `15` gave `207`), so each candidate is written, reopened and276 kept only if it is encrypted and grants nothing the source did not; otherwise a narrower set is tried, and the277 operation fails rather than weaken the protection. Setting new passwords requires the owner password.278- With owner rights the result is unencrypted unless `output.password.user` / `output.password.owner` are set;279 an `encryption-not-carried` warning says so.280- Not covered by a test: OCR / compression of an encrypted file opened with its owner password (the `encrypted`281 fact and the warning report what was actually written), and signed PDFs.282283`OptionDescriptor` has no “secret” kind: `password`, `output.password.user` and `output.password.owner` are plain284text options. The app should mask them and keep them out of presets and history.285286## Measured performance287288Machine: Apple M5 Max, macOS 27.0, debug build. **The Mac was shared with other sessions during the runs (load289average 58 to 91 on 18 cores, later 270)**, so these are pessimistic figures; where two runs differ both are given.290Reproduce with `ORIX_PDF_BENCH=1 swift test --filter Benchmarks`.291292Fixture `office.pdf`: 40 Letter pages, 40 lines of 11 pt text and one 1200 × 800 JPEG per page.293Fixture `scan.pdf`: 10 image-only Letter pages, 40 lines of 11 pt text rasterised at 300 dpi.294295| Measurement | Run 1 | Run 2 (best of 3) |296|---|---|---|297| PDF → PNG, 150 dpi (1275 × 1650) | 19.7 pages/s | 16.0 pages/s |298| PDF → PNG, 300 dpi (2550 × 3300) | 4.7 pages/s | 4.6 pages/s |299| PDF → JPEG, 150 dpi | 69.9 pages/s | 63.3 pages/s |300| PDF → JPEG, 300 dpi | 26.8 pages/s | 27.2 pages/s |301| PDF → TIFF (LZW), 150 dpi | 24.4 pages/s | 27.3 pages/s |302| PDF → TXT | 646 pages/s | 528 pages/s |303| PDF → DOCX | 102 pages/s | 91 pages/s |304| `pdf.ocr` accurate, automatic language (render + Vision + rewrite) | 3.31 pages/s | 3.11 pages/s |305| `pdf.ocr` accurate, `en-US` | 3.63 pages/s | 2.04 pages/s |306| `pdf.ocr` fast, automatic language | 3.77 pages/s | 3.18 pages/s |307| `pdf.ocr` fast, `en-US` | 3.80 pages/s | 2.93 pages/s |308| Vision alone, accurate, 2550 × 3300 pages | — | 4.1 pages/s |309| Vision alone, fast | — | 4.1 pages/s |310| Rendering the 10 scanned pages at 300 dpi | — | 0.24 s in total |311| `pdf.merge`, 5 × 2 000 pages | 4 937 pages/s | 1 758 pages/s |312| `pdf.split`, every page, 2 000 pages (2 000 files) | 1 178 pages/s | 293 pages/s |313| `pdf.split`, every 100 pages, 2 000 pages | 8 125 pages/s | 1 784 pages/s |314| `pdf.compress` `office.pdf`, 150 dpi q 0.6 | 225 pages/s | 57 pages/s |315| `pdf.compress` `scan.pdf`, 150 dpi q 0.6 | 20.7 pages/s | 3.0 pages/s |316| Images → PDF, 20 JPEG 2000 × 1500, pass-through | 60 images/s | 55 images/s |317318PNG export is dominated by PNG encoding in ImageIO (JPEG at the same size is 3 to 6 times faster).319OCR is dominated by Vision. **“Fast” was not faster than “accurate” on this fixture on macOS 27** (same 4.1 pages/s320for Vision alone); it also supports fewer languages (6 against 33 reported by `supportedRecognitionLanguages()`).321OCR quality on `scan.pdf`: 39 of the 40 lines of page 1 are extracted exactly, 6 800 words placed over 10 pages.322The first recognition after a cold start took about 40 s once (model load); later runs do not pay it.323324Peak resident memory, one operation per process (fixture generation included, `ORIX_PDF_BENCH_CASE=…`):325326| Operation | Peak RSS |327|---|---|328| PDF → PNG 300 dpi, 40 pages | 104 MB |329| `pdf.ocr`, 10 scanned pages at 300 dpi | 586 MB |330| PDF → TXT with OCR, same pages | 624 MB (accurate), 500 MB (fast) |331| `pdf.merge` 5 × 2 000 pages | 163 MB |332| `pdf.split` every page, 2 000 pages | 106 MB |333| `pdf.compress` `scan.pdf` | 391 MB |3343352 000-page synthetic PDF (1 170 146 bytes, test `twoThousandPages` run alone; times from a run under load):336inspect 0.28 s; text export of all pages 0.94 s; extract 21 pages 0.12 s; split every 500 pages 0.84 s; split337into 2 000 files 4.95 s; merge with itself (4 000 pages) 0.57 s; rotate all pages 0.14 s; render 3 pages 0.04 s;338compression attempt 0.33 s. **Peak RSS of the whole test: 163 MB.**339340## Safety limits341342256 megapixels and 32 000 px per rendered page; 1.5 gigapixels per multi-page TIFF; 400 megapixels and 65 000 px343per source or extracted image; 5 000 sources per merge / images → PDF; 200 000 entries per page list; 100 000344outline entries and 48 levels; 100 000 extracted images; content scanning stops after 200 000 `Do` operators and345six levels of nested forms. Declared sizes are checked against the actual data before an image is built.346Nothing in a PDF is executed (JavaScript is only detected). Malformed inputs tested: random bytes, empty file,347header only, missing file, second half of a file, first half of a file, a page tree that references itself with348an absurd media box and a form XObject that draws itself.349350## PDFKit behaviours relied on (observed on macOS 27.0 only)3513521. `PDFDocument.write` calls `draw(with:to:)` on pages of a delegate-provided subclass, with a PDF context in353 unrotated page coordinates measured from the media-box corner. OCR and compression depend on it.3542. PDFKit creates those page objects without running Swift initialisers: a stored array property crashed355 (`EXC_BAD_ACCESS`); the subclass therefore has a single optional reference as its only stored property.3563. Edits to the outline of a document loaded from a file are **not written** (an added entry disappeared on357 save, a new outline root was ignored); outlines are written for documents created with `PDFDocument()`.358 This is why merge / split / extract build new documents. An existing outline is carried by plain rewrites.3594. A plain rewrite of a loaded document keeps attachments, tags, XMP, AcroForm, JavaScript and encryption.3605. `PDFOutline` children and destinations read as empty once their `PDFDocument` is released.3616. `PDFDocument.unlock(withPassword:)` returns `true` on a document that is not locked even with a wrong password;362 `permissionsStatus` is what tells owner from user.363364## Evaluated and NOT implemented365366- **PDF → HTML**: not attempted; belongs with the documents engine if wanted.367- **Images in PDF → DOCX**: AppKit's DOCX writer drops attachments (measured). Tables, columns, lists, Word styles:368 not reconstructed.369- **Own PDF object rewriter / incremental-update writer** (for byte-preserving OCR and compression, and to keep370 tags and attachments): not implemented; reasons in the two “alternatives” tables.371- **Linearised (“fast web view”) output, PDF/A, PDF/X**: PDFKit offers no control; only the linearisation flag of372 the source is reported. Whether outputs happen to be linearised was not checked.373- **Tagged-PDF preservation through merge / split / OCR / compression, attachments through those operations, XMP374 rewriting, digital signatures** (reading, validating, preserving), **form flattening**, **redaction**.375- **CCITT / JBIG2 image extraction; Separation / DeviceN / Lab images; inline images; stencil masks.**376- **Rotation by arbitrary angles, cropping, resizing pages, N-up, watermarks, page numbers.**377- **Greyscale or monochrome conversion in compression, font subsetting, removal of unused objects.**378- **OCR with `RecognizeDocumentsRequest`** (tables, paragraphs): evaluated, not used.379- **Decrypting without a password, or removing restrictions without the owner password**: refused by design.380- **HEIC / WebP / AVIF as page-export formats**: only PNG, JPEG and TIFF are declared.381382## Known defects and gaps383384- Not run on macOS 15 or 26 (see the top of this file).385- “Fast” recognition brings no speed on macOS 27 in our measurement; the option is kept because it is a real386 Vision setting, but the label promises more than was measured.387- OCR and compression rewrite every page through Quartz, including pages that need nothing: output content streams388 are not byte-identical to the source, lossless (Flate) images are re-deflated, and a media box with a non-zero389 origin is moved to (0, 0).390- A merged file made from a locked restricted source takes the open password of the first such source.391- The DOCX / RTF path is validated on one synthetic layout; real multi-column documents will produce paragraphs in392 PDFKit's reading order with no column structure.393- Positional text order interleaves the columns of multi-column pages (it is an option, off by default).394- EXIF orientations 2, 4, 5, 7, JPEG 2000 extraction, animated WebP / APNG, the end-to-end pixel cap, signed PDFs395 and encrypted sources through OCR / compression have no test.396- `preflight` opens the document synchronously (and samples up to 200 pages for annotations); on very large files397 it is not instantaneous.398