Swift macOS如何使用NSPrintInfo和NSAttributedString进行打印

时间:2018-03-14 21:41:22

标签: swift macos nsattributedstring nsprintinfo

我想在我的应用程序中打印出一个列表。

但是,如果列表太大而无法放在一个页面上,则会出现问题 页面上的最后一行和第一行。

e.g。页面上的最后一行被裁剪,一些部分显示在下一页的顶部。

Screenshot of bottom of page 1 第1页底部的屏幕截图

Screenshot of top of page 2

第2页顶部的屏幕截图

如何设置我的打印作业,以便在每个页面上正确设置文字?

目前我有以下代码段:

   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 个答案:

没有答案