AirPrint the contents of a Text View using Swift

血红的双手。 提交于 2019-12-05 21:29:01

I think you're confusing it by offering both the view formatter and data to print. Try:

var pic:UIPrintInteractionController = .sharedPrintController()
var viewpf:UIViewPrintFormatter = myTextView.viewPrintFormatter()

pic.delegate = self
pic.showsPageRange = true
pic.printFormatter = viewpf
pic.presentAnimated(true, completionHandler: nil)

Here is the Swift 4 code for printing text:

func print(text: String) {

    let printController = UIPrintInteractionController.shared

    let printInfo = UIPrintInfo(dictionary: nil)
    printInfo.outputType = UIPrintInfoOutputType.general
    printController.printInfo = printInfo

    let format = UIMarkupTextPrintFormatter(markupText: textWithNewCarriageReturns)

    format.perPageContentInsets.top = 72
    format.perPageContentInsets.bottom = 72
    format.perPageContentInsets.left = 72
    format.perPageContentInsets.right = 72
    printController.printFormatter = format

    printController.present(animated: true, completionHandler: nil)
}

Alternatively, if you have a long string with multiple \n carriage returns, you need to first replace all of the \n occurrences with br / before submitting the string to the UIMarkupTextPrintFormatter. Here is an example for Swift 4:

func print(text: String) {
    let textWithNewCarriageReturns = text.replacingOccurrences(of: "\n", with: "<br />")

    let printController = UIPrintInteractionController.shared

    let printInfo = UIPrintInfo(dictionary: nil)
    printInfo.outputType = UIPrintInfoOutputType.general
    printController.printInfo = printInfo

    let format = UIMarkupTextPrintFormatter(markupText: textWithNewCarriageReturns)

    format.perPageContentInsets.top = 72
    format.perPageContentInsets.bottom = 72
    format.perPageContentInsets.left = 72
    format.perPageContentInsets.right = 72
    printController.printFormatter = format

    printController.present(animated: true, completionHandler: nil)
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!