使用Java将pdf设置为密码保护 [英] making pdf as password protected with java
问题描述
我想制作一个现有的PDF作为密码保护,我正在使用它遵循此URL的itext
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/
我已经开发了一个程序,该程序将发送带有PDF附件的邮件.下面是我将PDF文件设置为受密码保护的代码.
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.
现在,该PDF文件已附加在邮件中,但是当我尝试打开它时,我收到一个错误,指出它已损坏.
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);
推荐答案
您使用 PdfWriter
.该类可用于从头开始创建新的PDF,而不用操作现有的PDF.请改用 PdfStamper
来处理现有文档.
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.
这篇关于使用Java将pdf设置为密码保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!