Sources/OrgApp/PDFExport.swift

262 lines · 13044 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: "&quot;", with: "\"").replacingOccurrences(of: "&lt;", with: "<")
 74            .replacingOccurrences(of: "&gt;", with: ">").replacingOccurrences(of: "&amp;", 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    /// MathJax's `tex-svg-full.js`, which the app sets from `OrgMathJax.script`: every TeX
129    /// extension in one file, with SVG output that needs no font files, so nothing is fetched.
130    nonisolated(unsafe) public static var mathJaxURL: URL?
131
132    nonisolated static func bundledMathJax() throws -> String {
133        guard let url = mathJaxURL else { throw Failure(description: "MathJax is missing from the app.") }
134        return try String(contentsOf: url, encoding: .utf8)
135    }
136
137    /// `html` with the CDN's MathJax replaced by the bundled one, in the page. The configuration
138    /// before it stays.
139    nonisolated static func bundlingMathJax(_ html: String) throws -> String {
140        guard html.contains(HTMLExport.mathJaxScript) else { return html }
141        return html.replacingOccurrences(of: HTMLExport.mathJaxScript, with: "<script id=\"MathJax-script\">\(try bundledMathJax())</script>")
142    }
143
144    /// The page `html` (an `HTMLExport.page`) as a PDF. `directory` is the Org file's folder,
145    /// where relative image links are read from.
146    public static func pdf(html: String, directory: URL?, options: Options = Options()) async throws -> Data {
147        let page = try bundlingMathJax(html).replacingOccurrences(of: "</head>", with: css(options) + "\n</head>")
148        let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 800, height: 1100))
149        let loader = Loader()
150        webView.navigationDelegate = loader
151        #if os(macOS)
152        webView.appearance = NSAppearance(named: .aqua)
153        // A file beside nothing the user owns, readable with the images it links to. In the
154        // sandbox WebKit's own process can't read the user's folders, so the images go in the page.
155        let sandboxed = Sandbox.isActive
156        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-pdf-\(UUID().uuidString)")
157        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
158        defer { try? FileManager.default.removeItem(at: folder) }
159        let file = folder.appendingPathComponent("page.html")
160        let source = sandboxed ? inliningImages(page, directory: directory) : page
161        let based = directory.map { source.replacingOccurrences(of: "<head>", with: "<head>\n<base href=\"\($0.absoluteString)\">") } ?? source
162        try based.write(to: file, atomically: true, encoding: .utf8)
163        webView.loadFileURL(file, allowingReadAccessTo: sandboxed ? folder : URL(fileURLWithPath: "/"))
164        #else
165        webView.overrideUserInterfaceStyle = .light
166        webView.loadHTMLString(page, baseURL: directory)
167        #endif
168        try await loader.loaded()
169        // MathJax typesets after the page loads.
170        _ = try? await webView.callAsyncJavaScript(
171            "if (window.MathJax && MathJax.startup && MathJax.startup.promise) { await MathJax.startup.promise; }",
172            contentWorld: .page
173        )
174        let data = try await render(webView, margin: CGFloat(max(0, options.margin)))
175        return options.pageNumbers ? numberPages(data, margin: options.margin) : data
176    }
177
178    #if os(macOS)
179    private static func render(_ webView: WKWebView, margin: CGFloat) async throws -> Data {
180        let output = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString).pdf")
181        defer { try? FileManager.default.removeItem(at: output) }
182        let info = (NSPrintInfo.shared.copy() as? NSPrintInfo) ?? NSPrintInfo()
183        info.jobDisposition = .save
184        info.dictionary()[NSPrintInfo.AttributeKey.jobSavingURL] = output
185        info.topMargin = margin
186        info.bottomMargin = margin
187        info.leftMargin = margin
188        info.rightMargin = margin
189        info.horizontalPagination = .fit
190        info.verticalPagination = .automatic
191        info.isHorizontallyCentered = false
192        info.isVerticallyCentered = false
193        let operation = webView.printOperation(with: info)
194        operation.showsPrintPanel = false
195        operation.showsProgressPanel = false
196        operation.view?.frame = webView.bounds
197        // The operation runs modally for a window; this one is never shown.
198        let window = NSWindow(contentRect: webView.bounds, styleMask: .borderless, backing: .buffered, defer: false)
199        window.contentView = webView
200        let done = PrintDone()
201        await withCheckedContinuation { continuation in
202            done.continuation = continuation
203            operation.runModal(for: window, delegate: done, didRun: #selector(PrintDone.printOperationDidRun(_:success:contextInfo:)), contextInfo: nil)
204        }
205        guard done.success, let data = try? Data(contentsOf: output), !data.isEmpty else { throw Failure(description: "The PDF couldn't be made.") }
206        return data
207    }
208
209    private final class PrintDone: NSObject {
210        var continuation: CheckedContinuation<Void, Never>?
211        var success = false
212
213        @objc func printOperationDidRun(_ operation: NSPrintOperation, success: Bool, contextInfo: UnsafeMutableRawPointer?) {
214            self.success = success
215            continuation?.resume()
216            continuation = nil
217        }
218    }
219    #else
220    private static func render(_ webView: WKWebView, margin: CGFloat) async throws -> Data {
221        let letter = usesLetter()
222        let paper = CGRect(x: 0, y: 0, width: letter ? 612 : 595.2, height: letter ? 792 : 841.8)
223        let renderer = UIPrintPageRenderer()
224        renderer.addPrintFormatter(webView.viewPrintFormatter(), startingAtPageAt: 0)
225        renderer.setValue(NSValue(cgRect: paper), forKey: "paperRect")
226        renderer.setValue(NSValue(cgRect: paper.insetBy(dx: margin, dy: margin)), forKey: "printableRect")
227        let data = NSMutableData()
228        UIGraphicsBeginPDFContextToData(data, paper, nil)
229        renderer.prepare(forDrawingPages: NSRange(location: 0, length: renderer.numberOfPages))
230        for page in 0..<renderer.numberOfPages {
231            UIGraphicsBeginPDFPage()
232            renderer.drawPage(at: page, in: UIGraphicsGetPDFContextBounds())
233        }
234        UIGraphicsEndPDFContext()
235        guard renderer.numberOfPages > 0 else { throw Failure(description: "The PDF couldn't be made.") }
236        return data as Data
237    }
238    #endif
239
240    private final class Loader: NSObject, WKNavigationDelegate {
241        private var continuation: CheckedContinuation<Void, Error>?
242        private var result: Result<Void, Error>?
243
244        func loaded() async throws {
245            if let result { return try result.get() }
246            try await withCheckedThrowingContinuation { self.continuation = $0 }
247        }
248
249        private func finish(_ result: Result<Void, Error>) {
250            if let continuation {
251                continuation.resume(with: result)
252                self.continuation = nil
253            } else {
254                self.result = result
255            }
256        }
257
258        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { finish(.success(())) }
259        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { finish(.failure(error)) }
260        func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { finish(.failure(error)) }
261    }
262}