PlugPDF SDK iOS Developer Guide

GUIDE

PlugPDF VIEWER

  • How can I hide top bar and bottom bar?
  • How can I hide Page number indicator on PlugPDF Viewer?
  • How can I change Page number indicator position?
  • How can I detect that page was changed?
  • How can I get page slider value?
  • How to change page Preview size.
  • How can I go to the recent page when I close the PlugPDF Viewer?
  • How can I set Document title on PlugPDF Viewer?

ANNOTATION

  • How to get annotations information?
  • How to catch an annotation is added or removed?
  • Save and Remove annotations
  • Flatten annotations
  • Circle annotation
  • Square annotation
  • TextMarkup annotations ( Highlight, Underline, Strike Out)
  • Ink annotation
  • Note annotation
  • Eraser tool

DIGITAL SIGNATURE

Making an iOS application with the PlugPDF SDK ( Swift )

This tutorial walks you through the necessary steps to run a simple, fully functional mobile PDF reader on an iOS device. The goal is to get familiar with some basic PlugPDF concepts, as well as to build your first Swift application with Xcode.

Requirements

  1. An up-to-date version of both Xcode and iOS SDK, which can be downloaded from Apple’s developer site.
  2. The PlugPDF SDK supports XCode 6.0.2 onwards and iOS 6.1 onwards.

Steps required for making your first PDF iOS app

  1. Download the PlugPDF SDK
  2. Create a new Xcode project
  3. Add the PlugPDF framework
  4. Add some libraries
  5. Initialize the PlugPDF SDK
  6. Build the PDF viewer

1. Download the PlugPDF SDK

Download either a free trial license or an indie license as shown in the figure below.

Figure 1. Download PlugPDF now!

Figure 1. Download PlugPDF now!

You will then be redirected to a web page from which both PlugPDF for Android and iOS can be downloaded:

Figure 2. Thank you, your trial license key is on its way!

Figure 2. Thank you, your license key is on its way!

This is what the PlugPDF_iOS folder looks like.

Figure 3. PlugPDF_iOS folder structure

Figure 3. PlugPDF_iOS folder structure

Figure 4. PlugPDF_iOS folder content

Figure 4. PlugPDF_iOS folder content

On the other hand, you’ll instantly receive an email with your PlugPDF license key consisting of 56 alphanumeric characters like this example:

79F53DB9HHF9GH88EDB5297FH28FC6488AECC4EF496FB95A96CHFBF5

Please keep your license in a secure place since it will be required to initialize your PlugPDF applications, as we will show later in this paper.

2. Creating a new Xcode project

Let’s follow the steps illustrated in the figures below and create our first PDF application.

Figure 5. Open Xcode and choose File data-lazy-srcset= New > Project…” width=”300″ height=”287″ />

Figure 5. Open Xcode and choose File > New > Project…

Figure 6. Now select iOS data-lazy-srcset= Application > Single View Application ” width=”300″ height=”213″ />

Figure 6. Now select iOS > Application > Single View Application

Figure 7. Choose the options for your new project

Figure 7. Choose the options for your new project

Now Xcode will ask you to place your project under control version. By the way, this issue is not actually important for building your first PDF application, nevertheless let’s activate this default feature just to finish with the wizard.

Figure 8. Create Git repository

Figure 8. Select the Create Git repository checkbox, and finally click on the Create button

Then you need to add a Cocoa Touch Class on your project.

add file

Figure 9. Select your project, and  click on the New File

cocoa touch class

Figure 10. Select the Cocoa Touch Class, and  click on the Next button

cocoa class with header

Figure 11.  click the Create Bridging Header

3. Adding the PlugPDF framework

At this point, we are adding both the PlugPDF.framework and the PlugPDF.bundle to the sample project. The former is the PDF library itself, while the latter contains the resources such as the fonts and images to be used.

Figure 9. Select your sample project from the Xcode window

Figure 12. Select your sample project from the Xcode window as shown here

Figure 10. Choose File data-lazy-srcset= Add Files to ” width=”275″ height=”300″ />

Figure 13. Choose File > Add Files to “sample”…

Figure 11. Select both PlugPDF files

Figure 14. Select both PlugPDF files as illustrated in this image and click on the Add button

If everything is ok your Xcode project navigator will display the PlugPDF.framework and the PlugPDF.bundle.

Figure 12. Xcode project navigator

Figure 15. Xcode project navigator

4. Adding libraries

We must now add the libstdc++.dylib,libc.tbd,and libz.dylib libraries as well as the AVFoundation framework. So, first choose Build Phase > Link Binary With Libraries and then press on the + button as shown in the figure below.

Figure 13. Click on the + button

Figure 16. Click on the + button

Use the search box when the dialog window is opened, and easily find these two dynamic libraries.

Figure 14. Adding the libstdc++.dylib and libz.dylib libraries

Figure 17. Adding the libstdc++.dylib and libz.dylib libraries

The last step is adding the AVFoundation.framework, after which the Linked Frameworks and Libraries will be properly set. Finally make sure that your project is set like this figure.

Figure 15. Linked Frameworks and Libraries

Figure 15. Linked Frameworks and Libraries

5. Initialize the PlugPDF SDK

Firstly,  make sure that your sample.h file is as follows:

//  sample.h

//  sampleSwift


#import 

