DEV Community

Derek
Derek

Posted on

How to Build iOS PDF Viewer with SwiftUI

SwiftUI is Apple's latest user interface framework, designed to revolutionize the way developers create UI for iOS, macOS, watchOS, and tvOS. Launched at WWDC 2019, SwiftUI offers a modern, declarative syntax that allows developers to build complex UIs with less code and a more intuitive development process.

It is widely used for Apple apps, including PDF applications. In this article, you’ll see the Swift tutorial example and learn how to build a SwiftUI PDF viewer with ComPDFKit iOS PDF Library.

Step 1: Requirements for Swift UI PDF Library Integration

The following requirements are needed to integrate the ComPDFKit iOS PDF library through SwiftUI.

  • iOS 10.0 or higher.
  • Xcode 13.0 or newer for Swift.
  • ComPDFKit iOS PDF Library: Access the ComPDFKit iOS PDF library on GitHub for your SwiftUI PDF program.
  • License of ComPDFKit iOS PDF Library: Obtain a 30-day trial license by applying on the ComPDFKit website. It will be sent via email.

Note: ComPDFKit 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.

Step 2: Get iOS Library Package for Your SwiftUI PDF Viewer

To follow the SwiftUI tutorial example in Swift, it's essential to download the ComPDFKit iOS PDF Library in Swift. This library will enable you to seamlessly integrate PDF viewing capabilities into your SwiftUI application.

Access the iOS PDF library on GitHub for your SwiftUI project.

Image description

Step 3: Get Trial License for ComPDFKit PDF Library

Easily obtain a ComPDFKit iOS Library 30-day license with just a few clicks on the ComPDFKit website. No sales involved. Simply apply for the appropriate license, and you'll receive an email with the license automatically. Integrate the Swift PDF library into your project seamlessly.

Image description

Step 4: Apply the License Key for Your Swift UI PDF APP

Find the License Key

Here are the step-by-step tutorials for you to find the correct License Key to integrate PDF Viewer library into your SwiftUI project.

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

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

Online License:

xmlCopy code
<?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>
Enter fullscreen mode Exit fullscreen mode

Offline License:

xmlCopy code
<?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.
Enter fullscreen mode Exit fullscreen mode

Apply the License Key

Go to the ComPDFKit official website's Online Sales Interface to submit a trial application and receive an immediate free trial license for iOS platforms, valid for 30 days. Before using any ComPDFKit PDF SDK classes, you must perform the following steps to apply the license to your application:

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

  2. 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.

  3. 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
    }
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Integrate ComPDFKit iOS PDF Library — SwiftUI Tutorials

Let's discuss how to integrate ComPDFKit for iOS in SwiftUI framework and build an iOS PDF Viewer to display a PDF.

  1. Bridge CPDFViewController to SwiftUI

First, declare the CPDFSwiftViewController structure — which conforms to the UIViewControllerRepresentable protocol — so that you can bridge from UIKit to SwiftUI. After that, add a property of type CPDFConfiguration and implement the protocols as seen below:

import ComPDFKit

struct CPDFSwiftViewController: UIViewControllerRepresentable {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    class Coordinator: NSObject,CPDFViewBaseControllerDelete {
        var myview: CPDFSwiftViewController
        init(_ myview: CPDFSwiftViewController) {
            self.myview = myview
        }

        // MARK: - CPDFViewBaseControllerDelete
        func PDFViewBaseControllerDissmiss(_ baseControllerDelete: CPDFViewBaseController) {
            baseControllerDelete.dismiss(animated: true)
        }

    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIViewController(context: Context) -> CNavigationController {
        CPDFKit.verify(withKey: "LICENSE_KEY")

        let filePath = Bundle.main.path(forResource: "developer_guide_ios", ofType: "pdf")  ?? ""

        let configuration = CPDFConfiguration()

        let vc = CPDFViewController(filePath: filePath, password: nil, configuration: configuration)
        vc.delegate = context.coordinator;
        let navController = CNavigationController(rootViewController: vc)
        navController.modalPresentationStyle = .fullScreen

        return navController
    }

    func updateUIViewController(_ uiViewController: CNavigationController, context: UIViewControllerRepresentableContext<CPDFSwiftViewController>) {

    }

}
Enter fullscreen mode Exit fullscreen mode
  1. Use ComPDFKitView in SwiftUI

Use CPDFViewController in your SwiftUI content view:

struct ContentView: View {
    @State var isPresented: Bool = false

    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, world!")

            .toolbar {

                ToolbarItem(placement: .bottomBar) {
                    Button("Click to open the sample PDF") {
                        isPresented = true
                    }
                }
            }
            .fullScreenCover(isPresented: $isPresented) {
                CPDFSwiftViewController()

            }
        }
        .padding()
    }
}
Enter fullscreen mode Exit fullscreen mode

In this guide, we use an iPad 14 device as an example. After building the demo successfully, the "developer_guide_ios.pdf" file will be opened and displayed.

Image description

FAQ about SwiftUI & ComPDFKit

  1. How to Get SwiftUI Updates?

What's new in SwiftUI - WWDC24: SwiftUI has introduced numerous new APIs, making it more convenient to work with the framework. This includes enhancements to core components, new ways to use foundational APIs, and ease of use improvements. You can now create custom container views.

  1. What is UIKit and SwiftUI?

SwiftUI and UIKit are frameworks for designing user interfaces in iOS development. SwiftUI offers a modern, streamlined approach to UI development, while UIKit provides robustness and versatility.

  1. What is the difference between Swift and SwiftUI?

Swift is a programming language created by Apple Inc. It is a powerful and fast language that makes development on Apple products more enjoyable and efficient.
SwiftUI is a declarative framework for building user interfaces on Apple platforms.

  1. Why is SwiftUI better?

SwiftUI excels in quicker UI development, a declarative syntax for control, Swift integration, and cross-platform compatibility. The framework offers a rich set of transitions and animations, enhancing the user experience.

  1. What are the disadvantages of SwiftUI?

Limited Deployment: SwiftUI is supported only on iOS 13+, macOS 10.15+, watchOS 6+, and tvOS 13+.
Maturation Stage: As a newer framework, SwiftUI is still evolving and maturing.

  1. Why ComPDFKit PDF SDK for iOS?

ComPDFKit PDF SDK for iOS is designed to make PDF handling seamless and efficient. It offers robust features for viewing, annotating, editing, and converting PDF files. Its high performance and flexibility make it an excellent choice for developers looking to integrate PDF functionalities into their iOS applications.

  1. Where can I find all ComPDFKit iOS PDF library developer guides?

All developer guides can be found on the documentation page.

  1. Where can I download the ComPDFKit PDF libraries?

Download on GitHub.

  1. Where can I get the trial license of ComPDFKit for iOS?

The license can be obtained directly on the pricing page (Without sales).

  1. How long can I trial ComPDFKit for iOS for free?

You can integrate ComPDFKit for iOS for 30 days. If you need more days for your free trial, you can contact the sales team.

Top comments (0)