Tutorials

How to Call ComPDFKit PDF API Library Swift

By ComPDFKit | Wed. 24 Jul. 2024
SwiftPDF API

ComPDFKit API Library allows Swift developers to build applications and quickly integrate multiple functions and services by providing a variety of Swift API tools, such as viewing, editing, signing, and annotating PDF documents, to improve user experience.

 

Therefore, in this tutorial, we will show you how to call ComPDFKit PDF API Library in Swift step by step, including ComPDFKit account registration, obtaining ComPDFKit API Library, identity authentication, and making API requests.

 

Before starting your project, you can register a ComPDFKit API libraries account, which provides you with a free account that supports you to process more than 1,000 documents without limit within 30 days.

 

 

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

 

Swift API Library Requirements Before Calling

Programming Environment: macOS 10.13 and higher, and iOS 10 and higher.

Dependencies: Xcode13 and higher.

 

Step 1: Register and Get a License

- Register a ComPDFKit account as developer, and then you will get a free account so that unlimitedly process 1000 documents for free every month.

- Go to console’s API Dashboard>Project>API Keys to access the Project ID, Public Key, and Secret Key.

 

 

Step 2: Obtain the Dependencies of the ComPDFKit API Library in Swift

Add the following dependency to your "Podfile":

pod 'compdfkit-api-swift'

 

Step 3: Authentication Your License

ComPDFKit API uses the JSON Web Tokens method for secure authentication. And you can authenticate your project easily as this:

// Create a client 
let client: CPDFClient = CPDFClient(publicKey: public_key, secretKey: secret_key)

 

Step 4: Make API Requests

Making an API request is actually very simple. Usually, it consists of four steps:

  • Create a task
  • Upload a file
  • Execute the task
  • Download the result file

 

Note:

  • Each step can be performed in two ways: asynchronous block and asynchronous wait. When using the asynchronous wait method, the programming environment needs to be macOS 10.15 and above, and iOS 13 and above.
  • Different PDF APIs correspond to different tasks, so please determine the PDF functions of the PDF API you need when creating a task.
  • Pay attention to the file format you upload. Although most ComPDFKit PDF APIs are designed for processing PDF files, some conversion PDF APIs can handle different formats, such as CSV to PDF API can handle CSV format.

 

Sample 1: Convert PDF to Excel(Async Block)

Before building your Swift PDF API request, provide the Public Key and Secret Key, as shown in the following code example.

//  PDFToExcel.swift
//  compdfkit-api-swift
//

#if os(iOS)
import Foundation
#else
import Cocoa
#endif

private let public_key = "x"
private let secret_key = "x"
class PDFToExcel: NSObject {
    private static var client: CPDFClient = CPDFClient(publicKey: public_key, secretKey: secret_key)
    
class func entrance() {
        // Create a task
        self.client.createTask(url: CPDFConversion.PDF_TO_EXCEL) { taskModel in
            guard let taskId = taskModel?.taskId else {
                Swift.debugPrint(taskModel?.errorDesc ?? "")
                return
            }
            
 // upload File
            let group = DispatchGroup()
            group.enter()
            let path = Bundle.main.path(forResource: "test", ofType: "pdf")
            self.client.uploadFile(filepath: path!, password: "", params: [
                CPDFFileUploadParameterKey.contentOptions.string() : "2",
                CPDFFileUploadParameterKey.worksheetOptions.string() : "1",
                CPDFFileUploadParameterKey.isContainAnnot.string() : "1",
                CPDFFileUploadParameterKey.isContainImg.string() : "1"
            ], taskId: taskId) { uploadFileModel in
                if let errorInfo = uploadFileModel?.errorDesc {
                    Swift.debugPrint(errorInfo)
                }
                group.leave()
            }
            
  group.notify(queue: .main) {
                // execute Task
                self.client.processFiles(taskId: taskId) { processFileModel in
                    if let errorInfo = processFileModel?.errorDesc {
                        Swift.debugPrint(errorInfo)
                    }
                    // get task processing information
                    self.client.getTaskInfo(taskId: taskId) { taskInfoModel in
                        guard let _model = taskInfoModel else {
                            Swift.debugPrint("error:....")
                            return
                        }
                        if (_model.isFinish()) {
                            _model.printInfo()
                        } else if (_model.isRuning()) {
                            Swift.debugPrint("Task incomplete processing")
//                            self.client.getTaskInfoComplete(taskId: taskId) { isFinish, params in
//                                Swift.debugPrint(params)
//                            }
                        } else {
                            Swift.debugPrint("error: \(_model.errorDesc ?? "")")
                        }
                    }
                }
            }
        }
    }
}

 

Sample 2: Convert PDF to Excel(Async Await)

Like sample 1, you also provide the Public Key and Secret Key before maiking your Swift API Library request, as shown in the following code example.

import Foundation

#else

import Cocoa

#endif



private let public\_key = "x"

private let secret\_key = "x"

class PDFToExcel: NSObject {

  @available(macOS 10.15.0, iOS 13.0, *)
    class func asyncEntrance() {
        let client: CPDFClient = CPDFClient(publicKey: public_key, secretKey: secret_key)
        
 Task { @MainActor in
            // Create a task
            let taskModel = await client.createTask(url: CPDFConversion.PDF_TO_EXCEL)
            let taskId = taskModel?.taskId ?? ""
            
 // upload File
            let path = Bundle.main.path(forResource: "test", ofType: "pdf")
            let uploadFileModel = await client.uploadFile(filepath: path ?? "", password: "", params: [
                CPDFFileUploadParameterKey.contentOptions.string() : "2",
                CPDFFileUploadParameterKey.worksheetOptions.string() : "1",
                CPDFFileUploadParameterKey.isContainAnnot.string() : "1",
                CPDFFileUploadParameterKey.isContainImg.string() : "1"
            ], taskId: taskId)
            
// execute Task
            let _ = await client.processFiles(taskId: taskId)
            // get task processing information
            let taskInfoModel = await client.getTaskInfo(taskId: taskId)
            guard let _model = taskInfoModel else {
                Swift.debugPrint("error:....")
                return
            }
            if (_model.isFinish()) {
                _model.printInfo()
            } else if (_model.isRuning()) {
                Swift.debugPrint("Task incomplete processing")
                client.getTaskInfoComplete(taskId: taskId) { isFinish, params in
                    Swift.debugPrint(params)
                }
            } else {
                Swift.debugPrint("error: \(taskInfoModel?.errorDesc ?? "")")


              }

}

}

}

Integrating Swift API libraries such as ComPDFKit allows businesses to optimize their PDF-related workflows, enhancing productivity, minimizing errors and debugging expenses, safeguarding data security, and delivering an improved user experience for both employees and customers.

 

Final Words

With this tutorial of calling ComPDFKit API Library in Swift, you can seamlessly integrate diverse functions and services into your projects, crafting an efficient document processing workflow and enhancing the overall user experience. 

 

In addition, utilizing the extensive and complimentary ComPDFKit PDF API Library provided by ComPDFKit, you can easily access a wide range of integration guides to enhance the applications of your PDF.

 

ComPDFKit API owns a professional R&D team that produces comprehensive technical documentation and guides to help developers. Also, if you have any questions or need  technical support, please contact us immediately. 

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