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 Xamarin SDK.
1//
2// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
3//
4
5using System;
6using pdftron;
7using pdftron.Common;
8using pdftron.Filters;
9using pdftron.SDF;
10using pdftron.PDF;
11
12using NUnit.Framework;
13
14namespace MiscellaneousSamples
15{
16 // A custom security handler used to obtain document password dynamically via user feedback.
17 /// <summary>
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 //---------------------------------------------------------------------------------------
23 /// </summary>
24 [TestFixture]
25 public class EncTest
26 {
27
28 [Test]
29 public static void Sample()
30 {
31
32 // Relative path to the folder containing test files.
33 const string input_path = "TestFiles/";
34
35 // Example 1: Securing a document with password protection and adjusting permissions
36 // on the document.
37 try
38 {
39 // Open the test file
40 Console.WriteLine("-------------------------------------------------");
41 Console.WriteLine("Securing an existing document...");
42 using (PDFDoc doc = new PDFDoc(Utils.GetAssetTempFile(input_path + "fish.pdf")))
43 {
44
45 if (!doc.InitSecurityHandler())
46 {
47 Console.WriteLine("Document authentication error...");
48 return;
49 }
50
51 // Perform some operation on the document. In this case we use low level SDF API
52 // to replace the content stream of the first page with contents of file 'my_stream.txt'
53 if (true) // Optional
54 {
55 Console.WriteLine("Replacing the content stream, use flate compression...");
56
57 // Get the first page dictionary using the following path: trailer/Root/Pages/Kids/0
58 Obj page_dict = doc.GetTrailer().Get("Root").Value().
59 Get("Pages").Value().Get("Kids").Value().GetAt(0);
60
61 // Embed a custom stream (file mystream.txt) using Flate compression.
62 MappedFile embed_file = new MappedFile(Utils.GetAssetTempFile(input_path + "my_stream.txt"));
63 FilterReader mystm = new FilterReader(embed_file);
64 page_dict.Put("Contents", doc.CreateIndirectStream(mystm));
65 embed_file.Close();
66 }
67
68 // Apply a new security handler with given security settings.
69 // In order to open saved PDF you will need a user password 'test'.
70 SecurityHandler new_handler = new SecurityHandler();
71 // Set a new password required to open a document
72 string my_password = "test";
73 new_handler.ChangeUserPassword(my_password);
74
75 // Set Permissions
76 new_handler.SetPermission (SecurityHandler.Permission.e_print, true);
77 new_handler.SetPermission (SecurityHandler.Permission.e_extract_content, false);
78
79 // Note: document takes the ownership of new_handler.
80 doc.SetSecurityHandler(new_handler);
81
82 // Save the changes.
83 Console.WriteLine("Saving modified file...");
84 doc.Save(Utils.CreateExternalFile("secured.pdf"), 0);
85 }
86
87 Console.WriteLine("Done. Result saved in secured.pdf");
88 }
89 catch (PDFNetException e)
90 {
91 Console.WriteLine(e.Message);
92 Assert.True(false);
93 }
94
95 // Example 2: Reading password protected document without user feedback.
96 try
97 {
98 // In this sample case we will open an encrypted document that
99 // requires a user password in order to access the content.
100 Console.WriteLine("-------------------------------------------------");
101 Console.WriteLine("Open the password protected document from the first example...");
102 using (PDFDoc doc = new PDFDoc(Utils.CreateExternalFile("secured.pdf"))) // Open the encrypted document that we saved in the first example.
103 {
104
105 Console.WriteLine("Initializing security handler without any user interaction...");
106
107 // At this point MySecurityHandler callbacks will be invoked.
108 // MySecurityHandler.GetAuthorizationData() should collect the password and
109 // AuthorizeFailed() is called if user repeatedly enters a wrong password.
110 if (!doc.InitStdSecurityHandler("test"))
111 {
112 Console.WriteLine("Document authentication error...");
113 Console.WriteLine("The password is not valid.");
114 return;
115 }
116 else
117 {
118 Console.WriteLine("The password is correct! Document can now be used for reading and editing");
119
120 // Remove the password security and save the changes to a new file.
121 doc.RemoveSecurity();
122 doc.Save(Utils.CreateExternalFile("secured_nomore1.pdf"), 0);
123 Console.WriteLine("Done. Result saved in secured_nomore1.pdf");
124 }
125
126 }
127 }
128 catch (PDFNetException e)
129 {
130 Console.WriteLine(e.Message);
131 Assert.True(false);
132 }
133
134 Console.WriteLine("Tests completed.");
135
136 }
137 }
138}
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales