Swift macOS how to print with NSPrintInfo and NSAttributedString

1.3k views Asked by At

I want to print out a list in my App.

However if the list is too large to fit on one page there is a problem with the last and the first line on a page.

e.g. the last line on a page is cropped and some parts are shown on top of next page.

Screenshot of bottom of page 1 Screenshot of bottom of page 1

Screenshot of top of page 2

Screenshot of top of page 2

How can I manage to set up my print job that the text is set up correctly on every page?

Currently I have the following code snippet:

   func makePDF(markup: String, amount: Int) {
    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.PaginationMode.autoPagination
    printInfo.verticalPagination = NSPrintInfo.PaginationMode.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: 560, height: (60 + 36 * amount)))

    if let htmlData = markup.data(using: String.Encoding.utf8) {
        let attrStr = NSAttributedString(html: htmlData, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:
            String.Encoding.utf8.rawValue], documentAttributes: nil)

        let frameRect = NSRect(x: 0, y: 0, width: 560, height: (60 + 36 * amount))
        let textField = NSTextField(frame: frameRect)
        textField.attributedStringValue = attrStr!
        view.addSubview(textField)

        let printOperation = NSPrintOperation(view: view, printInfo: printInfo)
        printOperation.showsPrintPanel = true
        printOperation.showsProgressPanel = true
        printOperation.run()

    }
}
0

There are 0 answers