Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a local PDF using Swift

Tags:

pdf

swift

ios8

I have a printing routine in Objective-C that prints a local PDF file.

I would like to get the same routine working in Swift. Can anyone help?

- (void)printFile:(NSURL *)url {

    if ([UIPrintInteractionController .canPrintURL(url]) {

        UIPrintInteractionController *
            controller = [UIPrintInteractionController
            sharedPrintController()];

        controller.printingItem = url;

        UIPrintInfo *printInfo = [UIPrintInfo printInfo];
        PrintInfo.outputType = UIPrintInfoOutputGeneral;
        PrintInfo.jobName = [url lastPathComponent];
        controller.printInfo = printInfo;

        controller.showPageRange = YES;

        [controller presentAnimated:YES completionHandler:Null];

    }

}
like image 525
Nick Hawkes Avatar asked Sep 26 '14 21:09

Nick Hawkes


People also ask

How do I create a PDF in swift 5?

Assign paperRect and printableRect let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi render. setValue(page, forKey: "paperRect") render. setValue(page, forKey: "printableRect") // 4. Create PDF context and draw let pdfData = NSMutableData() UIGraphicsBeginPDFContextToData(pdfData, .


2 Answers

This should point you in the right direction, follow the link to get a good idea of what this does.

@IBAction func print(sender: UIBarButtonItem) {
   if UIPrintInteractionController.canPrintURL(imageURL) {
    let printInfo = UIPrintInfo(dictionary: nil)
    printInfo.jobName = imageURL.lastPathComponent
    printInfo.outputType = .Photo

    let printController = UIPrintInteractionController.sharedPrintController()!
    printController.printInfo = printInfo
    printController.showsNumberOfCopies = false

    printController.printingItem = imageURL

    printController.presentAnimated(true, completionHandler: nil)
  }
}

taken from http://nshipster.com/uiprintinteractioncontroller/

like image 77
RandomBytes Avatar answered Oct 24 '22 09:10

RandomBytes


Update for swift 4.2

@IBAction func printAction(_ sender: UIButton) {
        if let guide_url = Bundle.main.url(forResource: "RandomPDF", withExtension: "pdf"){
            if UIPrintInteractionController.canPrint(guide_url) {
                let printInfo = UIPrintInfo(dictionary: nil)
                printInfo.jobName = guide_url.lastPathComponent
                printInfo.outputType = .photo

                let printController = UIPrintInteractionController.shared
                printController.printInfo = printInfo
                printController.showsNumberOfCopies = false

                printController.printingItem = guide_url

                printController.present(animated: true, completionHandler: nil)
            }
        }
    }
like image 6
swiftUser Avatar answered Oct 24 '22 09:10

swiftUser