Tutorials

How to Build a Swift PDF Editor and Reader to Edit PDF on iOS

By ComPDFKit | Mon. 30 Sep. 2024
iOSSwift

 

 

With the increasing prevalence of mobile devices, people are now handling a variety of tasks on their iPhones, iPads, and tablets, including viewing and lightly editing documents using a PDF editor and reader. Users want the ability to access and manage PDF files anywhere, whether it's during their commute, in a meeting, or at home, and they seek solutions to edit PDFs on iPhones. This trend not only boosts productivity but also enhances convenience.

 

To meet this growing demand, this article will guide you on how to integrate PDF editing and viewing capabilities into your iOS mobile application, providing your iPhone or iPad app users with the convenience of editing PDFs on the go.



Requirements to Create Swift PDF Editor and Viewer for iOS

 

Here are the Requirements of ComPDFKit PDF Swift library for PDF viewing and editing. Integrating ComPDFKit for iOS requires the latest stable version of Xcode available at the time the release was made. This is a hard requirement, as each version of Xcode is bundled with a specific version of the iOS Base SDK, which often defines how UIKit and various other frameworks behave.

 

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free



Step1: Get iOS PDF Reader and Editor Swift Library

 

To follow the integrating guides in Swift, you need to download the ComPDFKit PDF Swift Library for iOS. The license in the license_key_ios.xml file is only used for the SDK demo. If you need to try to integrate the Swift PDF Library into your project, remember to get the license of the PDF Library on the Pricing pages.

 

 

ComPDFkit Editor Swift Library

 

 

Step2: Get the License of ComPDFKit PDF Viewer and Editor for iPhone/iPad

 

Get the free license for the iOS PDF Library of ComPDFKit by few clicks! It can be integrated into your iPhone, iPad, or any iOS-based app with our free licensing plans, empowering your apps with PDF rendering and editing.

 

Get the License of ComPDFKit PDF Viewer and Editor for iPhone/iPad

 

 

Step 3: Create a New Swift PDF iOS Project

 

1. Fire up Xcode, and choose File-> New -> Project. Then, select App in iOS -> Application. And then, click Next.

 

Create a New Swift PDF iOS Project (1) 

2. Choose the options for your new project:

         - Enter the name of your product, for example, PDFViewer.

         - Choose and enter the Apple developer account of the app you want to release.

         - Enter the name of your organization identifier (com.example.pdfviewer).

         - Choose Storyboard for the interface.

         - Choose the programming Language "Swift".

         - Click the Next button.

         - Place the project to the location as desired. Then, click Create.

 

Choose the options for your new iOS project

 

 

Step 4: Add iOS PDF Library of ComPDFKit

 

You can integrate ComPDFKit PDF SDK for iOS into your apps by two methods, CocoaPods and manually. Here we are going to show you how to integrate the XCFrameworks of ComPDFKit iOS library for reading and editing PDFs manually.

 

1. Right-click the "PDFViewer" project, select Add Files to "PDFViewer"....


Add Files to "PDFViewer"


Find and choose "ComPDFKit.xcframework" in the download package, and then click Add.
Note: Make sure to check the Copy items if needed option.


Add "ComPDFKit.xcframework"
Then, the "PDFViewer" project will look like the following picture.


"PDFViewer" iOS project

 

2. Add the dynamic xcframework "ComPDFKit.xcframework" to the Xcode’s Embedded Binaries. Left-click the project, find Embedded Binaries in the General tab, and choose Embed & Sign.


Add the dynamic xcframework "ComPDFKit.xcframework" to the Xcode’s Embedded Binaries
For earlier versions of Xcode (like Xcode 13), the Bitcode option might be turned on by default, which requires it to be turned off to run. The precise step to do this are illustrated as shown in the picture below.


Turn off Bitcode option



Step 5: Apply License to Read and Edit PDF on iPhone

 

Find the License Key

 

Accurately obtaining the license key is crucial for the application of the license.

 

  • In the email you received, locate the XML file containing the license key.

  • Open the XML file and determine the license type through the <type> field. If <type>online</type> present, it is an online license; if absent or <type>offline</type> is present, it is an offline license.

Online License:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<license version="1">
    <platform>ios</platform>
    <starttime>xxxxxxxx</starttime>
    <endtime>xxxxxxxx</endtime>
    <type>online</type>
    <key>LICENSE_KEY</key>
</license>

 

Offline License:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<license version="1">
    <platform>ios</platform>
    <starttime>xxxxxxxx</starttime>
    <endtime>xxxxxxxx</endtime>
    <key>LICENSE_KEY</key>
</license>
  • Copy the LICENSE_KEY from the <key>LICENSE_KEY</key> field.

 

Apply the License Key

 

Get a free trial license from the ComPDFKit official website's Online Sales Interface, you will receive the iOS 30-day trial license via email immediately. Before using any ComPDFKit PDF SDK classes, you must perform the following steps to apply the license to your application:

 

  • In AppDelegate.swift, import the header file ComPDFKit.

  • Depending on the type of authentication obtained in the previous step, whether online or offline, initialize the license using the respective method based on your requirements.

  • Initialize the license:

 

Online license:

Follow the code below and call the method CPDFKit.verify(withOnlineLicense: "LICENSE_KEY") { code, message in } in func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool. You need to replace the LICENSE_KEY with the license you obtained.

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  // Set your online license key here. ComPDFKit is commercial software.
  // Each ComPDFKit license is bound to a specific app bundle id.
  // com.compdfkit.pdfviewe
    
    CPDFKit.verify(withOnlineLicense: "YOUR_LICENSE_KEY_GOES_HERE") { code, message in
    }
}

 

