let btn = UIButton()
btn.frame = CGRect(x: 15, y: 15, width: 120, height: 30)
btn.setTitle("print", for: .normal)
btn.addTarget(self, action: #selector(self.printData), for: .touchUpInside)
view.addSubview(btn)
btn.backgroundColor = UIColor.orange
func printData(){
let printInfo = UIPrintInfo(dictionary:nil)
printInfo.outputType = UIPrintInfoOutputType.general
printInfo.jobName = "My Print Job"
// Set up print controller
let printController = UIPrintInteractionController.shared
printController.printInfo = printInfo
// Assign a UIImage version of my UIView as a printing iten
printController.printingItem = self.view.toImage()
// Do it
printController.present(from: self.view.frame, in: self.view, animated: true, completionHandler: nil)
}
extension UIView {
func toImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
No comments:
Post a Comment