ios - 使用 Swift 在 iOS 中打印 View

标签 ios swift printing airprint

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

我到处寻找如何打印 View ,但我只能找到如何打印文本、webKit 和 mapKit。

有没有办法打印整个 View ?如果没有,什么是打印纯文本、框和照片的访客通行证的好解决方案。谢谢。

最佳答案

我通过修改此处找到的代码找到了问题的答案: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)
}

关于ios - 使用 Swift 在 iOS 中打印 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34206207/

相关文章:

ios - 本地化 Storyboard的修改 - 转换为基础 Storyboard

ios - 以前使用文档浏览器运行的应用程序的文档文件夹消失了

ios - 当 slider 按钮超过最大值的大约 60% 时,UISlider 最大轨道图像使用最小轨道图像

ios - 如何对齐 imageView 内的图像

api - 我的 App 获得批准并已在 App Store 中后,如何更改其背景

file - 如何在同一时间shell中读取两个文件

ssl - 自签名 SSL 证书和 stringWithContentsOfURL

swift - 由于 'private' 保护级别,Cocoapods lint 错误无法访问

Perl 打印不正确

Python 在 Print 语句中打印和乘以字符串