Printing the view in iOS with Swift
Asked Answered
G

4

17

I am developing an app which requires visitor passes to be generated and printed directly from an iPad over AirPrint.

I have looked everywhere to find out how to print a view but I can only find how to print text, webKit and mapKit.

Is there a way of printing an entire view? If not, what would be a good solution to print a visitor pass which will be plain text, boxes and a photograph. Thanks.

Golden answered 10/12, 2015 at 15:51 Comment(1)
Sorry my old ipad1 didn't let me add a comment only an answer. My comment was: Didvyou find a solution? I am looking for the same also with a qr code? At first I like to use my ipad app just as input device and have a local pc network lookup the data and print the badge/pass? I think a faster way would be to have the print layout created in my app based on the database data? Maybe create a pass/badge pdf with a qrcode and print this?Selfopinionated
G
13

I have found the answer to my question by modifying the code found here: AirPrint contents of a UIView

//create an extension to covert the view to an image
extension UIView {
 func toImage() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)

    drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)

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

//In your view controller    
@IBAction func printButton(sender: AnyObject) {

    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 = self.view.toImage()

    // If you want to specify a printer
    guard let printerURL = URL(string: "Your printer URL here, e.g. ipps://HPDC4A3E0DE24A.local.:443/ipp/print") else { return }
    guard let currentPrinter = UIPrinter(url: printerURL) else { return }                     

    printController.print(to: currentPrinter, completionHandler: nil)

    // Do it
    printController.presentFromRect(self.view.frame, inView: self.view, animated: true, completionHandler: nil)
}
Golden answered 15/2, 2016 at 18:2 Comment(2)
I am using above code to Print, But it always ask to select printer, is there any way by which Printer select Automatically.Mandarin
@JatinVashisht I've updated the answer to include this informationGolden
H
5

I think you have to look print photo sample code with Swift: https://developer.apple.com/library/ios/samplecode/PrintPhoto/Introduction/Intro.html

What exactly is your view, imageView or UIView? If you are interested in imageView or UIImage, Print Photo sample from Apple is for you. If your subject is UIView you can create pdf context from view.layers and send to AirPrint func like WebKit, text or you can print to create pdf data.

The best solution is Create Pdf file is in here for swift Generate PDF with Swift

Print pdf file is for swift implementation:

var pdfLoc = NSURL(fileURLWithPath:yourPdfFilePath)
let printController = UIPrintInteractionController.sharedPrintController()!
let printInfo = UIPrintInfo(dictionary:nil)!

printInfo.outputType = UIPrintInfoOutputType.General
printInfo.jobName = "print Job"
printController.printInfo = printInfo
printController.printingItem = pdfLoc
printController.presentFromBarButtonItem(printButton, animated: true, completionHandler: nil)
Hudgens answered 10/12, 2015 at 16:35 Comment(3)
If this question is tagged with swift, why would you provide an Objective-C implementation?Inestimable
Because I'm not familiar with swift very well, I edited my answer.Hudgens
Thanks, it would likely be a UIView. I looked at the solutions above but I'm not sure the PDF option is the best bet. I think the best thing to do would be to create the visitor pass HTML then print the web view. I'll let you know how I get on.Golden
D
5

Swift 5:

    let info = UIPrintInfo(dictionary:nil)
    info.outputType = UIPrintInfo.OutputType.general
    info.jobName = "Printing"

    let vc = UIPrintInteractionController.shared
    vc.printInfo = info

    vc.printingItem = UIImage.image(fromView: self.view) // your view here

    vc.present(from: self.view.frame, in: self.view, animated: true, completionHandler: nil)
extension UIImage {

    /// Get image from given view
    ///
    /// - Parameter view: the view
    /// - Returns: UIImage
    public class func image(fromView view: UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0)
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: false)

        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}
Daedalus answered 19/2, 2019 at 9:44 Comment(2)
Beautiful. Works perfectly.Lucretialucretius
@Lucretialucretius Thank you.Daedalus
S
2

Hier in Swift 3.x

 func prt() {

        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!
    }
}
Schram answered 28/6, 2017 at 22:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.