首页 > 解决方案 > 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 - 这里的任何错误都很可能在运行代码时得到以下日志(按此顺序):

  1. NSURLConnection 完成错误 - 代码 -1002
  2. 打印失败,因为 PMSessionBeginCGDocumentNoDialog() 返回 -61。
  3. NSURLConnection 完成错误 - 代码 -1002

PMSessionBeginCGDocumentNoDialog() -61 -> 表示我没有权限根据这个在某个位置写(写权限错误)

我尝试切换沙盒模式,并赋予应用程序读取和写入桌面文件的权限。

有谁知道如何修复 PMSessionBeginCGDocumentNoDialog() -61 错误?(或者通常让代码启动并运行......)谢谢!

标签: macoscocoapdfprintingswift4

解决方案


更多研究提出了以下答案: SO answer

指的是这个 GitHub 项目 GitHub Swift 3 PDFCreator

github项目中的代码解决了我的错误!工作完美。


推荐阅读