Password Protect PDF in Java
Password protection can be added to new PDF documents or to an existing PDF document using the DynamicPDF Generator and Merger products respectively. The steps and sample codes below explains using both products.
How to Password Protect a PDF
Setting password protection and encrypting a PDF can be done in a few lines of code.
When a user password is specified, the PDF viewer will require this password to open the PDF document. If left blank the viewer will not prompt for a password when opening the PDF.
When an owner password is specified, the PDF viewer will require it to modify the PDF.
Below is the list of classes used to set passwords or to encrypt PDF with different secuirty settings.
Steps to Password Protect PDF
- Create a
Document
object. - Create a
Page
object and add it toDocument
. - Create a
Aes256Security
object by setting the owner and user password. - Set the security to the
Document
. - Invoke the
Draw
method on the Document to output the PDF.
Sample code - Java
Document document = new Document();
Page page = new Page();
document.getPages().add(page);
Aes256Security security = new Aes256Security("owner", "user");
document.setSecurity(security);
document.Draw(@"Output.pdf");
How to Add Password to a PDF
The above security classes can be used to add password protection to an existing PDF document as well.
Steps to Add Password to PDF
- Create a
MergeDocument
object with the path to the PDF file. - Create a
Aes256Security
object by setting the owner and user password. - Set the security to the Document.
- Invoke the
Draw
method on the Document to output the PDF.
Sample code - Java
MergeDocument document = new MergeDocument("pdf-a.pdf");
Aes256Security security = new Aes256Security("owner", "user");
document.setSecurity(security);
document.Draw(@"Output.pdf");
Getting Started
DynamicPDF Generator and Merger Information
More information can be found here:
Available in Other Platforms
Generator and Merger PDF Libraries are available for .NET and COM/AxtiveX platforms. Refer to the respective product pages for more details.
- DynamicPDF Generator
- .NET - DynamicPDF Generator for .NET
- COM/ActiveX - DynamicPDF Generator for COM/ActiveX
- DynamicPDF Merger
- .NET - DynamicPDF Merger for .NET
- COM/ActiveX - DynamicPDF Merger for COM/ActiveX