-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExportToPDF.swift
70 lines (63 loc) · 1.89 KB
/
ExportToPDF.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import Foundation
import WebKit
class WebViewNavigationDelegate: NSObject, WKNavigationDelegate {
private let outputURL: URL
var onFinished: (@Sendable () -> Void)?
init(outputURL: URL) {
self.outputURL = outputURL
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
Task { @MainActor [outputURL, onFinished] in
let margins = NSEdgeInsets(
top: 0,
left: -40,
bottom: 0,
right: -40
)
let pageWidth: CGFloat = 595.22
let pageHeight: CGFloat = 841.85
let printableWidth = pageWidth - margins.left - margins.right
let printableHeight = pageHeight - margins.top - margins.bottom
let rect = CGRect(
x: margins.left,
y: margins.top,
width: printableWidth,
height: printableHeight
)
webView.frame = rect
webView.createPDF { result in
switch result {
case .success(let data):
do {
try FileManager.default.createDirectory(
at: outputURL.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil
)
try data.write(to: outputURL)
print("Saved PDF to \(outputURL.path)")
} catch {
print("Failed to save PDF: \(error)")
}
case .failure(let error):
print("Failed to create PDF: \(error)")
}
if let onFinished {
onFinished()
}
}
}
}
}
let cvFile = URL(fileURLWithPath: "index.html", isDirectory: false)
let rawHTML = try String(contentsOf: cvFile)
let request = URLRequest(url: cvFile)
let webView = WKWebView(frame: .zero)
let webViewDelegate = WebViewNavigationDelegate(outputURL: URL(fileURLWithPath: "cv.pdf", isDirectory: false))
webView.navigationDelegate = webViewDelegate
webView.load(request)
await withCheckedContinuation { continuation in
webViewDelegate.onFinished = {
continuation.resume()
}
}