SPB Git

Repository Public

pdf.md 10.0 KB

# PDF publishing

Code: Packages/ORIXDocsKit/Sources/DocLayout/PDFPublisher.swift, drawing in PageRenderer.swift, entry point DocumentConverter.export(_:format:pdfOptions:) (DocAutomation). Tests: Tests/DocLayoutTests/PDFTests.swift (PDFPublishingTests), SmokeTests.swift (TemplateRenderingTests). Background and the survey of what Core Graphics can express: technology-evaluation.md, section 8.

# Principle

A 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.

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).

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.

# What is written

Feature How Checked by
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)
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)
Equations Drawn as glyphs from the math font by SwiftMath's display list (layout-engine.md). textIsVectorWithEmbeddedFonts (a font whose name contains "Math" is listed)
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)
Hyperlinks For every run with a link, RenderHooks.link receives its rectangle. A target with a URL scheme becomes setURL(_:for:). externalAndInternalLinks
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)
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
Metadata Info dictionary: creator "ORIX Docs", and title, author, subject, keywords (joined with ", ") when not empty. pagesTextAndMetadata
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
Structure tags See below. On by default (tagged). structureTagsArePresentWhenRequested
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
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

The 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.

TemplateRenderingTests.everyTemplateLaysOutAndPublishes publishes every template and reopens the result with PDFKit.

# Tracked changes and comments

  • 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.
  • Comments are not exported: no annotations are written and the comment tint is off (showComments: false).
  • Change bars and break markers are editor decorations and are skipped (forPrint).
  • 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.
  • 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.

# Structure tags

With 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:

Content Tag
Body paragraph, paragraph in a table cell Paragraph
Paragraph whose outline level is 1–9 Header1 … Header6 (levels above 6 map to 6)
List item, and any other non-heading paragraph that has a label ListItem
Footnote and endnote paragraphs Note
Image, shape Figure with the alternative text (a shape falls back to its text)
Equation Figure with the LaTeX source as alternative text
Table borders and shading Table

structureTagsArePresentWhenRequested checks only that the file contains a StructTreeRoot when tagging is on and none when it is off.

# What is not claimed

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):

  • no validator (veraPDF or equivalent) is installed on the build machine and no validation script or report exists in the repository;
  • the exporter does not set kCGPDFContextCreatePDFA, an output intent, or XMP metadata;
  • 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.

The export sheet's wording follows this ("Conformance to PDF/UA is not claimed", FileSheets.swift), as does the comment on PDFOptions.tagged.

# Known limits

Structure:

  • 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.
  • 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.
  • Lists are flat ListItem elements without an enclosing list, label or body.
  • 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.
  • A paragraph split across pages becomes one element per fragment.
  • Equations are figures, not formula elements; their accessible description is LaTeX source.
  • No document language is written (no /Lang), and run languages are not passed to the tags.
  • Links are annotations only; they are not tied to link structure elements.

Colour and print:

  • 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.
  • Bleed is declared, not drawn: the bleed box is set, but page backgrounds and content are painted to the trim size only.
  • The document's PageSetup.background, when set, is painted; otherwise the page is left transparent (drawsPaper = false).

Content:

  • Hyphens added by the hyphenation step are real characters in the text of the file.
  • Bookmark destinations point to the top of the paragraph that contains the bookmark, not to the bookmark's position in the line.
  • Internal links to targets that are not headings, captions or bookmarks do nothing.
  • Missing fonts are substituted (layout-engine.md) and reported by the preflight, not by PDFResult.notes, which is always empty in the current code.
  • The PDF version, compression and font subsetting are whatever Core Graphics produces.
  • Export time for the benchmark document is in performance.md.
Files main
Menu

Theme