Some test text!

Search
Hamburger Icon

Encrypt and decrypt PDF files in Swift

More languages

More languages
JavaScript
Java (Android)
C++
C#
C# (.NET Core)
Go
Java
Kotlin
Obj-C
JS (Node.js)
PHP
Python
Ruby
Swift
C# (UWP)
VB
C# (Xamarin)

Sample Swift code for using PDFTron SDK to read encrypted (password protected) documents, secure a document with encryption, or remove encryption. Learn more about our Swift PDF Library.

Get Started Samples Download

To run this sample, get started with a free trial of Apryse SDK.

//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import PDFNet
import Foundation

//---------------------------------------------------------------------------------------
// This sample shows encryption support in PDFNet. The sample reads an encrypted document and
// sets a new SecurityHandler. The sample also illustrates how password protection can
// be removed from an existing PDF document.
//---------------------------------------------------------------------------------------
func runEncTest() -> Int {
    return autoreleasepool {
        var ret: Int = 0
        
        
        // Example 1:
        // secure a PDF document with password protection and adjust permissions

        do {
            try PTPDFNet.catchException {
                // Open the test file
                print("Securing an existing document ...")
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "fish", ofType: "pdf"))
                doc.initSecurityHandler()
                
                // Perform some operation on the document. In this case we use low level SDF API
                // to replace the content stream of the first page with contents of file 'my_stream.txt'
                if false {
//                    print("Replacing the content stream, use Flate compression...")
//                    
//                    // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
//                    let page_dict: PTObj = doc.getTrailer().get("Root").value().get("Pages").value().get("Kids").value().getAt(0)
//                    
//                    // Embed a custom stream (file mystream.txt) using Flate compression.
//                    let embed_file = PTMappedFile(filename: Bundle.main.path(forResource: "my_stream", ofType: "txt"))
//                    let mystm = PTFilterReader(filter: embed_file)
//                    let encode = PTFlateEncode(input_filter: PTFilter(), compression_level: -1, buf_sz: 256)
//                    page_dict.put("Contents", obj: doc.createIndirectStream(mystm, filter_chain: encode))
                }
                
                //encrypt the document
                
                
                // Apply a new security handler with given security settings.
                // In order to open saved PDF you will need a user password 'test'.
                let new_handler: PTSecurityHandler = PTSecurityHandler()
                
                // Set a new password required to open a document
                let user_password = "test"
                new_handler.changeUserPassword(user_password)
                
                // Set Permissions
                new_handler.setPermission(e_ptprint, value: true)
                new_handler.setPermission(e_ptextract_content, value: false)
                
                // Note: document takes the ownership of new_handler.
                doc.setSecurityHandler(new_handler)
                
                // Save the changes.
                print("Saving modified file...")
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("secured.pdf").path, flags: 0)

            }
        } catch let e as NSError {
            print("Uncaught exception: \(e)")
            ret = 1
        }
        
        // Example 2:
        // Opens an encrypted PDF document and removes its security.
        
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("secured.pdf").path)
                
                //If the document is encrypted prompt for the password
                if !doc.initSecurityHandler() {
                    var success = false
                    print("The password is: test")
                    for count in 0..<3 {
                        print("A password is required to open the document.")
                        print("Please enter the password:")
                        //let input = readLine()
                        let password = "test"
                        //for i in 0..<255 {
                        //    let value = input[input.index(input.startIndex, offsetBy: i)]
                        //    if value == "\0" {
                        //        break
                        //    }
                        //    password += ("\(value)")
                        //}
                        
                        if doc.initStdSecurityHandler(password) {
                            success = true
                            print("The password is correct.")
                            break
                        }
                        else if count < 3 {
                            print("The password is incorrect, please try again.")
                        }
                    }
                    if !success {
                        print("Document authentication error....")
                        ret = 1
                        return
                    }
                    
                    let hdlr: PTSecurityHandler = doc.getSecurityHandler()
                    print("Document Open Password: \(hdlr.isUserPasswordRequired())")
                    print("Permissions Password: \(hdlr.isMasterPasswordRequired())")
                    print("Permissions: ")
                    print("    Has 'owner' permissions: \(hdlr.getPermission(e_ptowner))")
                    print("    Open and decrypt the document: \(hdlr.getPermission(e_ptdoc_open))")
                    print("    Allow content extraction: \(hdlr.getPermission(e_ptextract_content))")
                    print("    Allow full document editing: \(hdlr.getPermission(e_ptdoc_modify))")
                    print("    Allow printing: \(hdlr.getPermission(e_ptprint))")
                    print("    Allow high resolution printing: \(hdlr.getPermission(e_ptprint_high))")
                    print("    Allow annotation editing: \(hdlr.getPermission(e_ptmod_annot))")
                    print("    Allow form fill: \(hdlr.getPermission(e_ptfill_forms))")
                    print("    Allow content extraction for accessibility: \(hdlr.getPermission(e_ptaccess_support))")
                    print("    Allow document assembly: \(hdlr.getPermission(e_ptassemble_doc))")
                }
                
                //remove all security on the document
                doc.removeSecurity()
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("not_secured.pdf").path, flags: 0)
            }
        } catch let e as NSError {
            print("Uncaught exception: \(e)")
            ret = 1
        }
        
        return ret
    }
}