Sample Java code for using Apryse SDK to read encrypted (password protected) documents, secure a document with encryption, or remove encryption. Learn more about our Android SDK.
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6package com.pdftron.android.pdfnetsdksamples.samples;
7
8import com.pdftron.android.pdfnetsdksamples.OutputListener;
9import com.pdftron.android.pdfnetsdksamples.PDFNetSample;
10import com.pdftron.android.pdfnetsdksamples.R;
11import com.pdftron.android.pdfnetsdksamples.util.Utils;
12import com.pdftron.common.PDFNetException;
13import com.pdftron.filters.FilterReader;
14import com.pdftron.filters.FlateEncode;
15import com.pdftron.filters.MappedFile;
16import com.pdftron.pdf.PDFDoc;
17import com.pdftron.pdf.PDFNet;
18import com.pdftron.sdf.Obj;
19import com.pdftron.sdf.PDFTronCustomSecurityHandler;
20import com.pdftron.sdf.SDFDoc;
21import com.pdftron.sdf.SecurityHandler;
22
23import java.io.BufferedReader;
24import java.io.InputStreamReader;
25import java.util.ArrayList;
26
27public class EncTest extends PDFNetSample {
28
29	private static OutputListener mOutputListener;
30
31	private static ArrayList<String> mFileList = new ArrayList<>();
32
33    public EncTest() {
34        setTitle(R.string.sample_encryption_title);
35        setDescription(R.string.sample_encryption_description);
36    }
37
38	@Override
39	public void run(OutputListener outputListener) {
40		super.run(outputListener);
41		mOutputListener = outputListener;
42		mFileList.clear();
43		printHeader(outputListener);
44
45        // Example 1:
46        // secure a document with password protection and
47        // adjust permissions
48
49        // Open the test file
50        mOutputListener.println("Securing an existing document ...");
51        try (PDFDoc doc = new PDFDoc((Utils.getAssetTempFile(INPUT_PATH + "fish.pdf").getAbsolutePath()))) {
52            doc.initSecurityHandler();
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                mOutputListener.println("Replacing the content stream, use flate compression...");
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 = new MappedFile((Utils.getAssetTempFile(INPUT_PATH + "my_stream.txt").getAbsolutePath()));
68                FilterReader mystm = new FilterReader(embed_file);
69                page_dict.put("Contents",
70                        doc.createIndirectStream(mystm,
71                                new FlateEncode(null)));
72            }
73
74            //encrypt the document
75
76            // Apply a new security handler with given security settings.
77            // In order to open saved PDF you will need a user password 'test'.
78            SecurityHandler new_handler = new SecurityHandler();
79
80            // Set a new password required to open a document
81            String user_password = "test";
82            new_handler.changeUserPassword(user_password);
83
84            // Set Permissions
85            new_handler.setPermission(SecurityHandler.e_print, true);
86            new_handler.setPermission(SecurityHandler.e_extract_content, false);
87
88            // Note: document takes the ownership of new_handler.
89            doc.setSecurityHandler(new_handler);
90
91            // Save the changes.
92            mOutputListener.println("Saving modified file...");
93            doc.save((Utils.createExternalFile("secured.pdf", mFileList).getAbsolutePath()), SDFDoc.SaveMode.NO_FLAGS, null);
94        } catch (PDFNetException e) {
95            mOutputListener.printError(e.getStackTrace());
96        }
97
98        // Example 2:
99        // Opens the encrypted document and removes all of
100        // its security.
101        try (PDFDoc doc = new PDFDoc((Utils.createExternalFile("secured.pdf", mFileList).getAbsolutePath()))) {
102            //If the document is encrypted prompt for the password
103            if (!doc.initSecurityHandler()) {
104                boolean success = false;
105                mOutputListener.println("The password is: test");
106                for (int count = 0; count < 3; count++) {
107                    BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
108                    mOutputListener.println("A password required to open the document.");
109                    mOutputListener.print("Please enter the password: ");
110                    // String password = r.readLine();
111                    if (doc.initStdSecurityHandler("test")) {
112                        success = true;
113                        mOutputListener.println("The password is correct.");
114                        break;
115                    } else if (count < 3) {
116                        mOutputListener.println("The password is incorrect, please try again");
117                    }
118                }
119                if (!success) {
120                    mOutputListener.println("Document authentication error....");
121                }
122            }
123
124            //remove all security on the document
125            doc.removeSecurity();
126            doc.save(Utils.createExternalFile("not_secured.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.NO_FLAGS, null);
127        } catch (Exception e) {
128            mOutputListener.printError(e.getStackTrace());
129        }
130
131        // Example 3:
132        // Encrypt/Decrypt a PDF using PDFTron custom security handler
133        mOutputListener.println("-------------------------------------------------");
134        mOutputListener.println("Encrypt a document using PDFTron Custom Security handler with a custom id and password...");
135        try (PDFDoc doc = new PDFDoc(Utils.getAssetTempFile(INPUT_PATH + "BusinessCardTemplate.pdf").getAbsolutePath()))
136        {   
137            // Create PDFTron custom security handler with a custom id. Replace this with your own integer
138            int custom_id = 123456789;
139            PDFTronCustomSecurityHandler custom_handler = new PDFTronCustomSecurityHandler(custom_id);
140
141            // Add a password to the custom security handler
142            String pass = "test";
143            custom_handler.changeUserPassword(pass);
144
145            // Save the encrypted document
146            doc.setSecurityHandler(custom_handler);
147            doc.save(Utils.createExternalFile("BusinessCardTemplate_enc.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.NO_FLAGS, null);
148                    
149            mOutputListener.println("Decrypt the PDFTron custom security encrypted document above...");
150            // Register the PDFTron Custom Security handler with the same custom id used in encryption
151            PDFNet.addPDFTronCustomHandler(custom_id);
152
153            PDFDoc doc_enc = new PDFDoc(Utils.createExternalFile("BusinessCardTemplate_enc.pdf", mFileList).getAbsolutePath());
154            doc_enc.initStdSecurityHandler(pass);
155            doc_enc.removeSecurity();
156            // Save the decrypted document
157            doc_enc.save(Utils.createExternalFile("BusinessCardTemplate_enc_dec.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.NO_FLAGS, null);
158            mOutputListener.println("Done. Result saved in BusinessCardTemplate_enc_dec.pdf");
159        } catch (Exception e) {
160            mOutputListener.printError(e.getStackTrace());
161        }
162        mOutputListener.println("-------------------------------------------------");
163        mOutputListener.println("Tests completed.");
164
165		for (String file : mFileList) {
166			addToFileList(file);
167		}
168		printFooter(outputListener);
169	}
170
171}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5package com.pdftron.android.pdfnetsdksamples.samples
6
7import com.pdftron.android.pdfnetsdksamples.OutputListener
8import com.pdftron.android.pdfnetsdksamples.PDFNetSample
9import com.pdftron.android.pdfnetsdksamples.R
10import com.pdftron.android.pdfnetsdksamples.util.Utils
11import com.pdftron.common.PDFNetException
12import com.pdftron.filters.FlateEncode
13import com.pdftron.filters.MappedFile
14import com.pdftron.pdf.PDFDoc
15import com.pdftron.pdf.PDFNet
16import com.pdftron.sdf.PDFTronCustomSecurityHandler
17import com.pdftron.sdf.SDFDoc
18import com.pdftron.sdf.SecurityHandler
19
20class EncTest : PDFNetSample() {
21    override fun run(outputListener: OutputListener?) {
22        super.run(outputListener)
23        mOutputListener = outputListener
24        mFileList.clear()
25        printHeader(outputListener!!)
26
27        // Example 1:
28        // secure a document with password protection and
29        // adjust permissions
30        try {
31            // Open the test file
32            mOutputListener!!.println("Securing an existing document ...")
33            PDFDoc(Utils.getAssetTempFile(INPUT_PATH.toString() + "fish.pdf")!!.getAbsolutePath()).use { doc ->
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                {
40                    mOutputListener!!.println("Replacing the content stream, use flate compression...")
41
42                    // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
43                    val page_dict: com.pdftron.sdf.Obj = doc.getTrailer().get("Root").value()
44                        .get("Pages").value()
45                        .get("Kids").value()
46                        .getAt(0)
47
48                    // Embed a custom stream (file mystream.txt) using Flate compression.
49                    val embed_file = MappedFile(Utils.getAssetTempFile(INPUT_PATH.toString() + "my_stream.txt")!!.getAbsolutePath())
50                    val mystm: com.pdftron.filters.FilterReader = com.pdftron.filters.FilterReader(embed_file)
51                    page_dict.put("Contents",
52                        doc.createIndirectStream(mystm,
53                            FlateEncode(null)))
54                }
55
56                //encrypt the document
57
58                // Apply a new security handler with given security settings.
59                // In order to open saved PDF you will need a user password 'test'.
60                val new_handler = SecurityHandler()
61
62                // Set a new password required to open a document
63                val user_password = "test"
64                new_handler.changeUserPassword(user_password)
65
66                // Set Permissions
67                new_handler.setPermission(SecurityHandler.e_print, true)
68                new_handler.setPermission(SecurityHandler.e_extract_content, false)
69
70                // Note: document takes the ownership of new_handler.
71                doc.setSecurityHandler(new_handler)
72
73                // Save the changes.
74                mOutputListener!!.println("Saving modified file...")
75                doc.save(Utils.createExternalFile("secured.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.NO_FLAGS, null)
76            }
77        } catch (e: PDFNetException) {
78            mOutputListener!!.printError(e.getStackTrace())
79        }
80
81        // Example 2:
82        // Opens the encrypted document and removes all of
83        // its security.
84        try {
85            PDFDoc(Utils.createExternalFile("secured.pdf", mFileList).getAbsolutePath()).use { doc ->
86                //If the document is encrypted prompt for the password
87                if (!doc.initSecurityHandler()) {
88                    var success = false
89                    mOutputListener!!.println("The password is: test")
90                    for (count in 0..2) {
91                        val r: java.io.BufferedReader = java.io.BufferedReader(java.io.InputStreamReader(java.lang.System.`in`))
92                        mOutputListener!!.println("A password required to open the document.")
93                        mOutputListener!!.print("Please enter the password: ")
94                        // String password = r.readLine();
95                        if (doc.initStdSecurityHandler("test")) {
96                            success = true
97                            mOutputListener!!.println("The password is correct.")
98                            break
99                        } else if (count < 3) {
100                            mOutputListener!!.println("The password is incorrect, please try again")
101                        }
102                    }
103                    if (!success) {
104                        mOutputListener!!.println("Document authentication error....")
105                    }
106                }
107
108                //remove all security on the document
109                doc.removeSecurity()
110                doc.save(Utils.createExternalFile("not_secured.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.NO_FLAGS, null)
111            }
112        } catch (e: java.lang.Exception) {
113            mOutputListener!!.printError(e.getStackTrace())
114        }
115
116        // Example 3:
117        // Encrypt/Decrypt a PDF using PDFTron custom security handler
118        try {
119            mOutputListener!!.println("-------------------------------------------------")
120            mOutputListener!!.println("Encrypt a document using PDFTron Custom Security handler with a custom id and password...")
121            PDFDoc(Utils.getAssetTempFile(INPUT_PATH.toString() + "BusinessCardTemplate.pdf")!!.getAbsolutePath()).use { doc ->
122                // Create PDFTron custom security handler with a custom id. Replace this with your own integer
123                val custom_id = 123456789
124                val custom_handler = PDFTronCustomSecurityHandler(custom_id)
125
126                // Add a password to the custom security handler
127                val pass = "test"
128                custom_handler.changeUserPassword(pass)
129
130                // Save the encrypted document
131                doc.setSecurityHandler(custom_handler)
132                doc.save(Utils.createExternalFile("BusinessCardTemplate_enc.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.NO_FLAGS, null)
133                mOutputListener!!.println("Decrypt the PDFTron custom security encrypted document above...")
134                // Register the PDFTron Custom Security handler with the same custom id used in encryption
135                PDFNet.addPDFTronCustomHandler(custom_id)
136                val doc_enc = PDFDoc(Utils.createExternalFile("BusinessCardTemplate_enc.pdf", mFileList).getAbsolutePath())
137                doc_enc.initStdSecurityHandler(pass)
138                doc_enc.removeSecurity()
139                // Save the decrypted document
140                doc_enc.save(Utils.createExternalFile("BusinessCardTemplate_enc_dec.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.NO_FLAGS, null)
141                mOutputListener!!.println("Done. Result saved in BusinessCardTemplate_enc_dec.pdf")
142            }
143        } catch (e: java.lang.Exception) {
144            mOutputListener!!.printError(e.getStackTrace())
145        }
146        mOutputListener!!.println("-------------------------------------------------")
147        mOutputListener!!.println("Tests completed.")
148        for (file in mFileList) {
149            addToFileList(file)
150        }
151        printFooter(outputListener)
152    }
153
154    companion object {
155        private var mOutputListener: OutputListener? = null
156        private val mFileList: java.util.ArrayList<String> = java.util.ArrayList<String>()
157    }
158
159    init {
160        setTitle(R.string.sample_encryption_title)
161        setDescription(R.string.sample_encryption_description)
162    }
163}
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales