Sources/OrgApp/PDFExport.swift

148 lines · 7100 bytes

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