UIImage To PDF Using VisionKit and PDFKit

PDFKit was introduced with iOS 11. Much respite to developers who earlier had to deal with C++ for PDF rendering in their applications.
The PDFKit allows us to create, modify and display PDFs in our applications.
The goal of this article is to convert UIImage(s) to a PDF using Swift.

We will be using VisionKit which has a Document Scanner Camera. We have already discussed the implementation of VisionKit here.

Plan Of Action

  • Scanning Documents Using VisionKit’s Document Scanner.
  • Converting images into a PDF Document.
  • Saving the PDF using FileManager.
  • Displaying the PDF in a PDFView

Before we jump onto the implementation, let’s give a quick look to PDFKit classes and methods.

PDFKit – What’s in it?

PDFKit consists of the following classes:

PDFPage – A PDFPage is responsible for rendering a single page of the PDF. Typically a PDFPage‘s initializer hosts an image.
PDFDocument – An instance of this class contains the complete PDF’s data and hosts every PDFPage.
PDFView – This is responsible for displaying the PDF in our application’s UI. It has the following properties that can be customized:

  • PDFDisplayMode – This can be either of the four – singlePage, singlePageContinuous ,twoUp or twoUpContinuous
  • PDFDisplayDirection – The pdf pages can be either horizontal or vertical scrolling

PDFThumbnailView – This is used for displaying thumbnail previews of the PDF pages.

There are other classes as well such as PDFOutline and PDFSelection(for selecting texts) which we are not covering in this particular article.

Implementation

UIImage To PDFPage To PDFDocument

let pdfDocument = PDFDocument()

for i in 0 ..< scan.pageCount {
   if let image = scan.imageOfPage(at: i).resize(toWidth: 250){
      let pdfPage = PDFPage(image: image)
      // Insert the PDF page into your document
      pdfDocument.insert(pdfPage!, at: i)        
   }
}            

This creates our PDF. We have resized the scanned images using a resize extension function (available at the end of this article).

Saving PDFDocument to Documents Directory

In order to save the PDFDocument, retrieve the raw data and write it to the Documents Directory URL as shown below:

let data = pdfDocument.dataRepresentation()
            
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            
let docURL = documentDirectory.appendingPathComponent("Scanned-Docs.pdf")
            
do{
            
  try data?.write(to: docURL)
            
}catch(let error){
   print("error is \(error.localizedDescription)")
}

Displaying In PDFView

Finally, we can embed the PDFView in the parent view and show the saved PDF in it:

let pdfView = PDFView()

pdfView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pdfView)

let docURL = documentDirectory.appendingPathComponent("Scanned-Docs.pdf")
        
if fileManager.fileExists(atPath: docURL.path){
    pdfView.document = PDFDocument(url: docURL)
}

Here's the output of the application in action:

ios-uiimage-to-pdfkit-pdfview

That's it. We are done converting a batch of UIImages into a PDF.
You can view the full source code in our Github Repository.

Leave a Reply

Your email address will not be published. Required fields are marked *