Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocLayout/PDFPublisher.swift3// Description: PDF publishing: draws the paginated layout with the page renderer into a Core Graphics PDF context (vector text, embedded4// font subsets), then adds hyperlinks, named destinations, document metadata, the outline, structure tags and print marks.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import CoreGraphics10import CoreText11import DocModel1213public struct PDFOptions: Sendable {14 /// Bookmarks panel built from the headings.15 public var includeOutline = true16 /// Structure tags (headings, paragraphs, figures with alternative text, tables). Conformance to PDF/UA is NOT claimed.17 public var tagged = true18 /// Trim marks at the page corners; the page is enlarged to make room for them.19 public var cropMarks = false20 /// Bleed around the trim box, in points (only with `cropMarks`).21 public var bleed: CGFloat = 022 /// 1-based inclusive page range; nil publishes every page.23 public var pageRange: ClosedRange<Int>?24 public init() {}25}2627public struct PDFResult: Sendable {28 public var data: Data29 public var pageCount: Int30 /// Things that could not be honoured (e.g. the outline could not be attached).31 public var notes: [String]32}3334public enum PDFPublisher {35 /// Layout options for publishing: no editor decorations, tracked changes shown as accepted.36 public static let layoutOptions = LayoutOptions(markup: .none, showComments: false, forPrint: true)3738 /// Lays out `doc` for print and publishes it. Pending tracked changes are published as if accepted, without altering the document.39 public static func publish(_ doc: DocumentModel, citations: (any CitationFormatting)? = nil, options: PDFOptions = PDFOptions(), cache: LayoutCache = LayoutCache()) -> PDFResult {40 var clean = doc41 if clean.hasTrackedChanges { clean.resolveChanges(accept: true) }42 let layout = Paginator.layout(clean, citations: citations, options: layoutOptions, cache: cache)43 return publish(clean, layout: layout, options: options)44 }4546 public static func publish(_ doc: DocumentModel, layout: DocumentLayout, options: PDFOptions = PDFOptions(), images: ImageStore = ImageStore()) -> PDFResult {47 let out = NSMutableData()48 let notes: [String] = []49 guard let consumer = CGDataConsumer(data: out as CFMutableData) else { return PDFResult(data: Data(), pageCount: 0, notes: ["Could not create the PDF"]) }50 let margin: CGFloat = options.cropMarks ? 24 + options.bleed : 051 let first = layout.pages.first?.size ?? CGSize(width: 612, height: 792)52 var media = CGRect(x: 0, y: 0, width: first.width + 2 * margin, height: first.height + 2 * margin)53 var info: [CFString: Any] = [kCGPDFContextCreator: "ORIX Docs"]54 if !doc.meta.title.isEmpty { info[kCGPDFContextTitle] = doc.meta.title }55 if !doc.meta.author.isEmpty { info[kCGPDFContextAuthor] = doc.meta.author }56 if !doc.meta.subject.isEmpty { info[kCGPDFContextSubject] = doc.meta.subject }57 if !doc.meta.keywords.isEmpty { info[kCGPDFContextKeywords] = doc.meta.keywords.joined(separator: ", ") }58 guard let ctx = CGContext(consumer: consumer, mediaBox: &media, info as CFDictionary) else { return PDFResult(data: Data(), pageCount: 0, notes: ["Could not create the PDF"]) }5960 let renderer = PageRenderer(doc: doc, layout: layout, images: images)61 renderer.drawsPaper = false62 let pagesToDraw: [Int] = layout.pages.indices.filter { i in options.pageRange.map { $0.contains(i + 1) } ?? true }63 // Internal link targets: headings, captions, bookmarks.64 var targets: [Int: [(name: String, y: CGFloat)]] = [:]65 var targetIDs = Set(layout.numbering.outline.map(\.id)).union(layout.numbering.captions.keys)66 for (name, id) in layout.numbering.bookmarks { targetIDs.insert(id); if let p = layout.pageOfBlock[id] { targets[p, default: []].append((name, layout.yOfBlock[id] ?? 0)) } }67 for id in targetIDs { if let p = layout.pageOfBlock[id] { targets[p, default: []].append((id, layout.yOfBlock[id] ?? 0)) } }68 let drawn = Set(pagesToDraw)69 let reachable = Set(targets.filter { drawn.contains($0.key) }.flatMap { $0.value.map(\.name) })7071 for pi in pagesToDraw {72 let page = layout.pages[pi]73 let w = page.size.width, h = page.size.height74 var box = CGRect(x: 0, y: 0, width: w + 2 * margin, height: h + 2 * margin)75 var pageInfo: [CFString: Any] = [kCGPDFContextMediaBox: Data(bytes: &box, count: MemoryLayout<CGRect>.size)]76 if options.cropMarks {77 var trim = CGRect(x: margin, y: margin, width: w, height: h)78 var bleed = trim.insetBy(dx: -options.bleed, dy: -options.bleed)79 pageInfo[kCGPDFContextTrimBox] = Data(bytes: &trim, count: MemoryLayout<CGRect>.size)80 pageInfo[kCGPDFContextBleedBox] = Data(bytes: &bleed, count: MemoryLayout<CGRect>.size)81 }82 ctx.beginPDFPage(pageInfo as CFDictionary)83 ctx.saveGState()84 // Page coordinates: origin at the top-left corner of the trimmed page, y pointing down.85 ctx.translateBy(x: margin, y: h + margin)86 ctx.scaleBy(x: 1, y: -1)87 func toPDF(_ r: CGRect) -> CGRect { CGRect(x: margin + r.minX, y: margin + h - r.maxY, width: r.width, height: r.height) }88 renderer.hooks.link = { rect, target in89 if target.hasPrefix("#") {90 let name = String(target.dropFirst())91 if reachable.contains(name) { ctx.setDestination(name as CFString, for: toPDF(rect)) }92 } else if let url = URL(string: target), url.scheme != nil {93 ctx.setURL(url as CFURL, for: toPDF(rect))94 }95 }96 if options.tagged {97 renderer.hooks.begin = { role in98 switch role {99 case .paragraph: CGPDFContextBeginTag(ctx, .paragraph, [:] as CFDictionary)100 case .heading(let n):101 let types: [CGPDFTagType] = [.header1, .header2, .header3, .header4, .header5, .header6]102 CGPDFContextBeginTag(ctx, types[max(0, min(5, n - 1))], [:] as CFDictionary)103 case .figure(let alt): CGPDFContextBeginTag(ctx, .figure, (alt.isEmpty ? [:] : [CGPDFTagProperty.alternativeText.rawValue as String: alt]) as CFDictionary)104 case .table: CGPDFContextBeginTag(ctx, .table, [:] as CFDictionary)105 case .tableRow: CGPDFContextBeginTag(ctx, .tableRow, [:] as CFDictionary)106 case .tableHeaderCell: CGPDFContextBeginTag(ctx, .tableHeaderCell, [:] as CFDictionary)107 case .tableDataCell: CGPDFContextBeginTag(ctx, .tableDataCell, [:] as CFDictionary)108 case .listItem: CGPDFContextBeginTag(ctx, .listItem, [:] as CFDictionary)109 case .note: CGPDFContextBeginTag(ctx, .note, [:] as CFDictionary)110 case .caption: CGPDFContextBeginTag(ctx, .caption, [:] as CFDictionary)111 case .artifact: CGPDFContextBeginTag(ctx, .paragraph, [:] as CFDictionary)112 }113 }114 renderer.hooks.end = { CGPDFContextEndTag(ctx) }115 }116 for t in targets[pi] ?? [] { ctx.addDestination(t.name as CFString, at: CGPoint(x: margin, y: margin + h - max(0, t.y - 6))) }117 renderer.draw(page: pi, in: ctx)118 ctx.restoreGState()119 if options.cropMarks { drawCropMarks(ctx, trim: CGRect(x: margin, y: margin, width: w, height: h), bleed: options.bleed) }120 ctx.endPDFPage()121 }122 if options.includeOutline, !layout.numbering.outline.isEmpty {123 CGPDFContextSetOutline(ctx, outline(layout: layout, pagesDrawn: pagesToDraw, margin: margin) as CFDictionary)124 }125 ctx.closePDF()126 let data = out as Data127 return PDFResult(data: data, pageCount: pagesToDraw.count, notes: notes)128 }129130 static func drawCropMarks(_ ctx: CGContext, trim: CGRect, bleed: CGFloat) {131 ctx.saveGState()132 ctx.setStrokeColor(CGColor(gray: 0, alpha: 1))133 ctx.setLineWidth(0.25)134 let gap = bleed + 3, len: CGFloat = 14135 for (x, dx) in [(trim.minX, -1.0), (trim.maxX, 1.0)] {136 for (y, dy) in [(trim.minY, -1.0), (trim.maxY, 1.0)] {137 ctx.move(to: CGPoint(x: x + dx * gap, y: y)); ctx.addLine(to: CGPoint(x: x + dx * (gap + len), y: y))138 ctx.move(to: CGPoint(x: x, y: y + dy * gap)); ctx.addLine(to: CGPoint(x: x, y: y + dy * (gap + len)))139 }140 }141 ctx.strokePath()142 ctx.restoreGState()143 }144145 /// The heading outline in the dictionary form Core Graphics expects (see CGPDFDocument.h): a root holding only children;146 /// each item has a title, a 1-based destination page, a destination rectangle and optional children.147 static func outline(layout: DocumentLayout, pagesDrawn: [Int], margin: CGFloat) -> [String: Any] {148 final class Node { var dict: [String: Any]; var children: [Node] = []; let level: Int; init(_ d: [String: Any], _ l: Int) { dict = d; level = l } }149 let pageNumber = Dictionary(uniqueKeysWithValues: pagesDrawn.enumerated().map { ($1, $0 + 1) })150 let root = Node([:], 0)151 var stack = [root]152 for e in layout.numbering.outline {153 guard let lp = layout.pageOfBlock[e.id], let number = pageNumber[lp] else { continue }154 let size = layout.pages[lp].size155 let y = margin + size.height - max(0, (layout.yOfBlock[e.id] ?? 0) - 6)156 let rect = CGRect(x: margin, y: y - 20, width: size.width, height: 20)157 let node = Node([kCGPDFOutlineTitle as String: (e.number.map { $0 + " " } ?? "") + e.text, kCGPDFOutlineDestination as String: number,158 kCGPDFOutlineDestinationRect as String: rect.dictionaryRepresentation], e.level)159 while stack.count > 1, stack[stack.count - 1].level >= e.level { stack.removeLast() }160 stack[stack.count - 1].children.append(node)161 stack.append(node)162 }163 func build(_ n: Node) -> [String: Any] {164 var d = n.dict165 if !n.children.isEmpty { d[kCGPDFOutlineChildren as String] = n.children.map(build) }166 return d167 }168 return [kCGPDFOutlineChildren as String: root.children.map(build)]169 }170171 /// Renders one page to a bitmap (thumbnails, previews, tests).172 public static func bitmap(page index: Int, doc: DocumentModel, layout: DocumentLayout, scale: CGFloat = 1, images: ImageStore = ImageStore()) -> CGImage? {173 guard layout.pages.indices.contains(index) else { return nil }174 let size = layout.pages[index].size175 let w = Int((size.width * scale).rounded()), h = Int((size.height * scale).rounded())176 guard w > 0, h > 0, let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!,177 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }178 ctx.translateBy(x: 0, y: CGFloat(h))179 ctx.scaleBy(x: scale, y: -scale)180 PageRenderer(doc: doc, layout: layout, images: images).draw(page: index, in: ctx)181 return ctx.makeImage()182 }183}184