5

我正在尝试通过 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)

但是,我也在这里读到了viewPrintFormatter仅适用于 UIWebView、UITextView 和 MKMapView 的内容,对吗?

当我用这个(使用打印机模拟器)打印时,我只得到一个空白页;尝试使用各种打印机/纸张尺寸。

非常感谢任何指导!

4

2 回答 2

9

我不确定这是否是正确的方法,但我最终通过将视图转换为 aUIImage然后将其设置为打印控制器的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 的扩展:

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

        drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)

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

如果有人有替代方法,请开放!

于 2015-09-08T16:52:10.997 回答
2

也许有人(像我一样)需要在将图像视图发送到打印机之前为其添加边框(否则图像将自动适合纸张)。为了做到这一点,我搜索了一些内置方法,但我没有找到它(顺便说一句,我从这里阅读了一些提示)。诀窍是将包含图像的视图添加到外部视图,然后将其居中。

    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()

它有点复杂,但它完成了它的肮脏工作。

于 2016-03-26T14:41:05.350 回答