Make PDF password protected with iText API.
1) Encrypt existing PDF document:-
To encrypt existing document one need to create object of PdfEncryptor class.
The encrypt method of PDFEncryptor class take following parameters
Reader : the read PDF
Output stream
: the output destination
Type : t
he type of encryption. It can be one of
STANDARD_ENCRYPTION_40,
public void encryptPDFFile(String sourceFilePath
, String destinationFilePath
, String userPassword
, String ownerPassword){
try{
PdfEncryptor.encrypt(new PdfReader(sourceFilePath)
, new FileOutputStream(destinationFilePath)
, PdfWriter.STANDARD_ENCRYPTION_128
, userPassword
, ownerPassword
, PdfWriter.ALLOW_DEGRADED_PRINTING);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
1) Encrypt PDF document generated form scratch:-
To encrypt generated document one have to create PdfWriter object.
Parameters required by setEncryption method of PdfWriter are
User Password : the user password.
O
P
wner Password : the owner password.
P
ermissions : the user permissions
Type : t
he type of encryption. It can be one of
STANDARD_ENCRYPTION_40,
STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.
public void encryptGeneratedPDFDocument(PdfWriter writer
, String userPassword, String ownerPassword)
{
try{
writer.setEncryption(userPassword.getBytes()
,ownerPassword.getBytes()
, PdfWriter.ALLOW_DEGRADED_PRINTING
, PdfWriter.STANDARD_ENCRYPTION_128);
} catch (DocumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
How to read PDF documents if documents are password protected
1) Need to decrypt pdf
2) Read pdf document.
For that one has to use constructor of PdfReader which will take byte array of owner
password as parameter.
public void readEncryptedPDF(List<File> fileList
, String actualPath
, String ownerPassword){
PdfReader reader = null;
try{
// If PDF document is not encrypted
reader = new PdfReader(ff.getAbsolutePath());
}catch (IOException io) {
System.err.println("BAD PASSWORD EXCEPTION");
// If PDF document is encrypted
reader = new PdfReader(ff.getAbsolutePath()
, ownerPassword.getBytes());
}
}
No comments:
Post a Comment