我正在尝试通过 iPad 应用程序设置打印,其中单击“打印”将打印包含其所有内容的视图。这是我尝试过的(从网上的一些示例中提取的):
// 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)
不过,我也读过here https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewPrintFormatter_Class/index.html#//apple_ref/occ/cl/UIViewPrintFormatter that viewPrintFormatter
仅适用于 UIWebView、UITextView 和 MKMapView,对吗?
当我用它打印时(使用打印机模拟器),我只是得到一个空白页;尝试过各种打印机/纸张尺寸。
非常感谢任何指导!
我不确定这是否是正确的方法,但我最终通过将视图转换为UIImage
然后将其设置为打印控制器的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)
The toImage()
方法是 UIView 的扩展:
extension UIView {
func toImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
如果有人有其他方法,请接受其他方法!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)