Печать представления в iOS с помощью Swift

Я разрабатываю приложение, которое требует создания и печати пропусков посетителей непосредственно с iPad через AirPrint.

Я искал везде, чтобы узнать, как распечатать представление, но я могу найти только то, как распечатать текст, webKit и mapKit.

Есть ли способ распечатать весь вид? Если нет, то что было бы хорошим решением, чтобы распечатать пропуск посетителя, который будет состоять из простого текста, полей и фотографии. Спасибо.


person Ben Sullivan    schedule 10.12.2015    source источник
comment
Извините, мой старый ipad1 не позволял мне добавлять комментарий, только ответ. Мой комментарий был: Вы нашли решение? Я ищу то же самое с qr-кодом? Сначала мне нравится использовать приложение для ipad просто как устройство ввода, а локальная сеть ПК выполняет поиск данных и распечатывает значок / пропуск? Я думаю, что более быстрым способом было бы создать макет печати в моем приложении на основе данных базы данных? Может быть, создать пропуск / бейдж в формате pdf с qrcode и распечатать его?   -  person alex    schedule 12.01.2016


Ответы (4)


Я нашел ответ на свой вопрос, изменив код, найденный здесь: содержимое AirPrint 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)
}
person Ben Sullivan    schedule 15.02.2016
comment
Я использую приведенный выше код для печати, но он всегда просит выбрать принтер, есть ли способ, которым принтер выбирает автоматически. - person Jatin Vashisht; 14.09.2018
comment
@JatinVashisht Я обновил ответ, чтобы включить эту информацию - person Ben Sullivan; 16.09.2018

Я думаю, вам нужно посмотреть образец кода для печати фотографий с помощью Swift: https://developer.apple.com/library/ios/samplecode/PrintPhoto/Introduction/Intro.html

Какой именно у вас вид, imageView или UIView? Если вы заинтересованы в imageView или UIImage, образец Print Photo от Apple для вас. Если ваша тема UIView, вы можете создать контекст PDF из view.layers и отправить в функцию AirPrint, например WebKit, текст или распечатать для создания данных PDF.

Лучшее решение - Создать файл Pdf здесь для быстрого Создать PDF с помощью Swift

Распечатать файл PDF для быстрой реализации:

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)
person furkan    schedule 10.12.2015
comment
Если этот вопрос помечен тегом swift, зачем вам предоставлять реализацию Objective-C? - person JAL; 10.12.2015
comment
Поскольку я не очень хорошо знаком со Swift, я отредактировал свой ответ. - person furkan; 10.12.2015
comment
Спасибо, скорее всего, это будет UIView. Я просмотрел приведенные выше решения, но не уверен, что вариант PDF — лучший выбор. Я думаю, что лучше всего было бы создать HTML-код посетителя, а затем распечатать веб-представление. Я дам вам знать, как я поживаю. - person Ben Sullivan; 11.12.2015

Свифт 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
    }
}
person Alexander Volkov    schedule 19.02.2019
comment
Красивый. Работает отлично. - person barrylachapelle; 12.11.2019
comment
@barrylachapelle Спасибо. - person Alexander Volkov; 03.12.2019

Hier в 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!
    }
}
person Eduard Kempinger    schedule 28.06.2017