UIView的AirPrint内容 [英] AirPrint contents of a UIView

查看:86
本文介绍了UIView的AirPrint内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过iPad应用程序设置打印,在其中单击打印将打印包含所有内容的视图。这是我尝试过的方法(从网上的一些示例中提取):

I'm trying to set up printing through an iPad app, where clicking Print will print a view with all of its contents. Here's what I've tried (pulled together from a few examples online):

// This is the View I want to print
// Just a 200x200 blue square
var testView = UIView(frame: CGRectMake(0, 0, 200, 200))
testView.backgroundColor = UIColor.blueColor()

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
// This is where I was thinking the print job got the
// contents to print to the page??
printController?.printFormatter = testView.viewPrintFormatter()

// Do it
printController!.presentFromRect(self.frame, inView: self, animated: true, completionHandler: nil)

但是,我也阅读了此处表示 viewPrintFormatter 仅适用于UIWebView,UITextView和MKMapView,对吗?

However, I also read here that viewPrintFormatter is only available to UIWebView, UITextView, and MKMapView, is that correct?

当我使用打印机模拟器进行打印时,我只会得到一个空白页面;

When I print with this (using the printer simulator) I just get an empty page; tried with various printers/paper sizes.

任何指导都值得赞赏!

推荐答案

我不确定这是否是正确的方法,但最终通过将视图转换为 UIImage 然后将其设置为打印控制器的 printingItem

I'm not sure if this is the proper way to do it, but I ended up solving this by converting the view to a UIImage and then setting it as the print controller's printingItem.

更新后的代码:

// This is the View I want to print
// Just a 200x200 blue square
var testView = UIView(frame: CGRectMake(0, 0, 200, 200))
testView.backgroundColor = UIColor.blueColor()

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 = testView!.toImage()

// Do it
printController!.presentFromRect(self.frame, inView: self, animated: true, completionHandler: nil)

toImage()方法是UIView的扩展:

The toImage() method is an extension to UIView:

extension UIView {
    func toImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)

        drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)

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

如果有人拥有,请接受其他方法!

Open to alternative approaches if anyone has one!

这篇关于UIView的AirPrint内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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