gpt4 book ai didi

java - 为现有 pdf 文件提供密码保护

转载 作者:行者123 更新时间:2023-11-29 05:22:43 24 4
gpt4 key购买 nike

我正在尝试为现有的 pdf 文件提供密码。它适用于使用 .jrxml 或 .jasper 保存的 jasper 报告,但如何将其提供给 pdf 文件。

示例代码:

public static void main(String[] args) {
String USER="Sai123";
String OWNER="Sairam";

try {
InputStream input=new FileInputStream(new File("D:\\Project1\\EmailSendExample\\WebContent\\PDFiles\\AnnexI.pdf"));
OutputStream file = new FileOutputStream(new File("D:\\Test.pdf"));
/*PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("D:\\Test.pdf"));
stamper.setEncryption(PdfWriter.ALLOW_PRINTING, OWNER,USER, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
stamper.close();
reader.close();*/

JRPdfExporter exporter = new JRPdfExporter();

//exporter.setParameter(JRExporterParameter.INPUT_FILE, new File("D:\\Project1\\EmailSendExample\\WebContent\\PDFiles\\AnnexI.pdf"));
exporter.setParameter(JRExporterParameter.OUTPUT_FILE,new File("D:\\Test.pdf"));
exporter.setParameter(JRPdfExporterParameter.OWNER_PASSWORD, "Sai123");
exporter.setParameter(JRPdfExporterParameter.USER_PASSWORD, "Sairam");
exporter.setParameter(JRPdfExporterParameter.IS_ENCRYPTED, Boolean.TRUE);
exporter.exportReport();
System.out.println("Report Generation Complete");

file.close();

} catch (Exception e) {

e.printStackTrace();
}

它抛出类似的错误

net.sf.jasperreports.engine.JRException: No input source supplied to the exporter.
at net.sf.jasperreports.engine.JRAbstractExporter.setInput(JRAbstractExporter.java:922)
at net.sf.jasperreports.engine.export.JRPdfExporter.exportReport(JRPdfExporter.java:296)
at pdfpassword.main(pdfpassword.java:45)

提前感谢您的宝贵建议。

最佳答案

According to me,we cannot provide pdf file as input to JRexporter.  so in order to make existing pdf password protected use the code below.It works for me.  

代码:


private static String USER_PASSWORD = "password";
private static String OWNER_PASSWORD = "naveen";
public static void main(String[] args) throws IOException {
try
{
PdfReader pdfReader = new PdfReader("/home/base/Desktop/newtask/ext.pdf");
PdfStamper pdfStamper = new PdfStamper(pdfReader,new FileOutputStream("/home/base/Desktop/newtask/ext1.pdf"));
pdfStamper.setEncryption(USER_PASSWORD.getBytes(),OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
pdfStamper.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (com.itextpdf.text.DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

关于java - 为现有 pdf 文件提供密码保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24036335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com