Offline license:

Follow the code below and call the method CPDFKit.verifyWithKey:"LICENSE_SECRET" in func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool. You need to replace the LICENSE_KEY with the license you obtained.

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  // Set your license key here. ComPDFKit is commercial software.
  // Each ComPDFKit license is bound to a specific app bundle id.
  // com.compdfkit.pdfviewer
    
    CPDFKit.verify(withKey: "YOUR_LICENSE_KEY_GOES_HERE")
    return true
}

 

 

Step 6: Run Your Project to Read PDF on iPhone

 

1. Prepare a test PDF file, drag and drop it into the newly created pdfView project. By this way, you can load and preview the local PDF document using NSBundle. The following image shows an example of importing a PDF document named “Online5" into the project.

 

Run Your Project to Read PDF on iPhone

 

2. Create a CPDFDocument object through URL, and create a CPDFView to display it. The following code shows how to load PDF data using a local PDF path and display it by CPDFView.

​ 

  let document = CPDFDocument(url: url)
        
   if let error = document?.error, error._code != CPDFDocumentPasswordError {
      return
   }  
   let pdfView = CPDFView(frame: view.bounds)  
   pdfView.document = document

 

3. Add the created CPDFView to the view of the current controller. Sample code shows below.

  view.addSubview(pdfView)

 

4. Connect your device or simulator, and use shortcut "Command_R" to run the App. The PDF file will be opened and displayed.

 

 Connect your device or simulator

 

5. If the PDF content cannot be displayed, check if the created NSURL and CPDFDocument objects are empty, or if the size of the created CPDFView is zero. They should not be empty.

 

If there are special characters in the file path, your NSURL will be nil. Handle it with the following code.

 filePath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

 

If the size of the created CPDFView is zero, follow the code below to adjust the size of View.

  pdfView.frame = self.view.bounds

 

All the code to create a CPDFViewController shows below:

import UIKit
import ComPDFKit
class ViewController: UIViewController {
    
    public var filePath: String = String()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let url = URL(filePath: filePath)
//        let url = URL(fileURLWithPath: fliePath)
        let document = CPDFDocument(url: url)
        
        if let error = document?.error, error._code != CPDFDocumentPasswordError {
            return
        }
        
        let pdfView = CPDFView(frame: view.bounds)
        pdfView.document = document
        view.addSubview(pdfView)
    }
}

 

SceneDelegate sample code:

import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)
    {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        
        let fileURL = Bundle.main.bundleURL.appendingPathComponent("xxxx.pdf")
//        let writbaleURL = copyFileURLToDocumentFolder(fileURL)
        let writbaleURL = fileURL.path()
        
        let tPDFViewController:ViewController = ViewController.init()
        tPDFViewController.fliePath = writbaleURL
        
        window!.rootViewController = UINavigationController(rootViewController: tPDFViewController)
        window!.makeKeyAndVisible()
        guard let _ = (scene as? UIWindowScene) else { return }
    }
    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
    }
    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }
    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }
    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }
    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }
}

​ 

Note: We display a PDF with the iPhone 14 Pro iOS16.2 simulator in this sample code.



Step 7: Change to Edit PDF Mode on iPhone

 

Before performing PDF content editing, you should initialize the content editing mode. This example shows how to initialize editing mode:

var document = CPDFDocument(url: URL(string: "filePath"))
let page = document?.page(at: 0)

let pdfView = CPDFView(frame: self.view.bounds)
    
// Set the document to be displayed.
pdfView?.document = document
pdfView?.beginEditingLoadType([.text, .image])

 

Here is the explanation of the editing mode settings:

 

Editing Mode Description Parameters
Text Mode In text mode, the text blocks surrounded by dotted lines will be displayed in the PDF document. Users can select text blocks and add, delete, copy, and paste text. CEditingLoadTypeText
Image Mode In image mode, the images surrounded by dotted lines will be displayed in the PDF document. Users can select images and then delete, crop, rotate, mirror, replace, save images, or set image properties. CEditingLoadTypeImage
Text & Image Mode In text and image mode, the text blocks and images surrounded by dotted lines will be displayed in the PDF document. Users can select and edit both text and images. CEditingLoadTypeText|CEditingLoadTypeImage

 

Explore comprehensive guides on editing PDF text and images on ComPDFKit’s documentation pages.



Troubleshooting

 

1. Bitcode

Even when all configurations are correct, there may still be compilation errors. First, check if bitcode is disabled. In older versions of Xcode (such as Xcode 13), the Bitcode option may be enabled by default. It needs to be set to No in order to run the app.

 

2. No PDF Displayed

Check if the special encoding is required in the path we passed in, or if the local path we passed in exists.

 

 

Final Words

 

We hope this guide has provided you with a clear understanding of the steps required for a smooth integration of the ComPDFKit PDF SDK for iOS. Should you encounter any issues related to licensing, please check that your Bundle ID settings align properly with the information you provided us. For expired licenses, feel free to contact the ComPDFKit team or obtain a new license directly from our website.

 

If you’d like to see our iOS PDF library in action, don't hesitate to request a demo to better evaluate its performance and capabilities.


For any additional problems or technical support needs, our ComPDFKit team is always ready to assist. Your satisfaction and the seamless functionality of your applications are our top priorities. Thank you for choosing ComPDFKit!

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free