0

I want to generate a pdf file from html content. (To generate invoices from a html template) I would like to note, that I am a swift-beginner.

To print the html content to a pdf file I use the following code:

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()
        }
    }

Which is based on this StackOverFlow Question/Answer : StackOverFlowAnswer

I had to "translate" the code to swift4 - Any mistakes here are very possible When running the code I get the following logs (in that order):

  1. NSURLConnection finished with error - code -1002
  2. Printing failed because PMSessionBeginCGDocumentNoDialog() returned -61.
  3. NSURLConnection finished with error - code -1002

PMSessionBeginCGDocumentNoDialog() -61 -> means that I don't have the permission to write at a certain location according to this (Write permission error)

I tried to switch of the sandbox mode, and gave the application the right to read and write to/from desktop files.

Does any one know how to fix the PMSessionBeginCGDocumentNoDialog() -61 error? (or in general get the code up and running...) Thank you!

Luchspeter
  • 556
  • 7
  • 19

1 Answers1

0

Some more research brought up the following answer: SO answer

which refers to this GitHub project GitHub Swift 3 PDFCreator

The code in the github project solved my errors! Worked perfectly.

Luchspeter
  • 556
  • 7
  • 19