Sources/OrgApp/PDFExport.swift

5eef7a168632da902fdd0979d57258320e4fdfc2
orgstar/Sources/OrgApp/PDFExport.swift history · blame · raw

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