首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Cocoa swift macOS Print html to pdf

Cocoa swift macOS Print html to pdf
EN

Stack Overflow用户
提问于 2018-05-28 17:55:41
回答 1查看 1.4K关注 0票数 0

我想从html内容生成一个pdf文件。(从html模板生成发票)我想指出的是,我是一个swift-beginner.

要将html内容打印到pdf文件,我使用以下代码:

代码语言:javascript
复制
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。由于PMSessionBeginCGDocumentNoDialog()返回-61.
  2. NSURLConnection,
  3. 打印失败。已完成,错误代码-1002

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

我尝试切换沙箱模式,并赋予应用程序对桌面文件进行读写的权限。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-28 18:18:25

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

它引用了这个GitHub项目的GitHub Swift 3 PDFCreator

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50563662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档