Sources/OrgApp/PDFExport.swift

194 lines · 9401 bytes

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