一尘不染

使用Swift在iOS中打印视图

swift

我正在开发一个应用程序,该程序需要生成访客通行证,并直接通过iPad在AirPrint上进行打印。

我到处都在寻找如何打印视图,但是我只能找到如何打印文本,webKit和mapKit。

有没有一种打印整个视图的方法?如果没有,那么打印纯文本,框和照片的访客通行证是一个很好的解决方案。谢谢。


阅读 278

收藏
2020-07-07

共1个答案

一尘不染

//create an extension to covert the view to an image
extension UIView {
func toImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)

    drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
 }
}

//In your view controller    
@IBAction func printButton(sender: AnyObject) {

    let printInfo = UIPrintInfo(dictionary:nil)
    printInfo.outputType = UIPrintInfoOutputType.General
    printInfo.jobName = "My Print Job"

    // Set up print controller
    let printController = UIPrintInteractionController.sharedPrintController()
    printController.printInfo = printInfo

    // Assign a UIImage version of my UIView as a printing iten
    printController.printingItem = self.view.toImage()

    // If you want to specify a printer
    guard let printerURL = URL(string: "Your printer URL here, e.g. ipps://HPDC4A3E0DE24A.local.:443/ipp/print") else { return }
    guard let currentPrinter = UIPrinter(url: printerURL) else { return }

    printController.print(to: currentPrinter, completionHandler: nil)

    // Do it
    printController.presentFromRect(self.view.frame, inView: self.view, animated: true, completionHandler: nil)
}
2020-07-07