Repository Public
1<!--2ORIX Docs3File: docs/architecture/pdf.md4Description: PDF publishing: what the exporter writes, how tracked changes and comments are treated, what is not claimed, and known limits.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->8# PDF publishing910Code: `Packages/ORIXDocsKit/Sources/DocLayout/PDFPublisher.swift`, drawing in `PageRenderer.swift`, entry point `DocumentConverter.export(_:format:pdfOptions:)` (`DocAutomation`).11Tests: `Tests/DocLayoutTests/PDFTests.swift` (`PDFPublishingTests`), `SmokeTests.swift` (`TemplateRenderingTests`).12Background and the survey of what Core Graphics can express: [technology-evaluation.md, section 8](../research/technology-evaluation.md#8-pdf-output).1314## Principle1516A PDF is the paginated layout drawn by the same `PageRenderer` that paints the screen, into a Core Graphics PDF context (`CGContext(consumer:mediaBox:_:)`). There is no second layout or drawing path, and no post-processing of the file: everything, including the outline, is written through that one context. Printing uses the same output — `ORIXDocument.printOperation(withSettings:)` exports a PDF and prints it with PDFKit.1718`PDFPublisher.publish(_:citations:options:cache:)` lays the document out with `PDFPublisher.layoutOptions` (`markup: .none`, `showComments: false`, `forPrint: true`) and calls `publish(_:layout:options:images:)`, which returns a `PDFResult` (data, page count, notes).1920`screenAndPrintLayoutsPaginateIdentically` checks, on four templates, that the print layout has the same page count, the same page for every block and the same fragment geometry as the screen layout.2122## What is written2324| Feature | How | Checked by |25|---|---|---|26| Pages | One PDF page per layout page, media box = page size; the context's y axis is flipped so page coordinates have their origin at the top-left. Sections with different paper sizes give pages of different sizes. | `pagesTextAndMetadata` (page count, 612 × 792 media box) |27| Vector text | Glyph runs are drawn with `CTRunDraw` / `CTLineDraw`; nothing is rasterised by the publisher. The fonts in the file are those Core Graphics embeds for the glyphs drawn; the code does not control embedding or subsetting. | `pagesTextAndMetadata` (PDFKit extracts and finds the text, including "café" and "日本語"); `textIsVectorWithEmbeddedFonts` (Poppler `pdffonts`: every font row reports `emb yes`); `popplerExtractsTheSameText` (`pdftotext`) |28| Equations | Drawn as glyphs from the math font by SwiftMath's display list ([layout-engine.md](layout-engine.md#equations)). | `textIsVectorWithEmbeddedFonts` (a font whose name contains "Math" is listed) |29| Images | Decoded once and drawn with `CGContext.draw`; PDF assets are drawn as vector content (`drawPDFPage`). Crop and rotation are applied by clipping and transforming. | `imagesKeepTheirResolution` (Poppler `pdfimages -list` reports the 400 × 240 source pixels) |30| Hyperlinks | For every run with a link, `RenderHooks.link` receives its rectangle. A target with a URL scheme becomes `setURL(_:for:)`. | `externalAndInternalLinks` |31| Internal links | A target `#name` becomes `setDestination(_:for:)` when `name` is a destination on a page that is being published. Contents entries carry such links to their headings. | `externalAndInternalLinks` (the link leads to page 2) |32| Named destinations | `addDestination(_:at:)` for every heading id, caption paragraph id and bookmark name, 6 pt above the top of the paragraph that holds it. | indirectly, through the internal link |33| Metadata | Info dictionary: creator "ORIX Docs", and title, author, subject, keywords (joined with ", ") when not empty. | `pagesTextAndMetadata` |34| Outline | `CGPDFContextSetOutline` with a dictionary built from `Numbering.outline`: title (heading number and text), 1-based destination page, destination rectangle, children by heading level. On by default (`includeOutline`). | `outlineMirrorsTheHeadings` |35| Structure tags | See below. On by default (`tagged`). | `structureTagsArePresentWhenRequested` |36| Crop marks | With `cropMarks`, each page is enlarged by 24 pt + `bleed` on every side, `TrimBox` and `BleedBox` are declared, and 0.25 pt marks 14 pt long are drawn at the four corners outside the bleed. | `cropMarksEnlargeThePageAndDeclareTheTrimBox` |37| Page range | `pageRange` is a 1-based inclusive range of layout pages. Outline entries and internal links whose target is outside the range are left out. | `pageRangeLimitsTheOutput` |3839The Poppler-based tests look for the tools in `/opt/homebrew/bin` and return early, printing `ORIX-PDF-SKIP …`, when a tool is not installed. `docs/reports/test-results.json` (written by `Scripts/test.sh`) records the engine test run as a whole — number of tests and pass or fail — not the outcome of individual tests, and not whether the Poppler checks ran or were skipped. This document therefore describes what the tests check, not a validation result.4041`TemplateRenderingTests.everyTemplateLaysOutAndPublishes` publishes every template and reopens the result with PDFKit.4243## Tracked changes and comments4445* `publish(_:citations:options:cache:)` works on a **copy** of the document in which every pending change has been accepted (`resolveChanges(accept: true)`), so deleted text is not in the file at all, not even hidden. The document being edited is not modified. Test: `pendingChangesArePublishedAsAcceptedWithoutTouchingTheDocument`.46* Comments are not exported: no annotations are written and the comment tint is off (`showComments: false`).47* Change bars and break markers are editor decorations and are skipped (`forPrint`).48* `DocumentConverter.preflight(_:format:)` tells the user about both before exporting ("The PDF shows the document as if every pending change were accepted", "Comments are not included in the PDF"), and lists substituted fonts.49* The lower-level `publish(_:layout:options:images:)` draws whatever layout it is given; a caller that passes a layout computed with markup gets the markup colours in the file.5051## Structure tags5253With `PDFOptions.tagged`, the render hooks call the Core Graphics tagging functions available since macOS 10.15 (`CGPDFContextBeginTag` / `CGPDFContextEndTag`), which build the structure tree from the nesting and order of the calls made while drawing:5455| Content | Tag |56|---|---|57| Body paragraph, paragraph in a table cell | `Paragraph` |58| Paragraph whose outline level is 1–9 | `Header1` … `Header6` (levels above 6 map to 6) |59| List item, and any other non-heading paragraph that has a label | `ListItem` |60| Footnote and endnote paragraphs | `Note` |61| Image, shape | `Figure` with the alternative text (a shape falls back to its text) |62| Equation | `Figure` with the LaTeX source as alternative text |63| Table borders and shading | `Table` |6465`structureTagsArePresentWhenRequested` checks only that the file contains a `StructTreeRoot` when tagging is on and none when it is off.6667## What is not claimed6869**No conformance to PDF/A or PDF/UA is claimed, and none must be advertised.** The reasons are stated in the research document's requirements ([section 8](../research/technology-evaluation.md#8-pdf-output)):7071* no validator (veraPDF or equivalent) is installed on the build machine and no validation script or report exists in the repository;72* the exporter does not set `kCGPDFContextCreatePDFA`, an output intent, or XMP metadata;73* the tag structure falls short of what PDF/UA requires (see "Known limits"), and PDF/UA also needs human review of reading order and alternative texts.7475The export sheet's wording follows this ("Conformance to PDF/UA is not claimed", `FileSheets.swift`), as does the comment on `PDFOptions.tagged`.7677## Known limits7879Structure:8081* **Headers and footers are left untagged.** `PageRenderer.drawText` opens no tag for header and footer fragments. The tagging API used here cannot mark artifacts; `PDFPublisher` contains a mapping from an `.artifact` role to a paragraph tag, but the renderer never emits that role. Watermarks, page borders, rules and crop marks are untagged as well.82* **Tables carry no row or cell structure.** The `Table` tag encloses only the drawing of borders and shading. Cell text is drawn afterwards, with the other text fragments, as `Paragraph` elements outside the table element. The roles `tableRow`, `tableHeaderCell`, `tableDataCell` and `caption` exist in `ContentRole` but nothing emits them; captions are tagged as paragraphs.83* **Lists** are flat `ListItem` elements without an enclosing list, label or body.84* **Reading order is drawing order**: tables' frames, then text fragments in placement order (body by column, footnotes at each column end, then headers and footers), then floats in front of text.85* **A paragraph split across pages** becomes one element per fragment.86* **Equations are figures**, not formula elements; their accessible description is LaTeX source.87* **No document language** is written (no `/Lang`), and run languages are not passed to the tags.88* Links are annotations only; they are not tied to link structure elements.8990Colour and print:9192* **No colour management and no output intent.** Colours are given to Core Graphics as sRGB (or device grey for rules and marks); there is no CMYK conversion.93* **Bleed is declared, not drawn**: the bleed box is set, but page backgrounds and content are painted to the trim size only.94* The document's `PageSetup.background`, when set, is painted; otherwise the page is left transparent (`drawsPaper = false`).9596Content:9798* **Hyphens** added by the hyphenation step are real characters in the text of the file.99* **Bookmark destinations** point to the top of the paragraph that contains the bookmark, not to the bookmark's position in the line.100* **Internal links** to targets that are not headings, captions or bookmarks do nothing.101* **Missing fonts** are substituted ([layout-engine.md](layout-engine.md#font-resolution)) and reported by the preflight, not by `PDFResult.notes`, which is always empty in the current code.102* The PDF version, compression and font subsetting are whatever Core Graphics produces.103* Export time for the benchmark document is in [performance.md](../development/performance.md).104