macos - Cocoa swift macOS 打印 html 到 pdf
问题描述
我想从 html 内容生成一个 pdf 文件。(从 html 模板生成发票)我想指出,我是一个swift-beginner。
要将 html 内容打印到 pdf 文件,我使用以下代码:
func makePDF(markup: String) {
let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let printOpts: [NSPrintInfo.AttributeKey: Any] = [NSPrintInfo.AttributeKey.jobDisposition: NSPrintInfo.JobDisposition.save, NSPrintInfo.AttributeKey.jobSavingURL: directoryURL]
let printInfo = NSPrintInfo(dictionary: printOpts)
//printInfo.horizontalPagination = NSPrintInfo.
//printInfo.verticalPagination = NSPrintInfo.AutoPagination
printInfo.topMargin = 20.0
printInfo.leftMargin = 20.0
printInfo.rightMargin = 20.0
printInfo.bottomMargin = 20.0
let view = NSView(frame: NSRect(x: 0, y: 0, width: 570, height: 740))
if let htmlData = markup.data(using: String.Encoding.utf8) {
if let attrStr = NSAttributedString(html: htmlData, options: [ .documentType : NSAttributedString.DocumentType.html], documentAttributes: nil) {
print(attrStr);
let frameRect = NSRect(x: 0, y: 0, width: 570, height: 740)
let textField = NSTextField(frame: frameRect)
textField.attributedStringValue = attrStr
view.addSubview(textField)
let printOperation = NSPrintOperation(view: view, printInfo: printInfo)
printOperation.showsPrintPanel = false
printOperation.showsProgressPanel = false
printOperation.run()
}
}
这是基于这个 StackOverFlow 问题/答案:StackOverFlowAnswer
我不得不将代码“翻译”为 swift4 - 这里的任何错误都很可能在运行代码时得到以下日志(按此顺序):
- NSURLConnection 完成错误 - 代码 -1002
- 打印失败,因为 PMSessionBeginCGDocumentNoDialog() 返回 -61。
- NSURLConnection 完成错误 - 代码 -1002
PMSessionBeginCGDocumentNoDialog() -61 -> 表示我没有权限根据这个在某个位置写(写权限错误)
我尝试切换沙盒模式,并赋予应用程序读取和写入桌面文件的权限。
有谁知道如何修复 PMSessionBeginCGDocumentNoDialog() -61 错误?(或者通常让代码启动并运行......)谢谢!
解决方案
推荐阅读
- asp.net-web-api - 如何使用 .Net Core 2.2 创建动态构建器 Odata?
- java - 无法在 Android 中删除文件
- html - 单向绑定无响应功能
- javascript - 使用 Vue-i18n 翻译来自脚本的文本
- symfony - 在没有 /usr/local/bin/composer 的服务器上使用 EasyDeployBundle 托管 Symfony 4 应用程序
- jquery - 当我添加溢出时,fancybox 正在跳转我的内容:隐藏到页面上只能看到 6 个图像
- qt - Qt 应用程序无法正确启动(0xc000007b)
- android - 如何在 Nativescript 中使用外部 sdk
- java - 用于复合 API 调用的 Spring Cloud Gateway?
- gwt - 隐藏