Sample C# code for using Apryse SDK to read encrypted (password protected) documents, secure a document with encryption, or remove encryption. Learn more about our Server SDK.
1//
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3//
4
5using System;
6using pdftron;
7using pdftron.Common;
8using pdftron.Filters;
9using pdftron.SDF;
10using pdftron.PDF;
11
12namespace EncTestCS
13{
14 // A custom security handler used to obtain document password dynamically via user feedback.
15 class MySecurityHandler : StdSecurityHandler
16 {
17 public MySecurityHandler (Int32 key_len, Int32 enc_code) : base(key_len, enc_code) {}
18 public MySecurityHandler (MySecurityHandler s) : base(s) {}
19
20 // In this callback ask the user for password/authorization data.
21 // This may involve a dialog box used to collect authorization data or something else.
22 override public bool GetAuthorizationData (SecurityHandler.Permission p)
23 {
24 Console.WriteLine("The input file requires user password.");
25 Console.WriteLine("Please enter the password:");
26 String pass = Console.ReadLine();
27 InitPassword(pass);
28 return true;
29 }
30
31 // This callback could be used to customize security handler preferences.
32 override public bool EditSecurityData(SDFDoc doc) { return false; }
33
34 // This callback is used when authorization process fails.
35 override public void AuthorizeFailed()
36 {
37 Console.WriteLine("Authorize failed...");
38 }
39
40 public static SecurityHandler Create(String name, Int32 key_len, Int32 enc_code) { return new MySecurityHandler(key_len, enc_code); }
41
42 override public SecurityHandler Clone() { return new MySecurityHandler(this); }
43 }
44
45 /// <summary>
46 //---------------------------------------------------------------------------------------
47 // This sample shows encryption support in PDFNet. The sample reads an encrypted document and
48 // sets a new SecurityHandler. The sample also illustrates how password protection can
49 // be removed from an existing PDF document.
50 //---------------------------------------------------------------------------------------
51 /// </summary>
52 class Class1
53 {
54 private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
55 static Class1() {}
56
57 static void Main(string[] args)
58 {
59 PDFNet.Initialize(PDFTronLicense.Key);
60
61 // Relative path to the folder containing test files.
62 string input_path = "../../../../TestFiles/";
63 string output_path = "../../../../TestFiles/Output/";
64
65 // Example 1: Securing a document with password protection and adjusting permissions
66 // on the document.
67 try
68 {
69 // Open the test file
70 Console.WriteLine("-------------------------------------------------");
71 Console.WriteLine("Securing an existing document...");
72 using (PDFDoc doc = new PDFDoc(input_path + "fish.pdf"))
73 {
74
75 if (!doc.InitSecurityHandler())
76 {
77 Console.WriteLine("Document authentication error...");
78 return;
79 }
80
81 // Perform some operation on the document. In this case we use low level SDF API
82 // to replace the content stream of the first page with contents of file 'my_stream.txt'
83 if (true) // Optional
84 {
85 Console.WriteLine("Replacing the content stream, use flate compression...");
86
87 // Get the first page dictionary using the following path: trailer/Root/Pages/Kids/0
88 Obj page_dict = doc.GetTrailer().Get("Root").Value().
89 Get("Pages").Value().Get("Kids").Value().GetAt(0);
90
91 // Embed a custom stream (file mystream.txt) using Flate compression.
92 MappedFile embed_file = new MappedFile(input_path + "my_stream.txt");
93 FilterReader mystm = new FilterReader(embed_file);
94 page_dict.Put("Contents", doc.CreateIndirectStream(mystm));
95 embed_file.Close();
96 }
97
98 // Apply a new security handler with given security settings.
99 // In order to open saved PDF you will need a user password 'test'.
100 StdSecurityHandler new_handler = new StdSecurityHandler();
101
102 // Set a new password required to open a document
103 string my_password = "test";
104 new_handler.ChangeUserPassword(my_password);
105
106 // Set Permissions
107 new_handler.SetPermission (SecurityHandler.Permission.e_print, true);
108 new_handler.SetPermission (SecurityHandler.Permission.e_extract_content, false);
109
110 // Note: document takes the ownership of new_handler.
111 doc.SetSecurityHandler(new_handler);
112
113 // Save the changes.
114 Console.WriteLine("Saving modified file...");
115 doc.Save(output_path + "secured.pdf", 0);
116 }
117
118 Console.WriteLine("Done. Result saved in secured.pdf");
119 }
120 catch (PDFNetException e)
121 {
122 Console.WriteLine(e.Message);
123 }
124
125 // Example 2: Reading password protected document without user feedback.
126 try
127 {
128 // In this sample case we will open an encrypted document that
129 // requires a user password in order to access the content.
130 Console.WriteLine("-------------------------------------------------");
131 Console.WriteLine("Open the password protected document from the first example...");
132 using (PDFDoc doc = new PDFDoc(output_path + "secured.pdf")) // Open the encrypted document that we saved in the first example.
133 {
134
135 Console.WriteLine("Initializing security handler without any user interaction...");
136
137 // At this point MySecurityHandler callbacks will be invoked.
138 // MySecurityHandler.GetAuthorizationData() should collect the password and
139 // AuthorizeFailed() is called if user repeatedly enters a wrong password.
140 if (!doc.InitStdSecurityHandler("test"))
141 {
142 Console.WriteLine("Document authentication error...");
143 Console.WriteLine("The password is not valid.");
144 return;
145 }
146 else
147 {
148 Console.WriteLine("The password is correct! Document can now be used for reading and editing");
149
150 // Remove the password security and save the changes to a new file.
151 doc.RemoveSecurity();
152 doc.Save(output_path + "secured_nomore1.pdf", 0);
153 Console.WriteLine("Done. Result saved in secured_nomore1.pdf");
154 }
155
156 }
157 }
158 catch (PDFNetException e)
159 {
160 Console.WriteLine(e.Message);
161 }
162
163 // Example 3:
164 // Encrypt/Decrypt a PDF using PDFTron custom security handler
165 try
166 {
167 Console.WriteLine("-------------------------------------------------");
168 Console.WriteLine("Encrypt a document using PDFTron Custom Security handler with a custom id and password...");
169 PDFDoc doc = new PDFDoc(input_path + "BusinessCardTemplate.pdf");
170
171 // Create PDFTron custom security handler with a custom id. Replace this with your own integer
172 int custom_id = 123456789;
173 PDFTronCustomSecurityHandler custom_handler = new PDFTronCustomSecurityHandler(custom_id);
174
175 // Add a password to the custom security handler
176 String pass = "test";
177 custom_handler.ChangeUserPassword(pass);
178
179 // Save the encrypted document
180 doc.SetSecurityHandler(custom_handler);
181 doc.Save(output_path + "BusinessCardTemplate_enc.pdf", 0);
182
183 Console.WriteLine("Decrypt the PDFTron custom security encrypted document above...");
184 // Register the PDFTron Custom Security handler with the same custom id used in encryption
185 PDFNet.AddPDFTronCustomHandler(custom_id);
186
187 PDFDoc doc_enc = new PDFDoc(output_path + "BusinessCardTemplate_enc.pdf");
188 doc_enc.InitStdSecurityHandler(pass);
189 doc_enc.RemoveSecurity();
190 // Save the decrypted document
191 doc_enc.Save(output_path + "BusinessCardTemplate_enc_dec.pdf", 0);
192 Console.WriteLine("Done. Result saved in BusinessCardTemplate_enc_dec.pdf");
193 }
194 catch (PDFNetException e)
195 {
196 Console.WriteLine(e.Message);
197 }
198
199 // Example 4: Reading password protected document with user feedback.
200 try
201 {
202 // Register standard security. Reguired only once per application session.
203 CreateDelegate del = new CreateDelegate(MySecurityHandler.Create);
204 SecurityManagerSingleton.Instance().RegisterSecurityHandler("Standard",
205 new SecurityDescriptor("Standard Security", del));
206
207 Console.WriteLine("-------------------------------------------------");
208 Console.WriteLine("Open the password protected document from the first example...");
209 using (PDFDoc doc = new PDFDoc(output_path + "secured.pdf")) // Open the encrypted document that we saved in the first example.
210 {
211
212 Console.WriteLine("Initializing security handler. The password will now be collected from the user");
213 Console.WriteLine("Enter 'test' as the password.");
214
215 // At this point MySecurityHandler callbacks will be invoked.
216 // MySecurityHandler.GetAuthorizationData() should collect the password and
217 // AuthorizeFailed() is called if user repeatedly enters a wrong password.
218 if (!doc.InitSecurityHandler())
219 {
220 Console.WriteLine("Document authentication error...");
221 Console.WriteLine("The password is not valid.");
222 return;
223 }
224 else
225 {
226 Console.WriteLine("The password is correct! Document can now be used for reading and editing");
227
228 // Remove the password security and save the changes to a new file.
229 doc.RemoveSecurity();
230 doc.Save(output_path + "secured_nomore2.pdf", 0);
231 Console.WriteLine("Done. Result saved in secured_nomore2.pdf");
232 }
233 }
234 }
235 catch (PDFNetException e)
236 {
237 Console.WriteLine(e.Message);
238 }
239 PDFNet.Terminate();
240 Console.WriteLine("-------------------------------------------------");
241 Console.WriteLine("Tests completed.");
242
243 }
244 }
245}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
3// Consult LICENSE.txt regarding license information.
4//---------------------------------------------------------------------------------------
5
6package main
7import (
8 "fmt"
9 "strconv"
10 . "pdftron"
11)
12
13import "pdftron/Samples/LicenseKey/GO"
14
15//---------------------------------------------------------------------------------------
16// This sample shows encryption support in PDFNet. The sample reads an encrypted document and
17// sets a new SecurityHandler. The sample also illustrates how password protection can
18// be removed from an existing PDF document.
19//---------------------------------------------------------------------------------------
20
21func main(){
22 PDFNetInitialize(PDFTronLicense.Key)
23
24 // Relative path to the folder containing the test files.
25 inputPath := "../../TestFiles/"
26 outputPath := "../../TestFiles/Output/"
27
28 // Example 1:
29 // secure a PDF document with password protection and adjust permissions
30
31 // Open the test file
32 fmt.Println("Securing an existing document...")
33
34 doc := NewPDFDoc(inputPath + "fish.pdf")
35 doc.InitSecurityHandler()
36
37 // Perform some operation on the document. In this case we use low level SDF API
38 // to replace the content stream of the first page with contents of file 'my_stream.txt'
39 if true{ // Optional
40 fmt.Println("Replacing the content stream, use Flate compression...")
41
42 // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
43 pageDict := (doc.GetTrailer().Get("Root").Value().Get("Pages").Value().Get("Kids").Value().GetAt(0))
44
45 // Embed a custom stream (file mystream.txt) using Flate compression.
46 embedFile := NewMappedFile(inputPath + "my_stream.txt")
47 mystm := NewFilterReader(embedFile)
48 pageDict.Put("Contents", doc.CreateIndirectStream(mystm, NewFilter()))
49 }
50 // encrypt the document
51
52 // Apply a new security handler with given security settings.
53 // In order to open saved PDF you will need a user password 'test'.
54 newHandler := NewSecurityHandler()
55
56 // Set a new password required to open a document
57 userPassword := "test"
58 newHandler.ChangeUserPassword(userPassword)
59
60 // Set permissions
61 newHandler.SetPermission(SecurityHandlerE_print, true)
62 newHandler.SetPermission(SecurityHandlerE_extract_content, false)
63
64 // Note: document takes the ownership of newHandler.
65 doc.SetSecurityHandler(newHandler)
66
67 // save the changes.
68 fmt.Println("Saving modified file...")
69 doc.Save(outputPath + "secured.pdf", uint(0))
70 doc.Close()
71
72 // Example 2:
73 // Opens an encrypted PDF document and removes its security.
74
75 doc = NewPDFDoc(outputPath + "secured.pdf")
76
77 // If the document is encrypted prompt for the password
78 if !doc.InitSecurityHandler(){
79 success := false
80 fmt.Println("The password is: test")
81 count := 0
82 for count < 3{
83 fmt.Println("A password required to open the document.")
84 var password string
85 fmt.Print("Please enter the password: \n")
86 fmt.Scanf("%s", &password)
87 fmt.Println(password)
88
89 if doc.InitStdSecurityHandler(password, len(password)){
90 success = true
91 fmt.Println("The password is correct.")
92 break
93 }else if count < 3{
94 fmt.Println("The password is incorrect, please try again")
95 }
96 count = count + 1
97 }
98 if !success{
99 fmt.Println("Document authentication error....")
100 return
101 }
102 hdlr := doc.GetSecurityHandler()
103 fmt.Println("Document Open Password: " + strconv.FormatBool(hdlr.IsUserPasswordRequired()))
104 fmt.Println("Permissions Password: " + strconv.FormatBool(hdlr.IsMasterPasswordRequired()))
105 fmt.Println(("Permissions: " +
106 "\n\tHas 'owner' permissions: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_owner)) +
107 "\n\tOpen and decrypt the document: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_doc_open)) +
108 "\n\tAllow content extraction: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_extract_content)) +
109 "\n\tAllow full document editing: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_doc_modify) ) +
110 "\n\tAllow printing: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_print)) +
111 "\n\tAllow high resolution printing: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_print_high)) +
112 "\n\tAllow annotation editing: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_mod_annot)) +
113 "\n\tAllow form fill: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_fill_forms)) +
114 "\n\tAllow content extraction for accessibility: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_access_support)) +
115 "\n\tAllow document assembly: " + strconv.FormatBool(hdlr.GetPermission(SecurityHandlerE_assemble_doc))))
116 }
117
118 // remove all security on the document
119 doc.RemoveSecurity()
120 doc.Save(outputPath + "not_secured.pdf", uint(0))
121 doc.Close()
122
123 PDFNetTerminate()
124 fmt.Println("Test completed.")
125}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6import java.io.BufferedReader;
7import java.io.IOException;
8import java.io.InputStreamReader;
9
10import com.pdftron.common.PDFNetException;
11import com.pdftron.filters.FilterReader;
12import com.pdftron.filters.FlateEncode;
13import com.pdftron.filters.MappedFile;
14import com.pdftron.pdf.*;
15import com.pdftron.sdf.*;
16
17
18//---------------------------------------------------------------------------------------
19// This sample shows encryption support in PDFNet. The sample reads an encrypted document and
20// sets a new SecurityHandler. The sample also illustrates how password protection can
21// be removed from an existing PDF document.
22//---------------------------------------------------------------------------------------
23public class EncTest {
24 public static void main(String[] args) {
25 PDFNet.initialize(PDFTronLicense.Key());
26
27 // Relative path to the folder containing test files.
28 String input_path = "../../TestFiles/";
29 String output_path = "../../TestFiles/Output/";
30
31 // Example 1:
32 // secure a document with password protection and
33 // adjust permissions
34
35 // Open the test file
36 System.out.println("Securing an existing document ...");
37 try (PDFDoc doc = new PDFDoc((input_path + "fish.pdf"))) {
38 doc.initSecurityHandler();
39
40 // Perform some operation on the document. In this case we use low level SDF API
41 // to replace the content stream of the first page with contents of file 'my_stream.txt'
42 if (true) // Optional
43 {
44 System.out.println("Replacing the content stream, use flate compression...");
45
46 // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
47 Obj page_dict = doc.getTrailer().get("Root").value()
48 .get("Pages").value()
49 .get("Kids").value()
50 .getAt(0);
51
52 // Embed a custom stream (file mystream.txt) using Flate compression.
53 MappedFile embed_file = new MappedFile((input_path + "my_stream.txt"));
54 FilterReader mystm = new FilterReader(embed_file);
55 page_dict.put("Contents",
56 doc.createIndirectStream(mystm,
57 new FlateEncode(null)));
58 }
59
60 //encrypt the document
61
62 // Apply a new security handler with given security settings.
63 // In order to open saved PDF you will need a user password 'test'.
64 SecurityHandler new_handler = new SecurityHandler();
65
66 // Set a new password required to open a document
67 String user_password = "test";
68 new_handler.changeUserPassword(user_password);
69
70 // Set Permissions
71 new_handler.setPermission(SecurityHandler.e_print, true);
72 new_handler.setPermission(SecurityHandler.e_extract_content, false);
73
74 // Note: document takes the ownership of new_handler.
75 doc.setSecurityHandler(new_handler);
76
77 // Save the changes.
78 System.out.println("Saving modified file...");
79 doc.save((output_path + "secured.pdf"), SDFDoc.SaveMode.NO_FLAGS, null);
80 } catch (PDFNetException e) {
81 e.printStackTrace();
82 }
83
84 // Example 2:
85 // Opens the encrypted document and removes all of
86 // its security.
87 try (PDFDoc doc = new PDFDoc((output_path + "secured.pdf"))) {
88 //If the document is encrypted prompt for the password
89 if (!doc.initSecurityHandler()) {
90 boolean success = false;
91 System.out.println("The password is: test");
92 for (int count = 0; count < 3; count++) {
93 BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
94 System.out.println("A password required to open the document.");
95 System.out.print("Please enter the password: ");
96 String password = r.readLine();
97 if (doc.initStdSecurityHandler(password)) {
98 success = true;
99 System.out.println("The password is correct.");
100 break;
101 } else if (count < 3) {
102 System.out.println("The password is incorrect, please try again");
103 }
104 }
105 if (!success) {
106 System.out.println("Document authentication error....");
107 PDFNet.terminate();
108 }
109 }
110
111 //remove all security on the document
112 doc.removeSecurity();
113 doc.save(output_path + "not_secured.pdf", SDFDoc.SaveMode.NO_FLAGS, null);
114 } catch (Exception e) {
115 e.printStackTrace();
116 }
117
118 // Example 3:
119 // Encrypt/Decrypt a PDF using PDFTron custom security handler
120 System.out.println("-------------------------------------------------");
121 System.out.println("Encrypt a document using PDFTron Custom Security handler with a custom id and password...");
122 try (PDFDoc doc = new PDFDoc(input_path + "BusinessCardTemplate.pdf"))
123 {
124 // Create PDFTron custom security handler with a custom id. Replace this with your own integer
125 int custom_id = 123456789;
126 PDFTronCustomSecurityHandler custom_handler = new PDFTronCustomSecurityHandler(custom_id);
127
128 // Add a password to the custom security handler
129 String pass = "test";
130 custom_handler.changeUserPassword(pass);
131
132 // Save the encrypted document
133 doc.setSecurityHandler(custom_handler);
134 doc.save(output_path + "BusinessCardTemplate_enc.pdf", SDFDoc.SaveMode.NO_FLAGS, null);
135
136 System.out.println("Decrypt the PDFTron custom security encrypted document above...");
137 // Register the PDFTron Custom Security handler with the same custom id used in encryption
138 PDFNet.addPDFTronCustomHandler(custom_id);
139
140 PDFDoc doc_enc = new PDFDoc(output_path + "BusinessCardTemplate_enc.pdf");
141 doc_enc.initStdSecurityHandler(pass);
142 doc_enc.removeSecurity();
143 // Save the decrypted document
144 doc_enc.save(output_path + "BusinessCardTemplate_enc_dec.pdf", SDFDoc.SaveMode.NO_FLAGS, null);
145 System.out.println("Done. Result saved in BusinessCardTemplate_enc_dec.pdf");
146 } catch (Exception e) {
147 e.printStackTrace();
148 }
149 System.out.println("-------------------------------------------------");
150 System.out.println("Tests completed.");
151 PDFNet.terminate();
152 }
153}
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#include <PDF/PDFNet.h>
7#include <PDF/PDFDoc.h>
8#include <SDF/SecurityHandler.h>
9#include <SDF/PDFTronCustomSecurityHandler.h>
10#include <Filters/FilterReader.h>
11#include <Filters/FlateEncode.h>
12#include <Filters/MappedFile.h>
13#include <iostream>
14#include <string>
15#include "../../LicenseKey/CPP/LicenseKey.h"
16
17using namespace std;
18
19using namespace pdftron;
20using namespace SDF;
21using namespace PDF;
22using namespace Filters;
23
24
25//---------------------------------------------------------------------------------------
26// This sample shows encryption support in PDFNet. The sample reads an encrypted document and
27// sets a new SecurityHandler. The sample also illustrates how password protection can
28// be removed from an existing PDF document.
29//---------------------------------------------------------------------------------------
30int main(int argc, char *argv[])
31{
32 int ret = 0;
33 PDFNet::Initialize(LicenseKey);
34
35 // Relative path to the folder containing test files.
36 string input_path = "../../TestFiles/";
37 string output_path = "../../TestFiles/Output/";
38
39 // Example 1:
40 // secure a PDF document with password protection and adjust permissions
41
42 try
43 {
44 // Open the test file
45 cout << "-------------------------------------------------" << endl << "Securing an existing document..." << endl;
46 PDFDoc doc((input_path + "fish.pdf").c_str());
47 if (!doc.InitSecurityHandler())
48 {
49 cout << "Document authentication error..." << endl;
50 ret = 1;
51 }
52
53
54 // Perform some operation on the document. In this case we use low level SDF API
55 // to replace the content stream of the first page with contents of file 'my_stream.txt'
56 if (true) // Optional
57 {
58 cout << "Replacing the content stream, use flate compression..." << endl;
59
60 // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
61 Obj page_dict = doc.GetTrailer().Get("Root").Value()
62 .Get("Pages").Value()
63 .Get("Kids").Value()
64 .GetAt(0);
65
66 // Embed a custom stream (file mystream.txt) using Flate compression.
67 MappedFile embed_file((input_path + "my_stream.txt"));
68 FilterReader mystm(embed_file);
69 page_dict.Put("Contents",
70 doc.CreateIndirectStream(mystm,
71 FlateEncode(Filter())));
72 }
73
74 //encrypt the document
75
76
77 // Apply a new security handler with given security settings.
78 // In order to open saved PDF you will need a user password 'test'.
79 SecurityHandler new_handler;
80
81 // Set a new password required to open a document
82 const char* user_password="test";
83 new_handler.ChangeUserPassword(user_password);
84
85 // Set Permissions
86 new_handler.SetPermission (SecurityHandler::e_print, true);
87 new_handler.SetPermission (SecurityHandler::e_extract_content, false);
88
89 // Note: document takes the ownership of new_handler.
90 doc.SetSecurityHandler(new_handler);
91
92 // Save the changes.
93 cout << "Saving modified file..." << endl;
94 doc.Save((output_path + "secured.pdf").c_str(), 0, NULL);
95
96 cout << "Done. Result saved in secured.pdf" << endl;
97 }
98 catch(Common::Exception& e) {
99 cout << e << endl;
100 ret = 1;
101 }
102 catch(...) {
103 cout << "Unknown Exception" << endl;
104 ret = 1;
105 }
106
107 // Example 2:
108 // Opens an encrypted PDF document and removes its security.
109
110 try
111 {
112 cout << "-------------------------------------------------" << endl;
113 cout << "Open the password protected document from the first example..." << endl;
114
115 // Open the encrypted document that we saved in the first example.
116 PDFDoc doc((output_path + "secured.pdf").c_str());
117
118 cout << "Initializing security handler without any user interaction..." << endl;
119
120 // At this point MySecurityHandler callbacks will be invoked.
121 // MySecurityHandler.GetAuthorizationData() should collect the password and
122 // AuthorizeFailed() is called if user repeatedly enters a wrong password.
123 if (!doc.InitStdSecurityHandler("test"))
124 {
125 cout << "Document authentication error..." << endl << "The password is not valid." << endl;
126 ret = 1;
127 }
128 else
129 {
130 cout << "The password is correct! Document can now be used for reading and editing" << endl;
131
132 // Remove the password security and save the changes to a new file.
133 doc.RemoveSecurity();
134 doc.Save(output_path + "secured_nomore1.pdf", 0, NULL);
135 cout << "Done. Result saved in secured_nomore1.pdf" << endl;
136
137 /*
138 SecurityHandler hdlr = doc.GetSecurityHandler();
139 cout << "Document Open Password: " << hdlr.IsUserPasswordRequired() << endl;
140 cout << "Permissions Password: " << hdlr.IsMasterPasswordRequired() << endl;
141 cout << "Permissions: "
142 << "\n\tHas 'owner' permissions: " << hdlr.GetPermission(SecurityHandler::e_owner)
143 << "\n\tOpen and decrypt the document: " << hdlr.GetPermission(SecurityHandler::e_doc_open)
144 << "\n\tAllow content extraction: " << hdlr.GetPermission(SecurityHandler::e_extract_content)
145 << "\n\tAllow full document editing: " << hdlr.GetPermission(SecurityHandler::e_doc_modify)
146 << "\n\tAllow printing: " << hdlr.GetPermission(SecurityHandler::e_print)
147 << "\n\tAllow high resolution printing: " << hdlr.GetPermission(SecurityHandler::e_print_high)
148 << "\n\tAllow annotation editing: " << hdlr.GetPermission(SecurityHandler::e_mod_annot)
149 << "\n\tAllow form fill: " << hdlr.GetPermission(SecurityHandler::e_fill_forms)
150 << "\n\tAllow content extraction for accessibility: " << hdlr.GetPermission(SecurityHandler::e_access_support)
151 << "\n\tAllow document assembly: " << hdlr.GetPermission(SecurityHandler::e_assemble_doc)
152 << endl;
153 */
154 }
155 }
156 catch(Common::Exception& e) {
157 cout << e << endl;
158 ret = 1;
159 }
160 catch(...) {
161 cout << "Unknown Exception" << endl;
162 ret = 1;
163 }
164
165 // An advanced example showing how to work with custom security handlers.
166 // A custom security handler is a class derived from a SecurityHandler.
167
168 // Define a custom security handler used to obtain document password dynamically via user feedback.
169 class MySecurityHandler : public SecurityHandler
170 {
171 public:
172 MySecurityHandler (int key_len, int enc_code) : SecurityHandler("Standard", key_len, enc_code) {}
173 MySecurityHandler (const MySecurityHandler& s) : SecurityHandler(s) {}
174 virtual ~MySecurityHandler() {
175 // cout << "MySecurityHandler Destroy";
176 }
177
178 // In this callback ask the user for password/authorization data.
179 // This may involve a dialog box used to collect authorization data or something else.
180 virtual bool GetAuthorizationData (Permission p)
181 {
182 cout << "The input file requires user password." << endl;
183 cout << "Please enter the password:" << endl;
184
185 string password;
186 cin >> password;
187
188 InitPassword(password.c_str());
189 return true;
190 }
191
192 // This callback could be used to customize security handler preferences.
193 virtual bool EditSecurityData(SDF::SDFDoc& doc) { return false; }
194
195 // This callback is used when authorization process fails.
196 virtual void AuthorizeFailed() { cout << "Authorize failed...." << endl; }
197
198
199 MySecurityHandler(const MySecurityHandler& s, TRN_SecurityHandler base)
200 : SecurityHandler(base, true, s.m_derived_procs)
201 {
202 }
203
204 virtual SecurityHandler* Clone(TRN_SecurityHandler base) const
205 {
206 return new MySecurityHandler(*this, base);
207 }
208
209 // MySecurityHandler's factory method
210 static TRN_SecurityHandler Create(const char* name, int key_len, int enc_code, void* custom_data)
211 {
212 MySecurityHandler* ret = new MySecurityHandler (key_len, enc_code);
213
214 // Explicitly specify which methods are overloaded.
215 ret->SetDerived(
216 has_CloneProc | // Clone - must be implemented in every derived class.
217 has_AuthFailedProc |
218 has_GetAuthDataProc);
219 return (TRN_SecurityHandler) ret->mp_handler;
220 }
221 };
222
223 // Example 3:
224 // Encrypt/Decrypt a PDF using PDFTron custom security handler
225 try
226 {
227 cout << "-------------------------------------------------" << endl;
228 cout << "Encrypt a document using PDFTron Custom Security handler with a custom id and password..." << endl;
229 PDFDoc doc(input_path + "BusinessCardTemplate.pdf");
230
231 // Create PDFTron custom security handler with a custom id. Replace this with your own integer
232 UInt32 custom_id = 123456789;
233 SDF::PDFTronCustomSecurityHandler custom_handler(custom_id);
234
235 // Add a password to the custom security handler
236 const UString pass("test");
237 custom_handler.ChangeUserPassword(pass);
238
239 // Save the encrypted document
240 doc.SetSecurityHandler(custom_handler);
241 doc.Save((output_path + "BusinessCardTemplate_enc.pdf").c_str(), SDFDoc::e_linearized, 0);
242
243 cout << "Decrypt the PDFTron custom security encrypted document above..." << endl;
244 // Register the PDFTron Custom Security handler with the same custom id used in encryption
245 PDFNet::AddPDFTronCustomHandler(custom_id);
246
247 PDFDoc doc_enc(output_path + "BusinessCardTemplate_enc.pdf");
248 doc_enc.InitStdSecurityHandler(pass);
249 doc_enc.RemoveSecurity();
250 // Save the decrypted document
251 doc_enc.Save((output_path + "BusinessCardTemplate_enc_dec.pdf").c_str(), SDFDoc::e_linearized, 0);
252 cout << "Done. Result saved in BusinessCardTemplate_enc_dec.pdf" << endl;
253 }
254 catch (Common::Exception & e) {
255 cout << e << endl;
256 ret = 1;
257 }
258 catch (...) {
259 cout << "Unknown Exception" << endl;
260 ret = 1;
261 }
262
263 // Example 4:
264 // Read a password protected PDF using a custom security handler.
265
266 try
267 {
268 // Register standard security. Required only once per application session.
269 PDFNet::RegisterSecurityHandler("Standard", "Standard Security", MySecurityHandler::Create);
270
271 cout << "-------------------------------------------------" << endl;
272 cout << "Open the password protected document from the first example..." << endl;
273 PDFDoc doc((output_path + "secured.pdf").c_str()); // Open the encrypted document that we saved in the first example.
274
275 cout << "Initializing security handler. The password will now be collected from the user" << endl;
276 cout << "Enter 'test' as the password." << endl;
277
278 // this data is just to show how you can pass your own custom data through InitSecurityHandler
279 void* custom_data = const_cast<char*>("my custom pointer");
280
281 // At this point MySecurityHandler callbacks will be invoked.
282 // MySecurityHandler.GetAuthorizationData() should collect the password and
283 // AuthorizeFailed() is called if user repeatedly enters a wrong password.
284 if (!doc.InitSecurityHandler(custom_data))
285 {
286 cout << "Document authentication error..." << endl;
287 cout << "The password is not valid." << endl;
288 }
289 else
290 {
291 cout << "\nThe password is correct! Document can now be used for reading and editing" << endl;
292
293 // Remove the password security and save the changes to a new file.
294 doc.RemoveSecurity();
295 doc.Save((output_path + "secured_nomore2.pdf").c_str(), 0, NULL);
296 cout << "Done. Result saved in secured_nomore2.pdf" << endl;
297 }
298 }
299 catch(Common::Exception& e) {
300 cout << e << endl;
301 ret = 1;
302 }
303 catch(...) {
304 cout << "Unknown Exception" << endl;
305 ret = 1;
306 }
307
308 cout << "-------------------------------------------------" << endl;
309 cout << "Tests completed." << endl;
310
311 PDFNet::Terminate();
312 return ret;
313}
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//---------------------------------------------------------------------------------------
7// This sample shows encryption support in PDFNet. The sample reads an encrypted document and
8// sets a new SecurityHandler. The sample also illustrates how password protection can
9// be removed from an existing PDF document.
10//---------------------------------------------------------------------------------------
11const { PDFNet } = require('@pdftron/pdfnet-node');
12const PDFTronLicense = require('../LicenseKey/LicenseKey');
13
14((exports) => {
15 exports.runEncTest = () => {
16
17 const main = async () => {
18 let ret = 0;
19 // Relative path to the folder containing test files.
20 const inputPath = '../TestFiles/';
21 const outputPath = inputPath + 'Output/';
22 // Example 1:
23 // secure a PDF document with password protection and adjust permissions
24 try {
25 // Open the test file
26 console.log('-------------------------------------------------/nSecuring an existing document...');
27 const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'fish.pdf');
28 if (!(await doc.initSecurityHandler())) {
29 console.log('Document authentication error...');
30 ret = 1;
31 }
32
33 const performOperation = true; // optional parameter
34
35 // Perform some operation on the document. In this case we use low level SDF API
36 // to replace the content stream of the first page with contents of file 'my_stream.txt'
37 // Results in fish.pdf becoming a pair of feathers.
38 if (performOperation) {
39 console.log('Replacing the content stream, use Flate compression...');
40 // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
41 const pageTrailer = await doc.getTrailer();
42 const pageRoot = await pageTrailer.get('Root');
43 const pageRootValue = await pageRoot.value();
44 const pages = await pageRootValue.get('Pages');
45 const pagesVal = await pages.value();
46 const kids = await pagesVal.get('Kids');
47 const kidsVal = await kids.value();
48 const pageDict = await kidsVal.getAt(0);
49
50 const embedFile = await PDFNet.Filter.createMappedFileFromUString(inputPath + 'my_stream.txt');
51 const mystm = await PDFNet.FilterReader.create(embedFile);
52
53 const flateEncode = await PDFNet.Filter.createFlateEncode();
54
55 const indStream = await doc.createIndirectStreamFromFilter(mystm, flateEncode);
56 await pageDict.put('Contents', indStream);
57 }
58
59 // Encrypt the document
60 // Apply a new security handler with given security settings.
61 // In order to open saved PDF you will need a user password 'test'.
62 const newHandler = await PDFNet.SecurityHandler.createDefault();
63
64 // Set a new password required to open a document
65 newHandler.changeUserPasswordUString('test');
66
67 // Set Permissions
68 newHandler.setPermission(PDFNet.SecurityHandler.Permission.e_print, true);
69 await newHandler.setPermission(PDFNet.SecurityHandler.Permission.e_extract_content, false);
70
71 // Note: document takes the ownership of newHandler.
72 doc.setSecurityHandler(newHandler);
73
74 // Save the changes
75 console.log('Saving modified file...');
76 await doc.save(outputPath + 'secured.pdf', 0);
77 console.log('Done. Result saved in secured.pdf');
78 } catch (err) {
79 console.log(err);
80 console.log(err.stack);
81 ret = 1;
82 }
83
84 // Example 2:
85 // Opens an encrypted PDF document and removes its security.
86 try {
87 console.log('-------------------------------------------------');
88 console.log('Open the password protected document from the first example...');
89 const securedDoc = await PDFNet.PDFDoc.createFromFilePath(outputPath + 'secured.pdf');
90 console.log('Initializing security handler without any user interaction...');
91
92 // At this point MySecurityHandler callbacks will be invoked.
93 // MySecurityHandler.GetAuthorizationData() should collect the password and
94 // AuthorizeFailed() is called if user repeatedly enters a wrong password.
95 if (!(await securedDoc.initStdSecurityHandlerUString('test'))) {
96 console.log('Document authentication error.../nThe password is not valid.');
97 ret = 1;
98 return ret;
99 }
100
101 console.log('The password is correct! Document can now be used for reading and editing');
102
103 // Remove the password security and save the changes to a new file.
104 securedDoc.removeSecurity();
105 await securedDoc.save(outputPath + 'secured_nomore1.pdf', 0);
106 console.log('Done. Result saved in secured_nomore1.pdf');
107
108 /*
109 const hdlr = await securedDoc.getSecurityHandler();
110
111 console.log('Document Open Password: ' + (await hdlr.isUserPasswordRequired()));
112 console.log('Permissions Password: ' + (await hdlr.isMasterPasswordRequired()));
113 console.log('Permissions: ');
114 console.log("\tHas 'owner' permissions: " + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_owner)));
115
116 console.log('\tOpen and decrypt the document: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_doc_open)));
117 console.log('\tAllow content extraction: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_extract_content)));
118 console.log('\tAllow full document editing: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_doc_modify)));
119 console.log('\tAllow printing: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_print)));
120 console.log('\tAllow high resolution printing: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_print_high)));
121 console.log('\tAllow annotation editing: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_mod_annot)));
122 console.log('\tAllow form fill: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_fill_forms)));
123 console.log('\tAllow content extraction for accessibility: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_access_support)));
124 console.log('\tAllow document assembly: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_assemble_doc)));
125 */
126 } catch (err) {
127 console.log(err.stack);
128 ret = 1;
129 }
130
131 // Example 3:
132 // Encrypt/Decrypt a PDF using PDFTron custom security handler
133 try {
134 console.log('-------------------------------------------------');
135 console.log('Encrypt a document using PDFTron Custom Security handler with a custom id and password...');
136 const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + "BusinessCardTemplate.pdf");
137
138 // Create PDFTron custom security handler with a custom id. Replace this with your own integer
139 const custom_id = 123456789;
140 const custom_handler = await PDFNet.PDFTronCustomSecurityHandler.create(custom_id);
141
142 // Add a password to the custom security handler
143 const pass = 'test';
144 await custom_handler.changeUserPasswordUString(pass);
145
146 // Save the encrypted document
147 doc.setSecurityHandler(custom_handler);
148 await doc.save(outputPath + 'BusinessCardTemplate_enc.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
149
150 console.log('Decrypt the PDFTron custom security encrypted document above...');
151 // Register the PDFTron Custom Security handler with the same custom id used in encryption
152 await PDFNet.addPDFTronCustomHandler(custom_id);
153
154 const doc_enc = await PDFNet.PDFDoc.createFromFilePath(outputPath + 'BusinessCardTemplate_enc.pdf');
155 doc_enc.initStdSecurityHandlerUString(pass);
156 doc_enc.removeSecurity();
157 // Save the decrypted document
158 await doc_enc.save(outputPath + 'BusinessCardTemplate_enc_dec.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
159 console.log('Done. Result saved in BusinessCardTemplate_enc_dec.pdf');
160 } catch (err) {
161 console.log(err.stack);
162 ret = 1;
163 }
164
165 console.log('-------------------------------------------------');
166 console.log('Tests completed.');
167
168 return ret;
169 };
170
171 PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function (error) { console.log('Error: ' + JSON.stringify(error)); }).then(function () { return PDFNet.shutdown(); });
172 };
173 exports.runEncTest();
174})(exports);
175// eslint-disable-next-line spaced-comment
176//# sourceURL=EncTest.js
1<?php
2//---------------------------------------------------------------------------------------
3// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
4// Consult LICENSE.txt regarding license information.
5//---------------------------------------------------------------------------------------
6if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
7include("../../../PDFNetC/Lib/PDFNetPHP.php");
8include("../../LicenseKey/PHP/LicenseKey.php");
9
10//---------------------------------------------------------------------------------------
11// This sample shows encryption support in PDFNet. The sample reads an encrypted document and
12// sets a new SecurityHandler. The sample also illustrates how password protection can
13// be removed from an existing PDF document.
14//---------------------------------------------------------------------------------------
15 PDFNet::Initialize($LicenseKey);
16 PDFNet::GetSystemFontList(); // Wait for fonts to be loaded if they haven't already. This is done because PHP can run into errors when shutting down if font loading is still in progress.
17
18 // Relative path to the folder containing the test files.
19 $input_path = getcwd()."/../../TestFiles/";
20 $output_path = $input_path."Output/";
21
22 // Example 1:
23 // secure a PDF document with password protection and adjust permissions
24
25 // Open the test file
26 echo "Securing an existing document ...\n";
27 $doc = new PDFDoc($input_path."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 (true) // Optional
33 {
34 echo "Replacing the content stream, use Flate compression...\n";
35
36 // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
37 $page_dict = $doc->GetTrailer()->Get("Root")->Value()
38 ->Get("Pages")->Value()
39 ->Get("Kids")->Value()
40 ->GetAt(0);
41
42 // Embed a custom stream (file mystream.txt) using Flate compression.
43 $embed_file = new MappedFile($input_path."my_stream.txt");
44 $mystm = new FilterReader($embed_file);
45 $page_dict->Put("Contents", $doc->CreateIndirectStream($mystm, new FlateEncode(new Filter())));
46 }
47
48 //encrypt the document
49
50 // Apply a new security handler with given security settings.
51 // In order to open saved PDF you will need a user password 'test'.
52 $new_handler = new SecurityHandler();
53
54 // Set a new password required to open a document
55 $user_password="test";
56 $new_handler->ChangeUserPassword($user_password);
57
58 // Set Permissions
59 $new_handler->SetPermission (SecurityHandler::e_print, true);
60 $new_handler->SetPermission (SecurityHandler::e_extract_content, false);
61
62 // Note: document takes the ownership of new_handler.
63 $doc->SetSecurityHandler($new_handler);
64
65 // Save the changes.
66 echo "Saving modified file...\n";
67 $doc->Save($output_path."secured.pdf", 0);
68 $doc->Close();
69
70 // Example 2:
71 // Opens an encrypted PDF document and removes its security.
72
73 $doc = new PDFDoc($output_path."secured.pdf");
74
75 //If the document is encrypted prompt for the password
76 if (!$doc->InitSecurityHandler())
77 {
78 $success=false;
79 echo "The password is: test\n";
80 for($count=0; $count<3;$count++)
81 {
82 echo "A password required to open the document.\n"
83 ."Please enter the password:";
84
85 $password = trim(fgets(STDIN));
86 if($doc->InitStdSecurityHandler($password, strlen($password)))
87 {
88 $success=true;
89 echo "The password is correct.\n";
90 break;
91 }
92 else if($count<3)
93 {
94 echo "The password is incorrect, please try again\n";
95 }
96 }
97 if(!$success)
98 {
99 echo "Document authentication error....\n";
100 PDFNet::Terminate();
101 return;
102 }
103
104 $hdlr = $doc->GetSecurityHandler();
105 echo "Document Open Password: ".$hdlr->IsUserPasswordRequired()."\n";
106 echo "Permissions Password: ".$hdlr->IsMasterPasswordRequired()."\n";
107 echo "Permissions: "
108 ."\n\tHas 'owner' permissions: ".$hdlr->GetPermission(SecurityHandler::e_owner)
109 ."\n\tOpen and decrypt the document: ".$hdlr->GetPermission(SecurityHandler::e_doc_open)
110 ."\n\tAllow content extraction: ".$hdlr->GetPermission(SecurityHandler::e_extract_content)
111 ."\n\tAllow full document editing: ".$hdlr->GetPermission(SecurityHandler::e_doc_modify)
112 ."\n\tAllow printing: ".$hdlr->GetPermission(SecurityHandler::e_print)
113 ."\n\tAllow high resolution printing: ".$hdlr->GetPermission(SecurityHandler::e_print_high)
114 ."\n\tAllow annotation editing: ".$hdlr->GetPermission(SecurityHandler::e_mod_annot)
115 ."\n\tAllow form fill: ".$hdlr->GetPermission(SecurityHandler::e_fill_forms)
116 ."\n\tAllow content extraction for accessibility: ".$hdlr->GetPermission(SecurityHandler::e_access_support)
117 ."\n\tAllow document assembly: ".$hdlr->GetPermission(SecurityHandler::e_assemble_doc)
118 ."\n";
119 }
120
121 // remove all security on the document
122 $doc->RemoveSecurity();
123 $doc->Save($output_path."not_secured.pdf", 0);
124 $doc->Close();
125
126 // Example 3:
127 echo "-------------------------------------------------\n";
128 echo "Encrypt a document using PDFTron Custom Security handler with a custom id and password...\n";
129 $doc = new PDFDoc($input_path . "BusinessCardTemplate.pdf");
130
131 // Create PDFTron custom security handler with a custom id. Replace this with your own integer
132 $custom_id = 123456789;
133 $custom_handler = new PDFTronCustomSecurityHandler($custom_id);
134
135 // Add a password to the custom security handler
136 $pass = "test";
137 $custom_handler->ChangeUserPassword($pass);
138
139 // Save the encrypted document
140 $doc->SetSecurityHandler($custom_handler);
141 $doc->Save($output_path . "BusinessCardTemplate_enc.pdf", 0);
142 $doc->Close();
143
144 echo "Decrypt the PDFTron custom security encrypted document above...\n";
145 // Register the PDFTron Custom Security handler with the same custom id used in encryption
146 PDFNet::AddPDFTronCustomHandler($custom_id);
147
148 $doc_enc = new PDFDoc($output_path . "BusinessCardTemplate_enc.pdf");
149 $doc_enc->InitStdSecurityHandler($pass);
150 $doc_enc->RemoveSecurity();
151 // Save the decrypted document
152 $doc_enc->Save($output_path . "BusinessCardTemplate_enc_dec.pdf", 0);
153 $doc->Close();
154 PDFNet::Terminate();
155 echo "Done. Result saved in BusinessCardTemplate_enc_dec.pdf\n";
156 echo "-------------------------------------------------\n";
157 echo "Test Completed.\n";
158?>
1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6import site
7site.addsitedir("../../../PDFNetC/Lib")
8import sys
9from PDFNetPython import *
10
11sys.path.append("../../LicenseKey/PYTHON")
12from LicenseKey import *
13
14#---------------------------------------------------------------------------------------
15# This sample shows encryption support in PDFNet. The sample reads an encrypted document and
16# sets a new SecurityHandler. The sample also illustrates how password protection can
17# be removed from an existing PDF document.
18#---------------------------------------------------------------------------------------
19
20def main():
21 PDFNet.Initialize(LicenseKey)
22
23 # Relative path to the folder containing the test files.
24 input_path = "../../TestFiles/"
25 output_path = "../../TestFiles/Output/"
26
27 # Example 1:
28 # secure a PDF document with password protection and adjust permissions
29
30 # Open the test file
31 print("Securing an existing document...")
32
33 doc = PDFDoc(input_path + "fish.pdf")
34 doc.InitSecurityHandler()
35
36 # Perform some operation on the document. In this case we use low level SDF API
37 # to replace the content stream of the first page with contents of file 'my_stream.txt'
38 if True: # Optional
39 print("Replacing the content stream, use Flate compression...")
40
41 # Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
42 page_dict = (doc.GetTrailer().Get("Root").Value()
43 .Get("Pages").Value()
44 .Get("Kids").Value()
45 .GetAt(0))
46
47 # Embed a custom stream (file mystream.txt) using Flate compression.
48 embed_file = MappedFile(input_path + "my_stream.txt")
49 mystm = FilterReader(embed_file)
50 page_dict.Put("Contents", doc.CreateIndirectStream(mystm, FlateEncode(Filter())))
51
52 # encrypt the document
53
54 # Apply a new security handler with given security settings.
55 # In order to open saved PDF you will need a user password 'test'.
56 new_handler = SecurityHandler()
57
58 # Set a new password required to open a document
59 user_password = "test"
60 new_handler.ChangeUserPassword(user_password)
61
62 # Set permissions
63 new_handler.SetPermission(SecurityHandler.e_print, True)
64 new_handler.SetPermission(SecurityHandler.e_extract_content, False)
65
66 # Note: document takes the ownership of new_handler.
67 doc.SetSecurityHandler(new_handler)
68
69 # save the changes.
70 print("Saving modified file...")
71 doc.Save(output_path + "secured.pdf", 0)
72 doc.Close()
73
74 # Example 2:
75 # Opens an encrypted PDF document and removes its security.
76
77 doc = PDFDoc(output_path + "secured.pdf")
78
79 # If the document is encrypted prompt for the password
80 if not doc.InitSecurityHandler():
81 success = False
82 print("The password is: test")
83 count = 0
84 while count < 3:
85 print("A password required to open the document.")
86 if sys.version_info.major >= 3:
87 password = input("Please enter the password: \n")
88 else:
89 password = raw_input("Please enter the password: \n")
90
91 if doc.InitStdSecurityHandler(password, len(password)):
92 success = True
93 print("The password is correct.")
94 break
95 elif count < 3:
96 print("The password is incorrect, please try again")
97 count = count + 1
98
99 if not success:
100 print("Document authentication error....")
101 return
102
103 hdlr = doc.GetSecurityHandler()
104 print("Document Open Password: " + str(hdlr.IsUserPasswordRequired()))
105 print("Permissions Password: " + str(hdlr.IsMasterPasswordRequired()))
106 print(("Permissions: "
107 + "\n\tHas 'owner' permissions: " + str(hdlr.GetPermission(SecurityHandler.e_owner))
108 + "\n\tOpen and decrypt the document: " + str(hdlr.GetPermission(SecurityHandler.e_doc_open))
109 + "\n\tAllow content extraction: " + str(hdlr.GetPermission(SecurityHandler.e_extract_content))
110 + "\n\tAllow full document editing: " + str(hdlr.GetPermission(SecurityHandler.e_doc_modify) )
111 + "\n\tAllow printing: " + str(hdlr.GetPermission(SecurityHandler.e_print))
112 + "\n\tAllow high resolution printing: " + str(hdlr.GetPermission(SecurityHandler.e_print_high))
113 + "\n\tAllow annotation editing: " + str(hdlr.GetPermission(SecurityHandler.e_mod_annot))
114 + "\n\tAllow form fill: " + str(hdlr.GetPermission(SecurityHandler.e_fill_forms))
115 + "\n\tAllow content extraction for accessibility: " + str(hdlr.GetPermission(SecurityHandler.e_access_support))
116 + "\n\tAllow document assembly: " + str(hdlr.GetPermission(SecurityHandler.e_assemble_doc))))
117
118 # remove all security on the document
119 doc.RemoveSecurity()
120 doc.Save(output_path + "not_secured.pdf", 0)
121 doc.Close()
122
123 # Example 3:
124 # Encrypt/Decrypt a PDF using PDFTron custom security handler
125 print("-------------------------------------------------")
126 print("Encrypt a document using PDFTron Custom Security handler with a custom id and password...")
127 doc = PDFDoc(input_path + "BusinessCardTemplate.pdf")
128
129 # Create PDFTron custom security handler with a custom id. Replace this with your own integer
130 custom_id = 123456789
131 custom_handler = PDFTronCustomSecurityHandler(custom_id)
132
133 # Add a password to the custom security handler
134 password = "test"
135 custom_handler.ChangeUserPassword(password)
136
137 # Save the encrypted document
138 doc.SetSecurityHandler(custom_handler)
139 doc.Save(output_path + "BusinessCardTemplate_enc.pdf", 0)
140 doc.Close()
141
142 print("Decrypt the PDFTron custom security encrypted document above...")
143 # Register the PDFTron Custom Security handler with the same custom id used in encryption
144 PDFNet.AddPDFTronCustomHandler(custom_id)
145
146 doc_enc = PDFDoc(output_path + "BusinessCardTemplate_enc.pdf")
147 doc_enc.InitStdSecurityHandler(password)
148 doc_enc.RemoveSecurity()
149 # Save the decrypted document
150 doc_enc.Save(output_path + "BusinessCardTemplate_enc_dec.pdf", 0)
151 doc_enc.Close()
152 PDFNet.Terminate()
153 print("Done. Result saved in BusinessCardTemplate_enc_dec.pdf")
154 print("-------------------------------------------------");
155 print("Test completed.")
156
157if __name__ == '__main__':
158 main()
1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6require '../../../PDFNetC/Lib/PDFNetRuby'
7include PDFNetRuby
8require '../../LicenseKey/RUBY/LicenseKey'
9
10$stdout.sync = true
11
12#---------------------------------------------------------------------------------------
13# This sample shows encryption support in PDFNet. The sample reads an encrypted document and
14# sets a new SecurityHandler. The sample also illustrates how password protection can
15# be removed from an existing PDF document.
16#---------------------------------------------------------------------------------------
17
18 PDFNet.Initialize(PDFTronLicense.Key)
19
20 # Relative path to the folder containing the test files.
21 input_path = "../../TestFiles/"
22 output_path = "../../TestFiles/Output/"
23
24 # Example 1:
25 # secure a PDF document with password protection and adjust permissions
26
27 # Open the test file
28 puts "Securing an existing document..."
29
30 doc = PDFDoc.new(input_path + "fish.pdf")
31 doc.InitSecurityHandler()
32
33 # Perform some operation on the document. In this case we use low level SDF API
34 # to replace the content stream of the first page with contents of file 'my_stream.txt'
35 if true # Optional
36 puts "Replacing the content stream, use Flate compression..."
37
38 # Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
39 page_dict = (doc.GetTrailer().Get("Root").Value()
40 .Get("Pages").Value()
41 .Get("Kids").Value()
42 .GetAt(0))
43
44 # Embed a custom stream (file mystream.txt) using Flate compression.
45 embed_file = MappedFile.new(input_path + "my_stream.txt")
46 mystm = FilterReader.new(embed_file)
47 page_dict.Put("Contents", doc.CreateIndirectStream(mystm, FlateEncode.new(Filter.new())))
48 end
49
50 # encrypt the document
51
52 # Apply a new security handler with given security settings.
53 # In order to open saved PDF you will need a user password 'test'.
54 new_handler = SecurityHandler.new()
55
56 # Set a new password required to open a document
57 user_password = "test"
58 new_handler.ChangeUserPassword(user_password)
59
60 # Set permissions
61 new_handler.SetPermission(SecurityHandler::E_print, true)
62 new_handler.SetPermission(SecurityHandler::E_extract_content, false)
63
64 # Note: document takes the ownership of new_handler.
65 doc.SetSecurityHandler(new_handler)
66
67 # save the changes.
68 puts "Saving modified file..."
69 doc.Save(output_path + "secured.pdf", 0)
70 doc.Close()
71
72 # Example 2:
73 # Opens an encrypted PDF document and removes its security.
74
75 doc = PDFDoc.new(output_path + "secured.pdf")
76
77 # If the document is encrypted prompt for the password
78 if !doc.InitSecurityHandler()
79 success = false
80 puts "The password is: test"
81 count = 0
82 while count < 3 do
83 puts "A password required to open the document."
84 puts "Please enter the password:"
85 password = gets.chomp
86 if doc.InitStdSecurityHandler(password, password.length)
87 success = true
88 puts "The password is correct."
89 break
90 elsif count < 3
91 puts "The password is incorrect, please try again"
92 end
93 count = count + 1
94 end
95
96 if !success
97 puts "Document authentication error...."
98 return
99 end
100
101 hdlr = doc.GetSecurityHandler()
102 puts "Document Open Password: " + hdlr.IsUserPasswordRequired().to_s()
103 puts "Permissions Password: " + hdlr.IsMasterPasswordRequired().to_s()
104 puts ("Permissions: " +
105 "\n\tHas 'owner' permissions: " + hdlr.GetPermission(SecurityHandler::E_owner).to_s() +
106 "\n\tOpen and decrypt the document: " + hdlr.GetPermission(SecurityHandler::E_doc_open).to_s() +
107 "\n\tAllow content extraction: " + hdlr.GetPermission(SecurityHandler::E_extract_content).to_s() +
108 "\n\tAllow full document editing: " + hdlr.GetPermission(SecurityHandler::E_doc_modify).to_s() +
109 "\n\tAllow printing: " + hdlr.GetPermission(SecurityHandler::E_print).to_s() +
110 "\n\tAllow high resolution printing: " + hdlr.GetPermission(SecurityHandler::E_print_high).to_s() +
111 "\n\tAllow annotation editing: " + hdlr.GetPermission(SecurityHandler::E_mod_annot).to_s() +
112 "\n\tAllow form fill: " + hdlr.GetPermission(SecurityHandler::E_fill_forms).to_s() +
113 "\n\tAllow content extraction for accessibility: " + hdlr.GetPermission(SecurityHandler::E_access_support).to_s() +
114 "\n\tAllow document assembly: " + hdlr.GetPermission(SecurityHandler::E_assemble_doc).to_s())
115 end
116
117 # remove all security on the document
118 doc.RemoveSecurity()
119 doc.Save(output_path + "not_secured.pdf", 0)
120 doc.Close()
121
122 # Example 3:
123 # Encrypt/Decrypt a PDF using PDFTron custom security handler
124 puts "-------------------------------------------------"
125 puts "Encrypt a document using PDFTron Custom Security handler with a custom id and password..."
126 doc = PDFDoc.new(input_path + "BusinessCardTemplate.pdf")
127
128 # Create PDFTron custom security handler with a custom id. Replace this with your own integer
129 custom_id = 123456789
130 custom_handler = PDFTronCustomSecurityHandler.new(custom_id)
131
132 # Add a password to the custom security handler
133 password = "test"
134 custom_handler.ChangeUserPassword(password)
135
136 # Save the encrypted document
137 doc.SetSecurityHandler(custom_handler)
138 doc.Save(output_path + "BusinessCardTemplate_enc.pdf", 0)
139 doc.Close()
140
141 puts "Decrypt the PDFTron custom security encrypted document above..."
142 # Register the PDFTron Custom Security handler with the same custom id used in encryption
143 PDFNet.AddPDFTronCustomHandler(custom_id)
144
145 doc_enc = PDFDoc.new(output_path + "BusinessCardTemplate_enc.pdf")
146 doc_enc.InitStdSecurityHandler(password)
147 doc_enc.RemoveSecurity()
148 # Save the decrypted document
149 doc_enc.Save(output_path + "BusinessCardTemplate_enc_dec.pdf", 0)
150 doc_enc.Close()
151 PDFNet.Terminate
152 puts "Done. Result saved in BusinessCardTemplate_enc_dec.pdf"
153 puts "-------------------------------------------------"
154 puts "Test completed."
1'---------------------------------------------------------------------------------------
2' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3' Consult legal.txt regarding legal and license information.
4'---------------------------------------------------------------------------------------
5Imports System
6
7Imports pdftron
8Imports pdftron.Common
9Imports pdftron.Filters
10Imports pdftron.SDF
11Imports pdftron.PDF
12
13'---------------------------------------------------------------------------------------
14' This sample shows encryption support in PDFNet. The sample reads an encrypted document and
15' sets a new SecurityHandler. The sample also illustrates how password protection can
16' be removed from an existing PDF document.
17'---------------------------------------------------------------------------------------
18Module EncTestVB
19 Dim pdfNetLoader As PDFNetLoader
20 Sub New()
21 pdfNetLoader = pdftron.PDFNetLoader.Instance()
22 End Sub
23
24 ' A custom security handler used to obtain document password dynamically via user feedback.
25 Public Class MySecurityHandler
26 Inherits StdSecurityHandler
27
28 Sub New(ByVal key_len As Int32, ByVal enc_code As Int32)
29 MyBase.New(key_len, enc_code)
30 End Sub
31
32 Sub New(ByVal s As MySecurityHandler)
33 MyBase.New(s)
34 End Sub
35
36 ' In this callback ask the user for password/authorization data.
37 ' This may invlove a dialog box used to collect authorization data or something else.
38 Public Overrides Function GetAuthorizationData(ByVal p As SecurityHandler.Permission) As Boolean
39 Console.WriteLine("The input file requires user password.")
40 Console.WriteLine("Please enter the password:")
41 Dim pass As String = Console.ReadLine()
42 InitPassword(pass)
43 Return True
44 End Function
45
46 ' This callback could be used to customize security handler preferences.
47 Public Overloads Function EditSecurityData(ByVal doc As SDFDoc) As Boolean
48 Return False
49 End Function
50
51 ' This callback is used when authorization process fails.
52 Public Overloads Sub AuthorizeFailed()
53 Console.WriteLine("Authorize failed...")
54 End Sub
55
56 Public Shared Function Create(ByVal name As String, ByVal key_len As Int32, ByVal enc_code As Int32) As SecurityHandler
57 Return New MySecurityHandler(key_len, enc_code)
58 End Function
59
60 Public Overloads Function Clone() As SecurityHandler
61 Return New MySecurityHandler(Me)
62 End Function
63
64 End Class
65
66
67 Sub Main()
68
69 PDFNet.Initialize(PDFTronLicense.Key)
70
71 ' Relative path to the folder containing test files.
72 Dim input_path As String = "../../../../TestFiles/"
73 Dim output_path As String = "../../../../TestFiles/Output/"
74
75 ' Example 1: Securing a document with password protection and adjusting permissions
76 ' on the document.
77 Try
78 ' Open the test file
79 Console.WriteLine("-------------------------------------------------")
80 Console.WriteLine("Securing an existing document...")
81 Using doc As PDFDoc = New PDFDoc(input_path + "fish.pdf")
82 If Not doc.InitSecurityHandler() Then
83 Console.WriteLine("Document authentication error...")
84 Return
85 End If
86
87 ' Perform some operation on the document. In this case we use low level SDF API
88 ' to replace the content stream of the first page with contents of file 'my_stream.txt'
89 If (True) Then ' Optional
90 Console.WriteLine("Replacing the content stream, use flate compression...")
91
92 ' Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
93 Dim page_dict As Obj = doc.GetTrailer().Get("Root").Value(). _
94 Get("Pages").Value(). _
95 Get("Kids").Value(). _
96 GetAt(0)
97
98 ' Embed a custom stream (file mystream.txt) using Flate compression.
99 Dim embed_file As MappedFile = New MappedFile(input_path + "my_stream.txt")
100 Dim mystm As FilterReader = New FilterReader(embed_file)
101 page_dict.Put("Contents", doc.CreateIndirectStream(mystm))
102 embed_file.Close()
103 End If
104
105 ' Apply a new security handler with given security settings.
106 ' In order to open saved PDF you will need a user password 'test'.
107 Dim new_handler As StdSecurityHandler = New StdSecurityHandler
108
109 ' Set a new password required to open a document
110 Dim my_password As String = "test"
111 new_handler.ChangeUserPassword(my_password)
112
113 ' Set Permissions
114 new_handler.SetPermission(SecurityHandler.Permission.e_print, True)
115 new_handler.SetPermission(SecurityHandler.Permission.e_extract_content, False)
116
117 ' Note: document takes the ownership of new_handler.
118 doc.SetSecurityHandler(new_handler)
119
120 ' Save the changes.
121 Console.WriteLine("Saving modified file...")
122 doc.Save(output_path + "secured.pdf", 0)
123 End Using
124 Console.WriteLine("Done. Result saved in secured.pdf...")
125 Catch e As PDFNetException
126 Console.WriteLine(e.Message)
127 End Try
128
129 ' Example 2: Reading password protected document without user feedback.
130 Try
131 ' In this sample case we will open an encrypted document that
132 ' requires a user password in order to access the content.
133 Console.WriteLine("-------------------------------------------------")
134 Console.WriteLine("Open the password protected document from the first example...")
135 Using doc As PDFDoc = New PDFDoc(output_path + "secured.pdf") ' Open the encrypted document that we saved in the first example.
136 Console.WriteLine("Initializing security handler without any user interaction...")
137
138 ' At this point MySecurityHandler callbacks will be invoked.
139 ' MySecurityHandler.GetAuthorizationData() should collect the password and
140 ' AuthorizeFailed() is called if user repeatedly enters a wrong password.
141 If Not doc.InitStdSecurityHandler("test") Then
142 Console.WriteLine("Document authentication error...")
143 Console.WriteLine("The password is not valid.")
144 Return
145 Else
146 Console.WriteLine("The password is correct! Document can now be used for reading and editing")
147
148 ' Remove the password security and save the changes to a new file.
149 doc.SetSecurityHandler(Nothing)
150 doc.Save(output_path + "secured_nomore1.pdf", 0)
151 Console.WriteLine("Done. Result saved in secured_nomore1.pdf")
152 End If
153 End Using
154 Catch e As PDFNetException
155 Console.WriteLine(e.Message)
156 End Try
157
158 ' Example 3:
159 ' Encrypt/Decrypt a PDF using PDFTron custom security handler
160 Try
161 Console.WriteLine("-------------------------------------------------")
162 Console.WriteLine("Encrypt a document using PDFTron Custom Security handler with a custom id and password...")
163 Dim doc As PDFDoc = New PDFDoc(input_path & "BusinessCardTemplate.pdf")
164
165 ' Create PDFTron custom security handler with a custom id. Replace this with your own integer
166 Dim custom_id As Integer = 123456789
167 Dim custom_handler As PDFTronCustomSecurityHandler = New PDFTronCustomSecurityHandler(custom_id)
168 ' Add a password to the custom security handler
169 Dim pass As String = "test"
170 custom_handler.ChangeUserPassword(pass)
171 ' Save the encrypted document
172 doc.SetSecurityHandler(custom_handler)
173 doc.Save(output_path & "BusinessCardTemplate_enc.pdf", 0)
174 Console.WriteLine("Decrypt the PDFTron custom security encrypted document above...")
175 ' Register the PDFTron Custom Security handler with the same custom id used in encryption
176 PDFNet.AddPDFTronCustomHandler(custom_id)
177 Dim doc_enc As PDFDoc = New PDFDoc(output_path & "BusinessCardTemplate_enc.pdf")
178 doc_enc.InitStdSecurityHandler(pass)
179 doc_enc.RemoveSecurity()
180 ' Save the decrypted document
181 doc_enc.Save(output_path & "BusinessCardTemplate_enc_dec.pdf", 0)
182 Console.WriteLine("Done. Result saved in BusinessCardTemplate_enc_dec.pdf")
183 Catch e As PDFNetException
184 Console.WriteLine(e.Message)
185 End Try
186
187 ' Example 4: Reading password protected document with user feedback.
188 Try
189 ' Register standard security. Reguired only once per application session.
190 Dim del As CreateDelegate = New CreateDelegate(AddressOf MySecurityHandler.Create)
191 SecurityManagerSingleton.Instance().RegisterSecurityHandler("Standard", _
192 New SecurityDescriptor("Standard Security", del))
193
194 Console.WriteLine("-------------------------------------------------")
195 Console.WriteLine("Open the password protected document from the first example...")
196 Using doc As PDFDoc = New PDFDoc(output_path + "secured.pdf") ' Open the encrypted document that we saved in the first example.
197 Console.WriteLine("Initializing security handler. The password will now be collected from the user")
198 Console.WriteLine("Enter 'test' as the password.")
199
200 ' At this point MySecurityHandler callbacks will be invoked.
201 ' MySecurityHandler.GetAuthorizationData() should collect the password and
202 ' AuthorizeFailed() is called if user repeatedly enters a wrong password.
203 If Not doc.InitSecurityHandler() Then
204 Console.WriteLine("Document authentication error...")
205 Console.WriteLine("The password is not valid.")
206 Return
207 Else
208 Console.WriteLine("The password is correct! Document can now be used for reading and editing")
209
210 ' Remove the password security and save the changes to a new file.
211 doc.SetSecurityHandler(Nothing)
212 doc.Save(output_path + "secured_nomore2.pdf", 0)
213 Console.WriteLine("Done. Result saved in secured_nomore2.pdf")
214 End If
215 End Using
216 Catch e As PDFNetException
217 Console.WriteLine(e.Message)
218 End Try
219 PDFNet.Terminate()
220 Console.WriteLine("-------------------------------------------------")
221 Console.WriteLine("Tests completed.")
222 End Sub
223End Module
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales