Reputation: 11
I want to make an existing PDF as password protected for which I'm using the itext I am following this URL
http://howtodoinjava.com/2014/07/29/create-pdf-files-in-java-itext-tutorial/
I have developed a program which will send the mail with the PDF as attachment. Below is the code where I am making the PDF file as password protected.
Right now the PDF file is attached in mail but when I am trying to open it, I get an error that it is damaged.
What am I doing wrong in the code below?
// attachment part
MimeBodyPart attachPart = new MimeBodyPart();
String filename = "c:\\SettingupRulesin outlook2003.pdf";
//OutputStream file = new FileOutputStream(new File("PasswordProtected.pdf"));
final OutputStream os = new FileOutputStream(filename);
com.itextpdf.text.Document doc = new com.itextpdf.text.Document();
PdfWriter writer = PdfWriter.getInstance(doc, os);
writer.setEncryption(USER_PASSWORD.getBytes(),
OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING,
PdfWriter.ENCRYPTION_AES_128);
os.close();
DataSource source = new FileDataSource(filename);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(filename);
Upvotes: 0
Views: 2058
Reputation: 7634
You use a PdfWriter
. That class can be used to create new PDFs from scratch, not to manipulate existing ones. Please use a PdfStamper
instead which is for manipulating existing documents.
Upvotes: 1