2015-09-04 71 views
5

我試圖通過iPad應用程序設置打印,點擊Print將打印一個視圖及其所有內容。下面是我試了一下(從幾個例子拉到一起在線):UIView的AirPrint內容

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

不過,我也讀hereviewPrintFormatter僅提供給UIWebView中,UITextView的,和的MKMapView,是正確的?

當我用這個打印(使用打印機模擬器),我只是得到一個空白頁;嘗試使用各種打印機/紙張尺寸。

任何指導非常感謝!

+0

當你嘗試時發生了什麼? – Undo

+0

我的壞 - 更新的問題 –

回答

9

我不確定這是否是正確的方式,但我最終通過將視圖轉換爲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) 

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 
    } 
} 

開放的替代辦法,如果任何人有一個!

+0

很不錯,謝謝! – LinusGeffarth

+2

一個非常棒的解決方案,爲我完美工作。非常感謝.. –

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

這有點複雜,但它的骯髒的工作。