Following this example ( Swift: create pdf with WKWebView's createPdf - copied almost one to one), I try to create a pdf from WKWebView (I am still very amazed that it is still so catastrophically complicated (up to impossible) to create a PDF under macOS. (It's easier with php.)) However - code is
private func CreatePDF(htmlString: String) {
let width = ((21/2.54)*72)
let height = ((29.7/2.54)*72)
if let downloadDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let savePath = downloadDir.appendingPathComponent("swiftPdf").appendingPathExtension("pdf")
let webViewConfiguration = WKWebViewConfiguration()
let webView = WKWebView(frame: .init(x: 0, y: 0, width: width, height: height), configuration: webViewConfiguration)
let pdfConfiguration = WKPDFConfiguration()
pdfConfiguration.rect = CGRect(x: 0.0, y: 0.0, width: width, height: height)
webView.loadHTMLString(htmlString, baseURL: Bundle.main.resourceURL)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
webView.createPDF(configuration: pdfConfiguration) { result in
switch result {
case .success(let data):
do {
try data.write(to: savePath)
print("Successfully created and saved pdf…")
} catch let error {
print("Could not _save_ pdf: \(error)")
}
case .failure(let error): // <<-- always comes out here with error
print("Could not create pdf: \(error)")
}
}
}
}
}
The console tells
failure(Error Domain=WKErrorDomain Code=1 "An unknown error occurred" UserInfo={NSLocalizedDescription=An unknown error occurred.})
Could not create pdf: Error Domain=WKErrorDomain Code=1 "An unknown error occurred." UserInfo={NSLocalizedDescription=An unknown error occurred.}
Wonderful errormessage. :-)
But what ist the problem now?