@interface sample : NSObject

+ (void)try:(void(^)())try catch: (void (^) (NSException *))catch;

@end

sample.m file is as below:

#import "sample.h"

@implementation sample

+ (void)try:(void (^)())try catch:(void (^)(NSException *))catch {
    @try {
        try ? try() : nil;
    } @catch (NSException *exception) {
        catch ? catch(exception) : nil;
    }
}
@end

your Bridging Header.h file is  as follows:

//

//  Use this file to import your target's public headers that you would like to expose to Swift.

//

#import "sample.h"

#import "PlugPDF/PlugPDF.h"

#import "PlugPDF/DocumentViewController.h"

The PlugPDF SDK is initialized from within the AppDelegate.swift file by calling the PlugPDFInit function from the didFinishLaunchingWithOptions method.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let s = "52B4GG3AEG244963ED3433E9A3BAH2A844CHD7E6A3A46C5883CEFBF5" // Put your license key
        let cs = (s as NSString).utf8String;
        let buffer = UnsafeMutablePointer(mutating: cs);        
        sample.try({ () -> Void in
            PlugPDFInit(buffer);
        }, catch: {(exception) -> Void in
            print(exception!);
        });     
        let vc:ViewController = ViewController();
        let navigationController:UINavigationController = UINavigationController(rootViewController: vc);
        self.window?.rootViewController = navigationController;
        return true
    }

Then we just have to call the PlugPDFUninit(); function from the applicationWillTerminate method.

 func applicationWillTerminate(_ application: UIApplication) {
        PlugPDFUninit ();
    }

In a nutshell, make sure that your AppDelegate.m file is as follows:

//  AppDelegate.swift
//  sampleSwift
//  Created by epapyrus on 2017. 4. 12..
//  Copyright © 2017 plugpdf. All rights reserved.
//
import UIKit

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let s = "52B4GG3AEG244963ED3433E9A3BAH2A844CHD7E6A3A46C5883CEFBF5" // Put your license key
        let cs = (s as NSString).utf8String;
        let buffer = UnsafeMutablePointer(mutating: cs);
        sample.try({ () -> Void in
            PlugPDFInit(buffer);
        }, catch: {(exception) -> Void in
            print(exception!);
        });
        let vc:ViewController = ViewController();
        let navigationController:UINavigationController = UINavigationController(rootViewController: vc);
        self.window?.rootViewController = navigationController;
        // Override point for customization after application launch.
        return true
    }
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }
    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }
    func applicationWillEnterForeground(_ application: UIApplication) {

        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }
    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }
    func applicationWillTerminate(_ application: UIApplication) {
        PlugPDFUninit ();
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}

At this stage we can already run our first PDF application; if everything is ok Xcode will launch the iOS simulator.

6. Building the PDF viewer

In the previous section we have first created a Single View Application and then we’ve successfully initialized the PlugPDF SDK in the AppDelegate.swift file, however we still haven’t seen any of the cool PDF features and classes that are at our disposal. With the PlugPDFDocumentViewController class, embedding the following fully functional PDF reader into your iOS app is really a snap.

Let’s look at this example:

Figure 16. The user is displayed the Gone With the Wind button

Figure 16. The user is displayed the Gone With the Wind button

Figure 17. The PDF ebook is opened once the button above is clicked

Figure 17. The PDF ebook is opened once the button above is clicked

Figure 18. The main tool bar is displayed when clicking on the top of the simulator’s screen

Figure 18. The main tool bar is displayed when clicking on the top of the simulator’s screen

This simple yet effective PDF reader comes with these tools:

  • Rotate
  • Page display mode
  • Brightness
  • Outline
  • Search
  • Edit

There’s one important thing to notice:

let path = Bundle.main.path(forResource: "your", ofType: "pdf")

Indeed, our sample code is loading a PDF file called Gone_With_the_Wind.pdf but you can refer to any PDF file; in either case please add your PDF file to Xcode’s Copy Bundle Resources, otherwise you’ll get this error: Exception CorruptedPDF Thrown when a pass-in data or file is not PDF document or corrupted.

Figure 19. Copy Bundle Resources

Figure 19. Copy Bundle Resources

That’s it for now. We have already completed this tutorial for building an iOS PDF reader.

Then update your ViewController.swift as follows:

//
//  ViewController.swift
//  sampleSwift
//
//  Created by epapyrus on 2017. 4. 12..
//  Copyright © 2017 plugpdf. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(frame: CGRect(x: 200, y: 200, width: 100, height: 44))

        button.setTitle("Button Title", for: .normal)

        button.backgroundColor = UIColor.lightGray

        button.addTarget(self, action: #selector(ratingButtonTapped), for: .touchUpInside)

        self.view.addSubview(button)
        }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    func ratingButtonTapped() {
        let path = Bundle.main.path(forResource: "1234", ofType: "pdf") // path for your pdf file with name
        let password = ""
        let title = "plugPDF"
        if let url = NSURL(string: path!) {
            do {
                let newUrl = "file://\(url)";
                let data:NSData = try NSData.init(contentsOf: NSURL(string: newUrl)! as URL);
                let vc = PlugPDFDocumentViewController.initWith(data as Data!, password: password, title: title);
                self.navigationController?.pushViewController(vc!, animated: true)             
            } catch {
                print(error)
            }
        }
    }
}