SPB Git

Repository Public License

pdf.md 32.9 KB

# PDF engine (pdf) — compatibility notes

Package Packages/EnginePDF (module EnginePDF, factory makeEngines()), engine id pdf. Apple frameworks only: PDFKit, Core Graphics (CGPDF object and scanner APIs), Quartz (QuartzFilter), Vision, Core Text, ImageIO, AppKit (NSAttributedString document writing). No third-party code, no helper executable, no network.

Everything below was implemented, tested and measured on macOS 27.0 (26A5425a), Apple M5 Max (18 cores, 48 GB), Swift 6.4.2, debug build (swift test). The deployment target is macOS 15.0, but nothing here was run on macOS 15 or 26: several behaviours of PDFKit this engine relies on (listed in “PDFKit behaviours relied on”) were observed on macOS 27 only and must be re-checked on the older systems before release.

Tests: swift test from Packages/EnginePDF — 58 tests in 13 suites, all passing (✔ Test run with 58 tests in 13 suites passed after 13.790 seconds, 2026-11-21; two of them are the benchmark tests, which only run with ORIX_PDF_BENCH=1). Fixtures are generated in code (Core Graphics / Core Text / PDFKit / ImageIO, plus hand-written PDF objects for the features PDFKit cannot author); the only embedded binary is a 34-byte 1 × 1 WebP given as base64.

# Declared paths (24)

Suites are nested in PDFEngineTests. “Keeps” is the preserves set of the path.

Source Destination Operation Status Fidelity Keeps Main limitations Tests
pdf png — supported lossy dimensions flat images; several pages → folder; pixel cap Rendering/singlePageToPNG, severalPagesGoToAFolder, transparentBackground, annotationsCanBeLeftOut, cropBoxVersusMediaBox, stripRenderingIsSeamless
pdf jpeg — supported lossy dimensions same + no transparency, lossy Rendering/pageSelectionWidthAndGreyJPEG
pdf tiff — supported lossy dimensions same; optional multi-page TIFF (memory grows with pages, capped at 1.5 gigapixels) Rendering/multiPageTIFFAndPerPageTIFF
pdf txt — supported partial — text only, PDFKit order; OCR for pages without text TextExport/plainTextWithSeparators, hyphenationRepair, positionalOrderSortsTopToBottom, scannedDocumentIsReportedAndReadWithOCR
pdf markdown — supported partial — only ## Page N headings are added; nothing is escaped or detected TextExport/markdownAddsOnlyPageHeadings, scannedDocumentIsReportedAndReadWithOCR
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
pdf docx — experimental partial textStyles text reconstruction only: no layout, columns, tables, images, vectors RichText/rebuildsParagraphsAndStyles(docx), scannedDocumentsAreRefusedWithAdvice
pdf rtf — experimental partial textStyles same RichText/rebuildsParagraphsAndStyles(rtf)
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
pdf pdf pdf.merge (multiple sources) supported lossless vectorGeometry, images, links, chapters, dimensions, metadata tags, attachments, XMP, JavaScript, AcroForm dictionary, signatures dropped PageOperations/mergeKeepsOrderOutlineAndAnnotations
pdf folder pdf.split supported lossless same same PageOperations/splitModes
pdf pdf pdf.extract-pages supported lossless same same; links to removed pages break (warned) PageOperations/extractDeleteReorder
pdf pdf pdf.delete-pages supported lossless same same PageOperations/extractDeleteReorder
pdf pdf pdf.reorder-pages supported lossless same same PageOperations/extractDeleteReorder
pdf pdf pdf.rotate supported lossless same 90° steps, stored as page rotation; a signature does not stay valid PageOperations/rotationIsWrittenAsPageRotation
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
pdf folder pdf.extract-images supported partial images, transparency CCITT / JBIG2 / Separation / DeviceN / Lab / inline images not extracted (counted) ImageExtraction/jpegBytesAndLosslessPixels, handWrittenColourSpaces, unsupportedFiltersAndInlineImagesAreCounted
pdf pdf pdf.set-metadata supported lossless vectorGeometry, images, links, chapters, dimensions Info dictionary only; XMP is reported, not rewritten PageOperations/metadataCanBeSetAndStripped

