我想让pdf文件受密码保护。我只是用谷歌搜索它并找到下面给出的一个很好的解决方案。它工作正常但是在我使用下面给定的代码保护 pdf 后,它清除了我的 pdf 中已经存在的所有数据。
此代码使用的 jar 文件是:
itextpdf-5.2.1.jar
bcmail-jdk16-1.46.jar
bcprov-jdk16-1.46.jar
bctsp-jdk16-1.46.jar
保护 PDF 的代码:
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Secure_file {
private static String USER_PASSWORD = "password";
private static String OWNER_PASSWORD = "secured";
public static void main(String[] args) throws IOException {
Document document = new Document();
try {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:\\sample.pdf"));
writer.setEncryption(USER_PASSWORD.getBytes(),OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
document.open();
document.add(new Paragraph("This is Password Protected PDF document."));
document.close();
writer.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我需要在这个程序中做哪些改变?
如果您查找iText in Action 关键字,您会发现加密指向示例 part3.chapter12。EncryptionPdf。该示例的方法createPdf本质上等同于您的代码,但该方法encryptPdf是您想要的:
/** User password. */
public static byte[] USER = "Hello".getBytes();
/** Owner password. */
public static byte[] OWNER = "World".getBytes();
...
public void encryptPdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.setEncryption(USER, OWNER,
PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
stamper.close();
reader.close();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23434 次 |
| 最近记录: |