首页 > 解决方案 > 如何呈现受密码保护的 PDF

问题描述

我正在使用飞碟从 XHTML 生成 PDF。渲染效果很好,但是任何对 PDF 文档进行密码保护的尝试都会失败并出现异常。

我正在使用 Ajit Soman 在https://stackoverflow.com/a/46024498/4517737中推荐的代码。代码副本如下所示。如果取消注释注释行,则会在“ renderer.createPDF(os, false) ”行中引发异常。

异常是“线程中的异常”JavaFX 应用程序线程“java.lang.RuntimeException: java.lang.reflect.InvocationTargetException ”(对于 JavaFX 应用程序)。

对于纯 Java,异常是“线程中的异常”“main”java.lang.NoClassDefFoundError: org/bouncycastle/asn1/ASN1Encodable at com.itextpdf.text.pdf.PdfEncryption.(PdfEncryption.java:147).....引起:java.lang.ClassNotFoundException:org.bouncycastle.asn1.ASN1Encodable "

final File outputFile = File.createTempFile(fileName, ".pdf");
FileOutputStream os = new FileOutputStream(outputFile);
PDFEncryption pdfEncryption  = new PDFEncryption();
String password= "password@123";
pdfEncryption.setUserPassword(password.getBytes());
ITextRenderer renderer = new ITextRenderer();

// the following line causes Exception
// renderer.setPDFEncryption(pdfEncryption);

renderer.setDocumentFromString(htmlContent);
renderer.layout();
renderer.createPDF(os, false);
renderer.finishPDF();

请帮忙。

标签: pdf-generationpassword-protectionflying-saucer

解决方案


推荐阅读