Cross-cutting tests: PageLists/* (range syntax), Protection/* (passwords and permission flags on every path), Robustness/malformedAndTruncatedFiles, cancellationStopsTheWork, twoThousandPages, inspectionReportsWhatIsInTheFile, everyDeclaredPathIsListedOnceWithSettings (the 24 ids above are asserted), undeclaredRequestsAreRefused, PageOperations/featureRetentionMatchesThePreflightWarnings.

# Output shape

  • One selected page → one file. Several pages → one directory in the work directory, returned as the single entry of ConversionOutput.files, holding <name>-001.png … (zero-padded page numbers of the source). A multi-page TIFF is one file. pdf.split and pdf.extract-images return one directory.
  • Folder outputs are obtained with context.outputURL(for:extension: "").

# Page-list syntax (PageList, public)

1-3,7,10- — items separated by commas: N, A-B (descending allowed), A- (to the end), -B (from the start). Order and duplicates are kept for extraction and reordering. Out-of-range, empty items, non-ASCII digits and lists expanding to more than 200 000 entries are rejected with invalidOption / limitExceeded. Split by ranges: each comma-separated range is a file; with ; the files are separated by ; and each file can combine several ranges (1-3,7;8-).

# How each part works

# Rendering (PDF → PNG / JPEG / TIFF, thumbnails)

Pages are drawn into one malloc'd buffer strip by strip (about 12 megapixels per strip), so Core Graphics never needs a second full-size surface and cancellation is checked between strips. With annotations: PDFPage.draw; without: CGContext.drawPDFPage with the engine's own box / rotation transform (both routes are tested on rotated pages). Options: DPI or pixel width, sRGB / grey, white / transparent background (PNG and TIFF, colour only), page list, annotations on / off, crop box / media box, JPEG quality, TIFF compression, multi-page TIFF. Caps: 32 000 px per side and 256 megapixels per page; a larger request is rendered at a lower scale with a pixel-cap warning. The cap is unit-tested on the size computation only — no test renders a 256-megapixel page.

Public API: PDFPreview.pageCount(of:password:) and PDFPreview.thumbnail(of:pageIndex:maxPixelSize:password:annotations:) (longest side 16…4096 px, white background, sRGB).

# Text (PDF → TXT / Markdown)

PDFPage.string per page (PDFKit reading order) or, on request, lines sorted by position (top to bottom, pieces of one baseline left to right — for single-column pages only). Options: page separator (blank line, marker line, form feed, nothing), hyphenation repair, page list. Markdown adds ## Page N headings and nothing else. A page counts as having a text layer when it yields at least three letters or digits. Pages without one are read with Vision by default (ocr = “Pages without text”), with an ocr-used warning; with OCR off a document without any text fails with a message saying it is a scanned document and how to turn OCR on. preflight reports scanned-no-text (“… scanned document — use OCR …”) or scanned-ocr.

# Searchable PDF (pdf.ocr) — approach chosen and alternatives

Chosen: keep the original PDFDocument and add the text from a PDFPage subclass while PDFKit writes. The document is opened with a PDFDocumentDelegate returning OverlayPage from classForPage(). When PDFDocument.write(to:) runs, PDFKit calls draw(with:to:) on every page with a PDF context: the override calls super (the original page content goes through Quartz: vector stays vector, text stays text, JPEG streams are copied byte for byte — tested) and then draws the recognised words with CGTextDrawingMode.invisible. Each word is one Core Text run in Helvetica, sized to the height of Vision's word box and stretched horizontally to its width; the gaps between words receive a stretched space; all runs of a line follow the line's baseline (an earlier version that followed each gap's own direction made PDFKit split lines, see the tests). Recognition: VNRecognizeTextRequest on the page rendered at 300 dpi (option, 72–600; capped at 10 000 px a side), accurate or fast, automatic language detection or a list checked against supportedRecognitionLanguages(). Pages that already have text are skipped unless “Every page” is chosen (then a ocr-duplicate-text warning). If nothing is recognised or needed, the original bytes are returned (result = unchanged).

Measured result of this approach (test outlineLinksAnnotationsAndFormsSurvive and the retention test):

  • kept: outline (same entries and nesting), link annotations (URL and internal), form widget and its value, square annotation (still an annotation, not painted into the page), Info metadata, XMP packet, AcroForm dictionary, page sizes and rotation, the scan image itself (same pixel size and filter; a JPEG stream is byte-identical);
  • lost: tag structure (tagged PDF), file attachments, document JavaScript; a digital signature cannot stay valid;
  • changed: a media box that does not start at (0, 0) is moved to the origin by PDFKit (same size; the crop box moves with it; the text layer follows — tested with a hand-written [50 50 662 842] page);
  • accuracy on the fixtures (Helvetica 14–18 pt rendered at 150 and 300 dpi; upright page, /Rotate 90 page, cropped page, offset media box): every probe word found by PDFDocument.findString, selection box covering more than 60 % of the drawn word, centre within 1.87 pt (150 dpi) and 1.71 pt (300 dpi) of the true position.

Alternatives evaluated:

Alternative Result Verdict
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
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
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
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”)

# PDF → DOCX / RTF (experimental)

PDFSelection.selectionsByLine() gives each line with its attributed string (font, size, colour) and bounds. Lines are grouped into paragraphs: a new paragraph starts on a font-size change, a vertical gap above 0.7 line heights, a jump upwards, a first-line indent, or after a line that stops more than 15 % short of the right edge. Lines are joined with a space; a hyphen at a line end followed by a lower-case letter is removed (option). Fonts: family kept when installed, otherwise Helvetica / Times New Roman / Courier New chosen from the font name; size, bold, italic and colour kept. Paragraphs at least 15 % larger than the body size count as headings (they keep their size and get spacing; no Word heading style is written — NSAttributedString cannot express one). Page breaks are form feeds (they round-trip through the DOCX writer — tested). Title / author / subject are carried. Tested on one synthetic two-page layout only, hence .experimental. Placing page images was evaluated and dropped: AppKit's OOXML writer discards attachments (a round-trip of an attributed string with an image attachment produced a DOCX without any media part).

# Images → PDF

One page per image or TIFF frame, written with CGPDFContext. JPEG sources are embedded through CGImage(jpegDataProviderSource:): the PDF holds the original DCT stream (2 406 125-byte JPEG → 2 410 078-byte PDF, and extracting the image returns the source file byte for byte — tested). Other formats are stored losslessly (pixel-exact, alpha kept as a soft mask — tested); “Recompress as JPEG” re-encodes opaque images at the chosen quality. EXIF orientation is applied by the drawing transform (orientations 1, 3, 6, 8 tested; 2, 4, 5, 7 are implemented from the same derivation but not tested). Page size: fit to image (pixels × 72 / dpi, dpi from the file or the option, 72 when absent), A4, Letter, custom (mm), automatic or forced orientation, margins, fit or fill. Optional OCR layer in the same pass, output passwords, title / author. Animated GIF / WebP / APNG: first frame, with an animation-first-frame warning (GIF tested; the WebP fixture is a 1 × 1 still image, animated WebP and APNG are untested).

# Merge, split, extract, delete, reorder

A new PDFDocument receives the page objects of the sources (copies when a page is used twice); annotations travel with their pages; the outline is rebuilt for the pages that survive (an entry whose page is gone is kept only if a child survives, and then points to it). Merge nests each file's outline under an entry named after the file. Split modes: every page, every N pages, ranges, top-level outline entries (files named 001-<title>.pdf, pages before the first entry go to 001-Front matter.pdf). Embedded images are not re-encoded (JPEG extracted from a merged file is byte-identical — tested).

pdf.rotate and pdf.set-metadata modify the opened document and let PDFKit rewrite it.

# What each PDF-producing operation keeps (measured)

Fixture: hand-written PDF with an attachment, /MarkInfo + /StructTreeRoot, XMP, an AcroForm text field, document JavaScript (test featureRetentionMatchesThePreflightWarnings; the feature-dropped preflight warnings are asserted to match this table exactly).

Operation Attachments Tag structure XMP AcroForm dictionary JavaScript Widget annotation
pdf.rotate, pdf.set-metadata kept kept kept kept kept kept
pdf.compress, pdf.ocr (page subclass rewrite) lost lost kept kept lost kept
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

A field created with PDFKit (rich.pdf fixture) has no AcroForm dictionary in the first place; its widget and value (FieldValue42) survive merge, split and extraction. Outline, URL links, internal links (retargeted to the right page), square annotation: kept by merge, reorder, rotate, set-metadata, OCR and compression (structure compared before / after in the tests).

# Compression (pdf.compress) — approach chosen and alternatives

Chosen: a Quartz filter applied inside the page subclass while PDFKit rewrites the document. QuartzFilter(properties:) (public, Quartz framework) is built from a dictionary in the ColorSync .qfilter format (ImageSettings: ImageCompression = ImageJPEGCompress, Compression Quality, ImageScaleSettings / ImageResolution). OverlayPage.draw calls filter.apply(to:), super.draw, filter.remove(from:). Measured: images are resampled to the requested resolution at their drawn size (a 3000-px JPEG drawn 6 in wide becomes 1800 / 900 / 431 px at 300 / 150 / 72 dpi), images below the threshold are not upsampled, opaque Flate images become JPEG, text stays extractable, the outline / links / form field / annotations are kept, the page still has exactly one image XObject (it is not rasterised). If the result is not smaller than the source, it is deleted and the source bytes are copied to the output (result = already optimised, already-optimised warning). When an output password is requested the source bytes cannot be returned: a protected copy is written and reported as not compressed.

Caveats: the dictionary keys are those of .qfilter files (ColorSync Utility), which Apple does not document formally; the behaviour was verified on macOS 27.0 only. Images with a soft mask are downsampled but stay Flate-encoded (measured in the feasibility experiment). The JPEG quality scale is Quartz's, not ImageIO's.

Alternative Result Verdict
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
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
Undocumented "QuartzFilter" key of PDFDocument.write(to:withOptions:) not a public constant not used
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

Measured ratios (fixtures are synthetic: gradients with pixel noise, which JPEG compresses poorly at high quality and very well at low quality — real photographs will differ):

Fixture Settings Before After Ratio
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×
same 150 dpi, q 0.6 (default) 8 222 126 364 207 22.6×
same 72 dpi, q 0.3 8 222 126 48 070 171×
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×
same 100 dpi, q 0.4 613 871 119 484 5.1×
scan.pdf (10 image-only pages, 2550 × 3300 lossless) 150 dpi, q 0.6 8 368 339 6 247 794 1.3×
same 100 dpi, q 0.4 8 368 339 3 187 750 2.6×
text-only PDF, 3 pages default 12 450 attempt 12 483 → original returned (12 450) 1.0× (already optimised)

# Image extraction (pdf.extract-images)

Image XObjects are collected from page resources (inherited resources and nested form XObjects included; the same stream referenced from several pages is written once). CGPDFStreamCopyData returns DCT data as is → .jpg (byte-exact, tested) and JPX data as is → .jp2 / .j2k (no JPX fixture: untested). Everything else is rebuilt from the decoded samples: DeviceGray / RGB / CMYK, CalGray / CalRGB (treated as device), ICCBased (profile used when valid), Indexed, 1–16 bits, Decode arrays, soft masks → alpha; written as PNG (CMYK → sRGB with a warning). Tested by hand-written objects: Indexed RGB, CMYK, 4-bit grey, RGB + soft mask, plus a Separation image and a truncated image that must be skipped. Not extracted, counted in images-skipped (severity data loss): CCITTFax and JBIG2 (not attempted — whether Core Graphics would decode them was not tested), Separation / DeviceN / Lab / Pattern colour spaces, images whose data is shorter than declared. Inline images (BI … EI) are counted on the first 500 selected pages and reported, not extracted. Stencil and colour-key masks are not applied (warning). Images inside patterns and annotation appearance streams are not looked at.

A PDF from which no image file can be produced is refused with a clear error instead of an empty folder (fixed 2026-11-21 — the empty folder was rejected further on by the core with a generic “contains no file”): “This PDF contains no embedded image that can be extracted (…)”, followed by the count of every image that was seen and left out (unsupported encodings by name, images below the minimum size, inline images) and, when the pages hold only text and vector drawings, the advice to convert the PDF to PNG or JPEG instead. preflight says the same before converting (no-images, from a quick scan of the image objects of the first 300 pages; no warning when the document is longer than that or when a page selection is set). Tests: unsupportedFiltersAndInlineImagesAreCounted, pdfWithoutImagesIsRefusedClearlyAndAnnouncedByPreflight.

# Metadata and inspection

pdf.set-metadata edits or clears the Info dictionary through PDFDocument.documentAttributes (title, author, subject, keywords, creator, producer, creation and modification dates; ISO 8601 input). After “Remove existing metadata” the Info dictionary of the test output had no keys left; the output is re-read and anything remaining, or a retained XMP packet, is reported as a warning. XMP is detected, never rewritten. Merge and images → PDF accept a title (and author for images).

inspect (PDF): page count, PDF version, first page size, number of distinct page sizes and rotated pages (first 5 000 pages), encryption and each permission flag, linearisation flag (looks for /Linearized in the first 2 kB), text layer / images drawn / highest image resolution at drawn size / fonts with embedded status (on at most 12 evenly spread pages — the fields say how many were sampled), outline entries, top-level form fields, annotation count, attachments, tagged flag, XMP, JavaScript presence, every string of the Info dictionary. A locked document reports only “encrypted” and that a password is needed (pageCount stays nil). The image resolution ignores /UserUnit and clipping.

inspectableFormats is [.pdf] only (fixed 2026-11-21). The raster formats accepted by images → PDF were listed too, so — depending on the order in which the engines are registered — the PDF engine could be the one asked to inspect a PNG / JPEG / HEIC / TIFF / GIF / BMP / WebP file instead of the image engine. inspect still answers for those formats when called directly (pixel size, frame count, alpha, colour model, depth, DPI and orientation from ImageIO), and preflight of images → PDF reads the image facts it needs itself. Test: everyDeclaredPathIsListedOnceWithSettings asserts inspectableFormats == [.pdf].

# Protected PDFs

  • password opens a locked file, or lifts the restrictions when it is the owner password.
  • Opened without owner rights, the permission flags are enforced before anything is read or written: text / DOCX / image extraction need copying; PNG / JPEG / TIFF export needs printing; merge, split, extract, delete, reorder and rotate need document assembly (or changes); OCR, compression and metadata need changes. Refusals are ConversionError.encryptedInput with the name of the missing permission (tested for every path).
  • A restricted source never yields a less protected PDF: rotate / set-metadata keep the original encryption (PDFKit carries it; the original owner password still works — tested); assembled results are encrypted again with the same open password, a random owner password and the source's permission flags. PDFKit does not read back exactly the flags it is asked to write (asking for 15 gave 207), so each candidate is written, reopened and kept only if it is encrypted and grants nothing the source did not; otherwise a narrower set is tried, and the operation fails rather than weaken the protection. Setting new passwords requires the owner password.
  • With owner rights the result is unencrypted unless output.password.user / output.password.owner are set; an encryption-not-carried warning says so.
  • Not covered by a test: OCR / compression of an encrypted file opened with its owner password (the encrypted fact and the warning report what was actually written), and signed PDFs.

OptionDescriptor has no “secret” kind: password, output.password.user and output.password.owner are plain text options. The app should mask them and keep them out of presets and history.

# Measured performance

Machine: Apple M5 Max, macOS 27.0, debug build. The Mac was shared with other sessions during the runs (load average 58 to 91 on 18 cores, later 270), so these are pessimistic figures; where two runs differ both are given. Reproduce with ORIX_PDF_BENCH=1 swift test --filter Benchmarks.

Fixture office.pdf: 40 Letter pages, 40 lines of 11 pt text and one 1200 × 800 JPEG per page. Fixture scan.pdf: 10 image-only Letter pages, 40 lines of 11 pt text rasterised at 300 dpi.

Measurement Run 1 Run 2 (best of 3)
PDF → PNG, 150 dpi (1275 × 1650) 19.7 pages/s 16.0 pages/s
PDF → PNG, 300 dpi (2550 × 3300) 4.7 pages/s 4.6 pages/s
PDF → JPEG, 150 dpi 69.9 pages/s 63.3 pages/s
PDF → JPEG, 300 dpi 26.8 pages/s 27.2 pages/s
PDF → TIFF (LZW), 150 dpi 24.4 pages/s 27.3 pages/s
PDF → TXT 646 pages/s 528 pages/s
PDF → DOCX 102 pages/s 91 pages/s
pdf.ocr accurate, automatic language (render + Vision + rewrite) 3.31 pages/s 3.11 pages/s
pdf.ocr accurate, en-US 3.63 pages/s 2.04 pages/s
pdf.ocr fast, automatic language 3.77 pages/s 3.18 pages/s
pdf.ocr fast, en-US 3.80 pages/s 2.93 pages/s
Vision alone, accurate, 2550 × 3300 pages — 4.1 pages/s
Vision alone, fast — 4.1 pages/s
Rendering the 10 scanned pages at 300 dpi — 0.24 s in total
pdf.merge, 5 × 2 000 pages 4 937 pages/s 1 758 pages/s
pdf.split, every page, 2 000 pages (2 000 files) 1 178 pages/s 293 pages/s
pdf.split, every 100 pages, 2 000 pages 8 125 pages/s 1 784 pages/s
pdf.compress office.pdf, 150 dpi q 0.6 225 pages/s 57 pages/s
pdf.compress scan.pdf, 150 dpi q 0.6 20.7 pages/s 3.0 pages/s
Images → PDF, 20 JPEG 2000 × 1500, pass-through 60 images/s 55 images/s

PNG export is dominated by PNG encoding in ImageIO (JPEG at the same size is 3 to 6 times faster). OCR is dominated by Vision. “Fast” was not faster than “accurate” on this fixture on macOS 27 (same 4.1 pages/s for Vision alone); it also supports fewer languages (6 against 33 reported by supportedRecognitionLanguages()). OCR quality on scan.pdf: 39 of the 40 lines of page 1 are extracted exactly, 6 800 words placed over 10 pages. The first recognition after a cold start took about 40 s once (model load); later runs do not pay it.

Peak resident memory, one operation per process (fixture generation included, ORIX_PDF_BENCH_CASE=…):

Operation Peak RSS
PDF → PNG 300 dpi, 40 pages 104 MB
pdf.ocr, 10 scanned pages at 300 dpi 586 MB
PDF → TXT with OCR, same pages 624 MB (accurate), 500 MB (fast)
pdf.merge 5 × 2 000 pages 163 MB
pdf.split every page, 2 000 pages 106 MB
pdf.compress scan.pdf 391 MB

2 000-page synthetic PDF (1 170 146 bytes, test twoThousandPages run alone; times from a run under load): inspect 0.28 s; text export of all pages 0.94 s; extract 21 pages 0.12 s; split every 500 pages 0.84 s; split into 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; compression attempt 0.33 s. Peak RSS of the whole test: 163 MB.

# Safety limits

256 megapixels and 32 000 px per rendered page; 1.5 gigapixels per multi-page TIFF; 400 megapixels and 65 000 px per source or extracted image; 5 000 sources per merge / images → PDF; 200 000 entries per page list; 100 000 outline entries and 48 levels; 100 000 extracted images; content scanning stops after 200 000 Do operators and six levels of nested forms. Declared sizes are checked against the actual data before an image is built. Nothing in a PDF is executed (JavaScript is only detected). Malformed inputs tested: random bytes, empty file, header only, missing file, second half of a file, first half of a file, a page tree that references itself with an absurd media box and a form XObject that draws itself.

# PDFKit behaviours relied on (observed on macOS 27.0 only)

  1. PDFDocument.write calls draw(with:to:) on pages of a delegate-provided subclass, with a PDF context in unrotated page coordinates measured from the media-box corner. OCR and compression depend on it.
  2. PDFKit creates those page objects without running Swift initialisers: a stored array property crashed (EXC_BAD_ACCESS); the subclass therefore has a single optional reference as its only stored property.
  3. Edits to the outline of a document loaded from a file are not written (an added entry disappeared on save, a new outline root was ignored); outlines are written for documents created with PDFDocument(). This is why merge / split / extract build new documents. An existing outline is carried by plain rewrites.
  4. A plain rewrite of a loaded document keeps attachments, tags, XMP, AcroForm, JavaScript and encryption.
  5. PDFOutline children and destinations read as empty once their PDFDocument is released.
  6. PDFDocument.unlock(withPassword:) returns true on a document that is not locked even with a wrong password; permissionsStatus is what tells owner from user.

# Evaluated and NOT implemented

  • PDF → HTML: not attempted; belongs with the documents engine if wanted.
  • Images in PDF → DOCX: AppKit's DOCX writer drops attachments (measured). Tables, columns, lists, Word styles: not reconstructed.
  • Own PDF object rewriter / incremental-update writer (for byte-preserving OCR and compression, and to keep tags and attachments): not implemented; reasons in the two “alternatives” tables.
  • Linearised (“fast web view”) output, PDF/A, PDF/X: PDFKit offers no control; only the linearisation flag of the source is reported. Whether outputs happen to be linearised was not checked.
  • Tagged-PDF preservation through merge / split / OCR / compression, attachments through those operations, XMP rewriting, digital signatures (reading, validating, preserving), form flattening, redaction.
  • CCITT / JBIG2 image extraction; Separation / DeviceN / Lab images; inline images; stencil masks.
  • Rotation by arbitrary angles, cropping, resizing pages, N-up, watermarks, page numbers.
  • Greyscale or monochrome conversion in compression, font subsetting, removal of unused objects.
  • OCR with RecognizeDocumentsRequest (tables, paragraphs): evaluated, not used.
  • Decrypting without a password, or removing restrictions without the owner password: refused by design.
  • HEIC / WebP / AVIF as page-export formats: only PNG, JPEG and TIFF are declared.

# Known defects and gaps

  • Not run on macOS 15 or 26 (see the top of this file).
  • “Fast” recognition brings no speed on macOS 27 in our measurement; the option is kept because it is a real Vision setting, but the label promises more than was measured.
  • OCR and compression rewrite every page through Quartz, including pages that need nothing: output content streams are not byte-identical to the source, lossless (Flate) images are re-deflated, and a media box with a non-zero origin is moved to (0, 0).
  • A merged file made from a locked restricted source takes the open password of the first such source.
  • The DOCX / RTF path is validated on one synthetic layout; real multi-column documents will produce paragraphs in PDFKit's reading order with no column structure.
  • Positional text order interleaves the columns of multi-column pages (it is an option, off by default).
  • EXIF orientations 2, 4, 5, 7, JPEG 2000 extraction, animated WebP / APNG, the end-to-end pixel cap, signed PDFs and encrypted sources through OCR / compression have no test.
  • preflight opens the document synchronously (and samples up to 200 pages for annotations); on very large files it is not instantaneous.
Files main
Menu

Theme