Encrypt & Decrypt PDFs - PHP Sample Code

Sample code for using Apryse SDK to read encrypted (password protected) documents, secure a document with encryption, or remove encryption. Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. Learn more about our Server SDK.

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?>

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales