Sample Obj-C code for using Apryse SDK to read encrypted (password protected) documents, secure a document with encryption, or remove encryption. Learn more about our iOS SDK.
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6#import <OBJC/PDFNetOBJC.h>
7#import <Foundation/Foundation.h>
8
9//---------------------------------------------------------------------------------------
10// This sample shows encryption support in PDFNet. The sample reads an encrypted document and
11// sets a new SecurityHandler. The sample also illustrates how password protection can
12// be removed from an existing PDF document.
13//---------------------------------------------------------------------------------------
14int main(int argc, char *argv[])
15{
16 @autoreleasepool {
17 int ret = 0;
18 [PTPDFNet Initialize: 0];
19
20 // Example 1:
21 // secure a PDF document with password protection and adjust permissions
22
23 @try
24 {
25 // Open the test file
26 NSLog(@"Securing an existing document ...");
27 PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/fish.pdf"];
28 [doc InitSecurityHandler];
29
30 // Perform some operation on the document. In this case we use low level SDF API
31 // to replace the content stream of the first page with contents of file 'my_stream.txt'
32 if (NO) // Optional
33 {
34 NSLog(@"Replacing the content stream, use Flate compression...");
35
36 // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
37 PTObj *page_dict = [[[[[[[[doc GetTrailer] Get: @"Root"] Value] Get: @"Pages"] Value ] Get: @"Kids"] Value] GetAt: 0];
38
39 // Embed a custom stream (file mystream.txt) using Flate compression.
40 PTMappedFile *embed_file = [[PTMappedFile alloc] initWithFilename: @"../../TestFiles/mystream.txt"];
41 PTFilterReader *mystm = [[PTFilterReader alloc] initWithFilter: embed_file];
42 PTFlateEncode *encode = [[PTFlateEncode alloc] initWithInput_filter: [[PTFilter alloc] init] compression_level: -1 buf_sz: 256];
43 [page_dict Put: @"Contents" obj: [doc CreateIndirectStream: mystm filter_chain: encode]];
44 }
45
46 //encrypt the document
47
48
49 // Apply a new security handler with given security settings.
50 // In order to open saved PDF you will need a user password 'test'.
51 PTSecurityHandler *new_handler = [[PTSecurityHandler alloc] init];
52
53 // Set a new password required to open a document
54 NSString* user_password=@"test";
55 [new_handler ChangeUserPassword: user_password];
56
57 // Set Permissions
58 [new_handler SetPermission: e_ptprint value: YES];
59 [new_handler SetPermission: e_ptextract_content value: NO];
60
61 // Note: document takes the ownership of new_handler.
62 [doc SetSecurityHandler: new_handler];
63
64 // Save the changes.
65 NSLog(@"Saving modified file...");
66 [doc SaveToFile: @"../../TestFiles/Output/secured.pdf" flags: 0];
67
68 }
69 @catch(NSException *e)
70 {
71 NSLog(@"%@", e.reason);
72 ret = 1;
73 }
74
75 // Example 2:
76 // Opens an encrypted PDF document and removes its security.
77
78 @try
79 {
80 PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/Output/secured.pdf"];
81
82 //If the document is encrypted prompt for the password
83 if (![doc InitSecurityHandler])
84 {
85 bool success=NO;
86 NSLog(@"The password is: test");
87 int count;
88 for(count=0; count<3;count++)
89 {
90 char input[255];
91 NSLog(@"A password required to open the document.");
92 NSLog(@"Please enter the password:");
93 //scanf("%c", &input);
94 NSString *password = @"test";
95 // int i = 0;
96 // for (; i < 254; i++) {
97 // if (input[i] == '\0') {
98 // break;
99 // }
100 // [password stringByAppendingFormat: @"%c", input[i]];
101 // }
102
103 if([doc InitStdSecurityHandler: password])
104 {
105 success=true;
106 NSLog(@"The password is correct.");
107 break;
108 }
109 else if(count<3)
110 {
111 NSLog(@"The password is incorrect, please try again.");
112 }
113 }
114 if(!success)
115 {
116 NSLog(@"Document authentication error....");
117 ret = 1;
118 return ret;
119 }
120
121 PTSecurityHandler *hdlr = [doc GetSecurityHandler];
122 NSLog(@"Document Open Password: %d", [hdlr IsUserPasswordRequired]);
123 NSLog(@"Permissions Password: %d", [hdlr IsMasterPasswordRequired]);
124 NSLog(@"Permissions: ");
125 NSLog(@" Has 'owner' permissions: %d", [hdlr GetPermission: e_ptowner]);
126 NSLog(@" Open and decrypt the document: %d", [hdlr GetPermission: e_ptdoc_open]);
127 NSLog(@" Allow content extraction: %d", [hdlr GetPermission: e_ptextract_content]);
128 NSLog(@" Allow full document editing: %d", [hdlr GetPermission: e_ptdoc_modify]);
129 NSLog(@" Allow printing: %d", [hdlr GetPermission: e_ptprint]);
130 NSLog(@" Allow high resolution printing: %d", [hdlr GetPermission: e_ptprint_high]);
131 NSLog(@" Allow annotation editing: %d", [hdlr GetPermission: e_ptmod_annot]);
132 NSLog(@" Allow form fill: %d", [hdlr GetPermission: e_ptfill_forms]);
133 NSLog(@" Allow content extraction for accessibility: %d", [hdlr GetPermission: e_ptaccess_support]);
134 NSLog(@" Allow document assembly: %d", [hdlr GetPermission: e_ptassemble_doc]);
135 }
136
137 //remove all security on the document
138 [doc RemoveSecurity];
139 [doc SaveToFile: @"../../TestFiles/Output/not_secured.pdf" flags: 0];
140
141 }
142 @catch(NSException *e)
143 {
144 NSLog(@"%@", e.reason);
145 ret = 1;
146 }
147
148 // Example 3:
149 // Encrypt/Decrypt a PDF using PDFTron custom security handler
150
151 @try
152 {
153 NSLog(@"-------------------------------------------------");
154 NSLog(@"Encrypt a document using PDFTron Custom Security handler with a custom id and password...");
155 PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/BusinessCardTemplate.pdf"];
156
157 // Create PDFTron custom security handler with a custom id. Replace this with your own integer
158 unsigned int custom_id = 123456789;
159 PTSecurityHandler* custom_handler = [[PTPDFTronCustomSecurityHandler alloc] initWithCustom_id : custom_id];
160
161 // Add a password to the custom security handler
162 NSString *pass = @"test";
163 [custom_handler ChangeUserPassword: pass];
164
165 [doc SetSecurityHandler: custom_handler];
166
167 // Save the changes.
168 [doc SaveToFile: @"../../TestFiles/Output/BusinessCardTemplate_enc.pdf" flags: 0];
169
170
171 NSLog(@"Decrypt the PDFTron custom security encrypted document above...");
172 // Register the PDFTron Custom Security handler with the same custom id used in encryption
173 [PTPDFNet AddPDFTronCustomHandler : custom_id];
174 PTPDFDoc *doc_enc = [[PTPDFDoc alloc] initWithFilepath: @"../../TestFiles/Output/BusinessCardTemplate_enc.pdf"];
175 [doc_enc InitStdSecurityHandler : pass];
176 [doc RemoveSecurity];
177 // Save the decrypted document
178 [doc SaveToFile: @"../../TestFiles/Output/BusinessCardTemplate_enc_dec.pdf" flags: 0];
179 NSLog(@"Done. Result saved in BusinessCardTemplate_enc_dec.pdf");
180
181 }
182 @catch(NSException *e)
183 {
184 NSLog(@"%@", e.reason);
185 ret = 1;
186 }
187 [PTPDFNet Terminate: 0];
188 return ret;
189 }
190}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6import PDFNet
7import Foundation
8
9//---------------------------------------------------------------------------------------
10// This sample shows encryption support in PDFNet. The sample reads an encrypted document and
11// sets a new SecurityHandler. The sample also illustrates how password protection can
12// be removed from an existing PDF document.
13//---------------------------------------------------------------------------------------
14func runEncTest() -> Int {
15 return autoreleasepool {
16 var ret: Int = 0
17
18
19 // Example 1:
20 // secure a PDF document with password protection and adjust permissions
21
22 do {
23 try PTPDFNet.catchException {
24 // Open the test file
25 print("Securing an existing document ...")
26 let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "fish", ofType: "pdf"))
27 doc.initSecurityHandler()
28
29 // Perform some operation on the document. In this case we use low level SDF API
30 // to replace the content stream of the first page with contents of file 'my_stream.txt'
31 if false {
32// print("Replacing the content stream, use Flate compression...")
33//
34// // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
35// let page_dict: PTObj = doc.getTrailer().get("Root").value().get("Pages").value().get("Kids").value().getAt(0)
36//
37// // Embed a custom stream (file mystream.txt) using Flate compression.
38// let embed_file = PTMappedFile(filename: Bundle.main.path(forResource: "my_stream", ofType: "txt"))
39// let mystm = PTFilterReader(filter: embed_file)
40// let encode = PTFlateEncode(input_filter: PTFilter(), compression_level: -1, buf_sz: 256)
41// page_dict.put("Contents", obj: doc.createIndirectStream(mystm, filter_chain: encode))
42 }
43
44 //encrypt the document
45
46
47 // Apply a new security handler with given security settings.
48 // In order to open saved PDF you will need a user password 'test'.
49 let new_handler: PTSecurityHandler = PTSecurityHandler()
50
51 // Set a new password required to open a document
52 let user_password = "test"
53 new_handler.changeUserPassword(user_password)
54
55 // Set Permissions
56 new_handler.setPermission(e_ptprint, value: true)
57 new_handler.setPermission(e_ptextract_content, value: false)
58
59 // Note: document takes the ownership of new_handler.
60 doc.setSecurityHandler(new_handler)
61
62 // Save the changes.
63 print("Saving modified file...")
64 doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("secured.pdf").path, flags: 0)
65
66 }
67 } catch let e as NSError {
68 print("Uncaught exception: \(e)")
69 ret = 1
70 }
71
72 // Example 2:
73 // Opens an encrypted PDF document and removes its security.
74
75 do {
76 try PTPDFNet.catchException {
77 let doc: PTPDFDoc = PTPDFDoc(filepath: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("secured.pdf").path)
78
79 //If the document is encrypted prompt for the password
80 if !doc.initSecurityHandler() {
81 var success = false
82 print("The password is: test")
83 for count in 0..<3 {
84 print("A password is required to open the document.")
85 print("Please enter the password:")
86 //let input = readLine()
87 let password = "test"
88 //for i in 0..<255 {
89 // let value = input[input.index(input.startIndex, offsetBy: i)]
90 // if value == "\0" {
91 // break
92 // }
93 // password += ("\(value)")
94 //}
95
96 if doc.initStdSecurityHandler(password) {
97 success = true
98 print("The password is correct.")
99 break
100 }
101 else if count < 3 {
102 print("The password is incorrect, please try again.")
103 }
104 }
105 if !success {
106 print("Document authentication error....")
107 ret = 1
108 return
109 }
110
111 let hdlr: PTSecurityHandler = doc.getSecurityHandler()
112 print("Document Open Password: \(hdlr.isUserPasswordRequired())")
113 print("Permissions Password: \(hdlr.isMasterPasswordRequired())")
114 print("Permissions: ")
115 print(" Has 'owner' permissions: \(hdlr.getPermission(e_ptowner))")
116 print(" Open and decrypt the document: \(hdlr.getPermission(e_ptdoc_open))")
117 print(" Allow content extraction: \(hdlr.getPermission(e_ptextract_content))")
118 print(" Allow full document editing: \(hdlr.getPermission(e_ptdoc_modify))")
119 print(" Allow printing: \(hdlr.getPermission(e_ptprint))")
120 print(" Allow high resolution printing: \(hdlr.getPermission(e_ptprint_high))")
121 print(" Allow annotation editing: \(hdlr.getPermission(e_ptmod_annot))")
122 print(" Allow form fill: \(hdlr.getPermission(e_ptfill_forms))")
123 print(" Allow content extraction for accessibility: \(hdlr.getPermission(e_ptaccess_support))")
124 print(" Allow document assembly: \(hdlr.getPermission(e_ptassemble_doc))")
125 }
126
127 //remove all security on the document
128 doc.removeSecurity()
129 doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("not_secured.pdf").path, flags: 0)
130 }
131 } catch let e as NSError {
132 print("Uncaught exception: \(e)")
133 ret = 1
134 }
135
136 return ret
137 }
138}
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales