There are various libraries available through to which a pdf can protected with password encryption.
Full maven repository is available here -
But as a developer , I am using here itextpdf library and bouncyCastle libraries to make the PDF password protection.
Following is pom.xml for the dependencies :
Full maven repository is available here -
But as a developer , I am using here itextpdf library and bouncyCastle libraries to make the PDF password protection.
Following is pom.xml for the dependencies :
<dependencies>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.2.1</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.46</version>
</dependency>
</dependencies>
So most import libraries to use are :
1 . itextpdf-5.2.1.jar
2 . bcprov-jdk15on-1.46.jar
Code to implement :
/**
* @author sachin
*
*/
public class PdfEncryption {
public static void main(String[] args) {
try {
String outputPdfFile = "/Users/sachin/Desktop/testing.pdf";
String userPassword = "testing_user";
String ownerPassword ="testing_owner";
String pdfContent = "This is the demonstration of the pdf password protection";
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPdfFile));
writer.setEncryption(userPassword.getBytes(), ownerPassword.getBytes(),
PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
document.open();
document.addAuthor("Sachin Srivastava");
document.addCreator("Sachin Srivastava");
document.addSubject("Thanks for your support");
document.addTitle("Please read this");
HTMLWorker htmlWorker = new HTMLWorker(document);
htmlWorker.parse(new StringReader(pdfContent));
document.close();
writer.close();
System.out.println("pdf created from content");
} catch (Exception e) {
System.out.println("error occured in creating pdf from content");
}
}
}
Above code generates a PDF named testing.pdf with the password protection.
Here PDFWriter setEncryption is used to encrypt the pdf using user password byte
array as a first parameter, owner password byte array as a second parameter, 3rd
parameter as the PDF permission(PdfWriter.ALLOW_PRINTING - 2052 ) and 4th is the
encryption type which is of two type
ENCRYPTION_AES_128
ENCRYPTION_AES_256
So enjoy coding with tek9g tips of encrypting PDF and making it password protected.
Thanks for sharing this blog post,Nice written skill core Java online training Bangalore
ReplyDelete