How To Convert Image To PDF In Swift

In this article, we will convert captured images from iPhone and convert them into PDF using Swift.

You create a PDF graphics context using either the UIGraphicsBeginPDFContextToData or the UIGraphicsBeginPDFContextToFile function. These functions create the graphics context and associate it with a destination for the PDF data. For the UIGraphicsBeginPDFContextData function, the destination is an NSMutableData object that you provide. And for the UIGraphocsBeginPDFContextToFile function, the destination is a file in your app's Home directory
 
PDF documents organize their content in a page-based structure. This structure imposes two restrictions on any drawing you do.
  1. There must be an open page before you issue any drawing commands.
  2. You must specify the size of each page.         
GraphicsBeginPDFPage or UIGraphicsBeginPDFPageWithInfo functions
 
Each time you want to create a new page, you must call one of these functions again to mark the start of the new page. The UIGraphicsBeginPDFPage function creates a page using the default size, while the UIGraphicsBeginPDFPageWithInfo function lets you customize the page size and other page attributes.
  1. let pdfData = NSMutableData()    
  2.       let imgView = UIImageView.init(image: image)    
  3.       let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)    
  4.       UIGraphicsBeginPDFContextToData(pdfData, imageRect, nil)    
  5.       UIGraphicsBeginPDFPage()    
  6.       let context = UIGraphicsGetCurrentContext()    
  7.       imgView.layer.render(in: context!)    
  8.       UIGraphicsEndPDFContext()              
  9.       //try saving in doc dir to confirm:    
  10.       let fileManager = FileManager.default    
  11.       let dir = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("PDFDocument")    
  12.       if !fileManager.fileExists(atPath: dir) {    
  13.           try! fileManager.createDirectory(atPath: dir, withIntermediateDirectories: true, attributes: nil)    
  14.       }    
  15.       let url = NSURL(string: dir)    
  16.       let path = url!.appendingPathComponent("\(filename).pdf")?.absoluteString    
  17.       do {    
  18.            try pdfData.write(toFile: path!, options: NSData.WritingOptions.atomic)    
  19.       } catch let error as NSError{    
  20.           print(error.localizedDescription)    
  21.       }