使用Swift在iOS中打印视图 [英] Printing the view in iOS with Swift

查看:145
本文介绍了使用Swift在iOS中打印视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am developing an app which requires visitor passes to be generated and printed directly from an iPad over AirPrint.

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

I have looked everywhere to find out how to print a view but I can only find how to print text, webKit and mapKit.

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

Is there a way of printing an entire view? If not, what would be a good solution to print a visitor pass which will be plain text, boxes and a photograph. Thanks.

推荐答案

我通过修改以下代码找到了问题的答案:UIView的AirPrint内容

I have found the answer to my question by modifying the code found here: AirPrint contents of a UIView

//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)
}

这篇关于使用Swift在iOS中打印视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