Print a scrollview as pdf in iOS swift

 Problem:

I had a view that has scrollview with dynamic data like images and text.I want to print the entire view to export as pdf and print.How can i achieve that?


Solution:

You can convert the screen to data and write it into pdf then you can use printController to print easily.As like below


Code:

import UIKit

import PDFGenerator


class ViewController: UIViewController {


    @IBAction func printAction(_ sender: Any) {

        let printInfo = UIPrintInfo(dictionary: nil)

          printInfo.jobName = newScroll.description

        printInfo.outputType = .general

      let path = self.newScroll.exportAsPdfFromViews()

        let printController = UIPrintInteractionController.shared


        printController.printInfo = printInfo

          printController.printingItem = NSURL(fileURLWithPath:path)

        printController.present(animated: true)


    }

    

    var newScroll = UIScrollView()

    override func viewDidLoad() {

        super.viewDidLoad()

        newScroll.frame = CGRect(x: 0, y: 150, width: 200, height: 300)

        for i in 0..<30 {

            let img = UIImageView(frame: CGRect(x: 0, y: i*170, width: 100, height: 150))

            img.image = UIImage(named: "1.png")

            let lbl = UILabel(frame: CGRect(x: 0, y: i*160, width: 100, height: 20))

            lbl.text = "test \(i)"

            newScroll.addSubview(img)

            newScroll.addSubview(lbl)

            newScroll.contentSize = CGSize(width: 100, height: i*200)

        }

        // Do any additional setup after loading the view.

    }



}


extension UIScrollView {

   

  // Export pdf from Save pdf in drectory and return pdf file path

  func exportAsPdfFromViews() -> String {

      var pdfData = Data()

      do {

          

          pdfData = try PDFGenerator.generated(by: [self])

      } catch (let error) {

              print(error)

          }


      return self.saveViewPdf(data: NSMutableData(data: pdfData))


  }


  // Save pdf file in document directory

  func saveViewPdf(data: NSMutableData) -> String {

    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)

    let docDirectoryPath = paths[0]

    let pdfPath = docDirectoryPath.appendingPathComponent("fileImg.pdf")

    if data.write(to: pdfPath, atomically: true) {

        return pdfPath.path

    } else {

        return ""

    }

  }

}

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

store cgpoint in userdefaults iOS swift