項目中要求tableView的截圖,轉為Data,并用AirPrint 打印出來,特地總結一下
tableView截圖
<pre>
func imageFromTableView(tableView: UITableView) -> UIImage {
var image = UIImage()
//開上下文
UIGraphicsBeginImageContextWithOptions(tableView.contentSize, tableView.isOpaque, 0.0)
//保存frame
let savedContentOffset = tableView.contentOffset
let savedFarme = tableView.frame
//設置tableView在畫布的位置和大小
tableView.contentOffset = .zero
tableView.frame = CGRect(x: 0, y: 0, width: tableView.contentSize.width, height: tableView.contentSize.height)
// 開始畫
tableView.layer.render(in: UIGraphicsGetCurrentContext()!)
//生成圖片保存在image中
image = UIGraphicsGetImageFromCurrentImageContext()!
//還原tableView的frame
tableView.contentOffset = savedContentOffset
tableView.frame = savedFarme
//關閉上下文
UIGraphicsEndImageContext()
return image
}
</pre>
image使用AirPrint打印
<pre>
let pic = UIPrintInteractionController.shared // 創(chuàng)建控制器
let printInfo = UIPrintInfo.printInfo() // 打印機配置
// UIPrintInfoOutputType:給 UIKit 提供要打印內容的類型提示??梢允且韵氯我庖粋€:
// .General(默認):文本和圖形混合類型;允許雙面打印。
// .Grayscale:如果你的內容只包括黑色文本,那么該類型比 .General 更好。
// .Photo:彩色或黑白圖像;禁用雙面打印,更適用于圖像媒體的紙張類型。
// .PhotoGrayscale:對于僅灰度的圖像,根據(jù)打印機的不同,該類型可能比 .Photo 更好。
printInfo.outputType = .general
pic.printInfo = printInfo
pic.showsNumberOfCopies = false //讓用戶選擇打印范圍,只在多頁的時候有用
pic.printingItem = image // 輸入源
//ipad 的調用方式
pic.present(from: rect, in: inView, animated: true, completionHandler: { (pick, isSuccess, error) in
})
// iphone 的調用方式
// pic.present(animated: true, completionHandler: { (pick, isSuccess, error) in })
</pre>
此時就會彈出打印頁面,但是系統(tǒng)自帶的顯示的是英文此時需要修改
info.plist中的文件,將en改為China
修改語言
