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