making pdf as password protected with java

蹲街弑〆低调 提交于 2019-12-30 13:26:07

问题


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);

来源:https://stackoverflow.com/questions/30476522/making-pdf-as-password-protected-with-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!