Encrypt & Decrypt PDFs - Ruby 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#---------------------------------------------------------------------------------------
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."

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales