我试图为现有的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)
提前感谢您的宝贵建议。
答案 0 :(得分:2)
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();
}
}
答案 1 :(得分:1)
我看到这一行评论了 -
//exporter.setParameter(JRExporterParameter.INPUT_FILE, new File("D:\\Project1\\EmailSendExample\\WebContent\\PDFiles\\AnnexI.pdf"));
关于输入的例外讨论 -
net.sf.jasperreports.engine.JRException: No input source supplied to the exporter.