title: Cocoa swift macOS Print html to pdf
body: <p>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 <strong>swift-beginner</strong>.</p>
  <p>To print the html content to a pdf file I use the following code:</p>
  <pre><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()
          }
      }
  </code></pre>
  <p>Which is based on this StackOverFlow Question/Answer : <a href="https://stackoverflow.com/a/39022707/7274172">StackOverFlowAnswer</a></p>
  <p>I had to &quot;translate&quot; the code to swift4 - Any mistakes here are very possible
  When running the code I get the following logs (in that order):</p>
  <ol>
  <li>NSURLConnection finished with error - code -1002</li>
  <li>Printing failed because PMSessionBeginCGDocumentNoDialog() returned -61.</li>
  <li>NSURLConnection finished with error - code -1002</li>
  </ol>
  <p>PMSessionBeginCGDocumentNoDialog() -61 -&gt; means that I don't have the permission to write at a certain location according to <a href="http://krypted.com/lists/comprehensive-list-of-mac-os-x-error-codes/" rel="nofollow noreferrer">this</a> (Write permission error)</p>
  <p>I tried to switch of the sandbox mode, and gave the application the right to read and write to/from desktop files.</p>
  <p>Does any one know how to fix the PMSessionBeginCGDocumentNoDialog() -61 error?
  (or in general get the code up and running...)
  Thank you!</p>