Sources/OrgApp/PDFExport.swift
232 lines · 11465 bytes
1import Foundation
2import OrgCore
3import PDFKit
4import UniformTypeIdentifiers
5import WebKit
6#if os(macOS)
7import AppKit
8#else
9import UIKit
10#endif
11
12/// PDF from the HTML export, laid out and paginated by WebKit as printing does: no Emacs or TeX.
13@MainActor
14public enum PDFExport {
15 /// US Letter where it's the custom, A4 elsewhere.
16 nonisolated static func usesLetter(_ region: String? = Locale.current.region?.identifier) -> Bool {
17 ["US", "CA", "MX", "PH", "CL", "CO", "VE", "PR"].contains(region ?? "")
18 }
19
20 public struct Failure: Error, CustomStringConvertible {
21 public let description: String
22 }
23
24 /// The page's margins in points, a font family for the text (empty: the export's own), and
25 /// whether pages are numbered.
26 public struct Options: Sendable, Equatable {
27 public var margin: Int
28 public var font: String
29 public var pageNumbers: Bool
30 public init(margin: Int = 50, font: String = "", pageNumbers: Bool = true) {
31 self.margin = margin
32 self.font = font
33 self.pageNumbers = pageNumbers
34 }
35 }
36
37 /// `printCSS` with the body font, when one is set.
38 static func css(_ options: Options) -> String {
39 guard !options.font.isEmpty else { return printCSS }
40 let family = options.font.replacingOccurrences(of: "\"", with: "")
41 return printCSS.replacingOccurrences(of: "</style>", with: "body { font-family: \"\(family)\", -apple-system, sans-serif; }\n</style>")
42 }
43
44 /// `html` with each `<img>` that names a local file given that file as a `data:` URI.
45 /// Relative paths are read from `directory`; files that can't be read keep their `src`.
46 nonisolated static func inliningImages(_ html: String, directory: URL?) -> String {
47 let pattern = /(<img\b[^>]*?\bsrc=")([^"]*)(")/
48 return html.replacing(pattern) { match in
49 let (_, before, src, after) = match.output
50 guard let uri = dataURI(String(src), directory: directory) else { return String(match.output.0) }
51 return before + uri + after
52 }
53 }
54
55 /// The file an `<img src>` names, as a `data:` URI; nil for remote or unreadable images.
56 nonisolated static func dataURI(_ src: String, directory: URL?) -> String? {
57 let path = src.replacingOccurrences(of: """, with: "\"").replacingOccurrences(of: "<", with: "<")
58 .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "&", with: "&")
59 let url: URL
60 if path.hasPrefix("file://") {
61 guard let parsed = URL(string: path) else { return nil }
62 url = parsed
63 } else if path.hasPrefix("/") {
64 url = URL(fileURLWithPath: path)
65 } else if path.hasPrefix("~/") {
66 url = URL(fileURLWithPath: OrgPaths.expandingTilde(path))
67 } else if !path.contains(":"), let directory {
68 url = directory.appendingPathComponent(path)
69 } else {
70 return nil
71 }
72 guard let data = try? Data(contentsOf: url) else { return nil }
73 let type = UTType(filenameExtension: url.pathExtension)?.preferredMIMEType ?? "application/octet-stream"
74 return "data:\(type);base64,\(data.base64EncodedString())"
75 }
76
77 /// Each page's number, centred in its bottom margin, as an annotation: drawing it into the
78 /// page would mean drawing the page again and losing WebKit's links.
79 static func numberPages(_ data: Data, margin: Int) -> Data {
80 guard let document = PDFDocument(data: data) else { return data }
81 for index in 0..<document.pageCount {
82 guard let page = document.page(at: index) else { continue }
83 let box = page.bounds(for: .mediaBox)
84 let height: CGFloat = 14
85 let bottom = box.minY + max(4, (CGFloat(margin) - height) / 2)
86 let note = PDFAnnotation(bounds: CGRect(x: box.midX - 40, y: bottom, width: 80, height: height), forType: .freeText, withProperties: nil)
87 note.contents = String(index + 1)
88 note.font = .systemFont(ofSize: 9)
89 note.fontColor = .gray
90 note.color = .clear
91 note.alignment = .center
92 let border = PDFBorder()
93 border.lineWidth = 0
94 note.border = border
95 note.isReadOnly = true
96 page.addAnnotation(note)
97 }
98 return document.dataRepresentation() ?? data
99 }
100
101 /// Rules added for paper: the page's own width, light colors, and no breaks inside code,
102 /// tables and figures or right after a heading.
103 static let printCSS = """
104 <style media="all">
105 :root { color-scheme: light; }
106 * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
107 body { max-width: none; margin: 0; padding: 0; font-size: 11pt; background: #fff; color: #222; }
108 pre, table, figure, blockquote, .figure { break-inside: avoid; }
109 h1, h2, h3, h4, h5, h6 { break-after: avoid; }
110 pre { white-space: pre-wrap; overflow-wrap: anywhere; }
111 </style>
112 """
113
114 /// The page `html` (an `HTMLExport.page`) as a PDF. `directory` is the Org file's folder,
115 /// where relative image links are read from.
116 public static func pdf(html: String, directory: URL?, options: Options = Options()) async throws -> Data {
117 let page = html.replacingOccurrences(of: "</head>", with: css(options) + "\n</head>")
118 let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 800, height: 1100))
119 let loader = Loader()
120 webView.navigationDelegate = loader
121 #if os(macOS)
122 webView.appearance = NSAppearance(named: .aqua)
123 // A file beside nothing the user owns, readable with the images it links to. In the
124 // sandbox WebKit's own process can't read the user's folders, so the images go in the page.
125 let sandboxed = Sandbox.isActive
126 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-pdf-\(UUID().uuidString)")
127 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
128 defer { try? FileManager.default.removeItem(at: folder) }
129 let file = folder.appendingPathComponent("page.html")
130 let source = sandboxed ? inliningImages(page, directory: directory) : page
131 let based = directory.map { source.replacingOccurrences(of: "<head>", with: "<head>\n<base href=\"\($0.absoluteString)\">") } ?? source
132 try based.write(to: file, atomically: true, encoding: .utf8)
133 webView.loadFileURL(file, allowingReadAccessTo: sandboxed ? folder : URL(fileURLWithPath: "/"))
134 #else
135 webView.overrideUserInterfaceStyle = .light
136 webView.loadHTMLString(page, baseURL: directory)
137 #endif
138 try await loader.loaded()
139 // MathJax typesets after the page loads.
140 _ = try? await webView.callAsyncJavaScript(
141 "if (window.MathJax && MathJax.startup && MathJax.startup.promise) { await MathJax.startup.promise; }",
142 contentWorld: .page
143 )
144 let data = try await render(webView, margin: CGFloat(max(0, options.margin)))
145 return options.pageNumbers ? numberPages(data, margin: options.margin) : data
146 }
147
148 #if os(macOS)
149 private static func render(_ webView: WKWebView, margin: CGFloat) async throws -> Data {
150 let output = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString).pdf")
151 defer { try? FileManager.default.removeItem(at: output) }
152 let info = (NSPrintInfo.shared.copy() as? NSPrintInfo) ?? NSPrintInfo()
153 info.jobDisposition = .save
154 info.dictionary()[NSPrintInfo.AttributeKey.jobSavingURL] = output
155 info.topMargin = margin
156 info.bottomMargin = margin
157 info.leftMargin = margin
158 info.rightMargin = margin
159 info.horizontalPagination = .fit
160 info.verticalPagination = .automatic
161 info.isHorizontallyCentered = false
162 info.isVerticallyCentered = false
163 let operation = webView.printOperation(with: info)
164 operation.showsPrintPanel = false
165 operation.showsProgressPanel = false
166 operation.view?.frame = webView.bounds
167 // The operation runs modally for a window; this one is never shown.
168 let window = NSWindow(contentRect: webView.bounds, styleMask: .borderless, backing: .buffered, defer: false)
169 window.contentView = webView
170 let done = PrintDone()
171 await withCheckedContinuation { continuation in
172 done.continuation = continuation
173 operation.runModal(for: window, delegate: done, didRun: #selector(PrintDone.printOperationDidRun(_:success:contextInfo:)), contextInfo: nil)
174 }
175 guard done.success, let data = try? Data(contentsOf: output), !data.isEmpty else { throw Failure(description: "The PDF couldn't be made.") }
176 return data
177 }
178
179 private final class PrintDone: NSObject {
180 var continuation: CheckedContinuation<Void, Never>?
181 var success = false
182
183 @objc func printOperationDidRun(_ operation: NSPrintOperation, success: Bool, contextInfo: UnsafeMutableRawPointer?) {
184 self.success = success
185 continuation?.resume()
186 continuation = nil
187 }
188 }
189 #else
190 private static func render(_ webView: WKWebView, margin: CGFloat) async throws -> Data {
191 let letter = usesLetter()
192 let paper = CGRect(x: 0, y: 0, width: letter ? 612 : 595.2, height: letter ? 792 : 841.8)
193 let renderer = UIPrintPageRenderer()
194 renderer.addPrintFormatter(webView.viewPrintFormatter(), startingAtPageAt: 0)
195 renderer.setValue(NSValue(cgRect: paper), forKey: "paperRect")
196 renderer.setValue(NSValue(cgRect: paper.insetBy(dx: margin, dy: margin)), forKey: "printableRect")
197 let data = NSMutableData()
198 UIGraphicsBeginPDFContextToData(data, paper, nil)
199 renderer.prepare(forDrawingPages: NSRange(location: 0, length: renderer.numberOfPages))
200 for page in 0..<renderer.numberOfPages {
201 UIGraphicsBeginPDFPage()
202 renderer.drawPage(at: page, in: UIGraphicsGetPDFContextBounds())
203 }
204 UIGraphicsEndPDFContext()
205 guard renderer.numberOfPages > 0 else { throw Failure(description: "The PDF couldn't be made.") }
206 return data as Data
207 }
208 #endif
209
210 private final class Loader: NSObject, WKNavigationDelegate {
211 private var continuation: CheckedContinuation<Void, Error>?
212 private var result: Result<Void, Error>?
213
214 func loaded() async throws {
215 if let result { return try result.get() }
216 try await withCheckedThrowingContinuation { self.continuation = $0 }
217 }
218
219 private func finish(_ result: Result<Void, Error>) {
220 if let continuation {
221 continuation.resume(with: result)
222 self.continuation = nil
223 } else {
224 self.result = result
225 }
226 }
227
228 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { finish(.success(())) }
229 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { finish(.failure(error)) }
230 func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { finish(.failure(error)) }
231 }
232}