Java 如何向base 64 pdf添加密码?
我有这样一种方法,在pdf中添加一个密码,但我使用的是计算机上的pdf。我想尝试的是接收一个字符串作为输入参数,该字符串将是base64中的pdf格式,并响应base64Java 如何向base 64 pdf添加密码?,java,pdf,itext7,Java,Pdf,Itext7,我有这样一种方法,在pdf中添加一个密码,但我使用的是计算机上的pdf。我想尝试的是接收一个字符串作为输入参数,该字符串将是base64中的pdf格式,并响应base64 public static void main(String[] args) { try { OutputStream file = new FileOutputStream(new File("D:\\Test.pdf")); Doc
public static void main(String[] args) {
try {
OutputStream file = new FileOutputStream(new File("D:\\Test.pdf"));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);
writer.setEncryption(USER_PASS.getBytes(), OWNER_PASS.getBytes(),
PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
document.open();
document.add(new Paragraph("Hello World, iText"));
document.add(new Paragraph(new Date().toString()));
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
如何处理Base64 pdf很复杂,因为这是第一次,但最终我开发了一种方法,可以将密码添加到Base64中已有的pdf中
public String EncriptarPDFconContraseña(String pdfBase64, String passwordUser, String passwordOwner) throws IOException, DocumentException {
PdfReader reader = new PdfReader(Base64.decode(pdfBase64));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, baos);
stamper.setEncryption(passwordUser.getBytes(), passwordOwner.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
stamper.close();
String base64 = Base64.encodeBytes(baos.toByteArray());
return base64;
}