Select Page

How to Generate PDFs from HTML in iOS using Swift UIKit

Jul 18, 2023

In the world of iOS app development, the ability to dynamically generate PDF documents from HTML content is a game changer. Imagine the possibilities of effortlessly transforming dynamic data in the form of interactive reports, professional invoices, or document generation workflows into stunning PDFs.  

In this blog, our Software Development Engineer, Balaji Pandian will give you step-by-step instructions on how to generate a PDF file from HTML in an iOS app using Swift. 

To begin with, you must have Xcode installed on your machine, as it serves as the development environment for iOS apps.  

Let’s get started. 

Step 1: Project Set up 

  • Open the Xcode and create a new iOS project.
  • Select the “Single View App” template and give your project a suitable name.
  • Choose Swift as the programming language and configure the desired options for other project settings. 
  •  After the project is created, navigate to the ViewController.swift file. 

Step 2: Import Frameworks  

To generate PDF from HTML, we need to import the necessary frameworks. Add the following import statements at the top of ViewController.swift file:

Step 3: WebView Setup 

  • Create a new class, ViewController, that inherits from UIViewController and adopts the WKNavigationDelegate protocol. This class will handle the generation of the PDF file.
  • Inside the ViewController class, override the viewDidLoad() method and perform the following steps: 
    • Create an instance of WKWebView. 
    • Set the navigationDelegate of the web view to self. 

    • Drag the Sample Invoice HTML file into the project.

Initiate the HTML file (Invoice.html) from the bundle and load the WebView request. 

Step 4: Generating PDF

  • Implement the webView(:didFinish:) method from the WKNavigationDelegate protocol. This method will be called when the web view finishes loading the JSON string to HTML file content. 
    • In Swift, the evaluateJavaScript method is used to execute JavaScript code within a WKWebView or WKWebViewConfiguration object. It allows you to interact with the web content loaded in the webView and manipulate it using JavaScript. 
    • Pass the webView instance to generatePDF (formatter: UIViewPrintFormatter() method. 
    • Mapping the JSON string to HTML key value  

  • Implement the generatePDF method that takes a WKWebView instance and a handler. 
    • Create an instance of UIPrintPageRenderer 
    • Add the web view’s viewPrintFormatter() to the print page renderer 
    • Set the paper size and printable area of the PDF 
    • Create an instance of NSMutableData to store the PDF data 
    • Initiate the PDF context using UIGraphicsBeginPDFContextToData(). 
    • Iterate over the print page renderer’s number of pages and draw each page using UIGraphicsBeginPDFPage() and printPageRenderer.drawPage(at:in:). 
    • End the PDF context using UIGraphicsEndPDFContext(). 
    • Pass the generated PDF data. 

  • Implement the savePDFToDisk(pdfData:) method to save the generated PDF data to the device’s document directory. 
    • Check if the PDF data is not NIL 
    • Get the document directory path using NSSearchPathForDirectoriesInDomains(). 
    • Construct the file path for the PDF  
    • Use pdfData.write(to:) to save the PDF data to the file 
    • Handle if any errors occur during the file-saving process 

To achieve a PDF preview with full view in Swift UI, you can utilize the PDFView class provided by Apple’s PDFKit framework. 

The below figure shows the final output of the conversion of PDF file from HTML format

By leveraging the WebKit framework, we have successfully achieved the rendering of HTML content within a WKWebView, subsequently converting it into a PDF document.  It is important to note that handling error cases and tailoring the code to meet your specific requirements is essential.  

There are further possibilities to explore and enhance the PDF generation process by: 

  • Empowering users to dynamically customize the HTML content 
  • Elevating the PDF layout with print page renderer modifications  
  • Implementing pagination and header/footer support 

You can also explore and combine various techniques to create unique and compelling PDFs tailored to your specific requirements on the fly. So, dive in, experiment, and explore. 

Happy coding! 

Want to know more, reach out to us at business@m2pfintech.com.  

Our team of experts is eager to connect with you. 

Subscribe to our newsletter and get the latest fintech news, views, and insights, directly to your inbox.

Follow us on LinkedIn and Twitter for insightful fintech bytes curated for curious minds like you.

0 Comments

Submit a Comment

Your email address will not be published.

You May Also Like…