我正在尝试通过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 viewPrintFormatter
仅适用于UIWebView,UITextView和MKMapView,这是正确的吗?
当我用它打印时(使用打印机模拟器)我只得到一个空页;试过各种打印机/纸张尺寸。
非常感谢任何指导!
答案 0 :(得分:9)
我不确定这是否是正确的方法,但我最终通过将视图转换为UIImage
并将其设置为打印控制器{s}来解决此问题。 {1}}。
更新的代码:
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)
方法是UIView的扩展:
toImage()
如果有人有一个方法,可以选择其他方法!
答案 1 :(得分:1)
也许某人(像我一样)需要在将图像视图发送到打印机之前为图像视图添加边框(否则图像将自动适合图纸)。为了做到这一点,我搜索了一些内置方法,但我还没有找到它(顺便说一句,我从here读了一些提示)。 诀窍是将包含图像的视图添加到外部视图,然后将其居中。
let borderWidth: CGFloat = 100.0
let myImage = UIImage(named: "myImage.jpg")
let internalPrintView = UIImageView(frame: CGRectMake(0, 0, myImage.size.width, myImage.size.height))
let printView = UIView(frame: CGRectMake(0, 0, myImage.size.width + borderWidth*2, myImage.size.height + borderWidth*2))
internalPrintView.image = myImage
internalPrintView.center = CGPointMake(printView.frame.size.width/2, printView.frame.size.height/2)
printView.addSubview(internalPrintView)
printController.printingItem = printView.toImage()
虽然有点复杂,但却做得不好。