Java 使用PDFBox保护PDF
我真的在为PDFBox的文档而挣扎。对于这样一个受欢迎的图书馆,信息似乎有点稀薄(对我来说!) 无论如何,我遇到的问题与保护PDF有关。目前我只想控制用户的访问权限。我特别想阻止用户修改PDF 如果我省略了访问权限代码,一切都会正常工作。我正在阅读来自外部资源的PDF文件。然后我读取并填充字段,在保存新PDF之前添加一些图像。这一切都很完美 当我添加以下代码来管理访问权限时,问题出现了:Java 使用PDFBox保护PDF,java,pdf,pdfbox,Java,Pdf,Pdfbox,我真的在为PDFBox的文档而挣扎。对于这样一个受欢迎的图书馆,信息似乎有点稀薄(对我来说!) 无论如何,我遇到的问题与保护PDF有关。目前我只想控制用户的访问权限。我特别想阻止用户修改PDF 如果我省略了访问权限代码,一切都会正常工作。我正在阅读来自外部资源的PDF文件。然后我读取并填充字段,在保存新PDF之前添加一些图像。这一切都很完美 当我添加以下代码来管理访问权限时,问题出现了: /* Secure the PDF so that it cannot be edited */ try {
/* Secure the PDF so that it cannot be edited */
try {
String ownerPassword = "DSTE$gewRges43";
String userPassword = "";
AccessPermission ap = new AccessPermission();
ap.setCanModify(false);
StandardProtectionPolicy spp = new StandardProtectionPolicy(ownerPassword, userPassword, ap);
pdf.protect(spp);
} catch (BadSecurityHandlerException ex) {
Logger.getLogger(PDFManager.class.getName()).log(Level.SEVERE, null, ex);
}
当我添加这段代码时,所有的文本和图像都会从输出的pdf中剥离出来。这些字段仍然存在于文档中,但它们都是空的,所有原始PDF中的文本和图像以及在代码中动态添加的文本和图像都消失了
更新:
好的,就我所知,问题来自与表单字段相关的bug。我将尝试一种不使用表单字段的不同方法,看看它能带来什么。我找到了这个问题的解决方案。看起来,如果PDF来自外部源,有时PDF会受到保护或加密 如果您在从外部源加载PDF文档时得到一个空白输出,并添加保护,那么您可能正在使用加密文档。我有一个处理PDF文档的流处理系统。所以下面的代码对我很有用。如果您只是使用PDF输入,那么您可以将下面的代码与您的流集成
public InputStream convertDocument(InputStream dataStream) throws Exception {
// just acts as a pass through since already in pdf format
PipedOutputStream os = new PipedOutputStream();
PipedInputStream is = new PipedInputStream(os);
System.setProperty("org.apache.pdfbox.baseParser.pushBackSize", "2024768"); //for large files
PDDocument doc = PDDocument.load(dataStream, true);
if (doc.isEncrypted()) { //remove the security before adding protections
doc.decrypt("");
doc.setAllSecurityToBeRemoved(true);
}
doc.save(os);
doc.close();
dataStream.close();
os.close();
return is;
}
现在获取返回的InputStream并将其用于您的安全应用程序
PipedOutputStream os = new PipedOutputStream();
PipedInputStream is = new PipedInputStream(os);
System.setProperty("org.apache.pdfbox.baseParser.pushBackSize", "2024768");
InputStream dataStream = secureData.data();
PDDocument doc = PDDocument.load(dataStream, true);
AccessPermission ap = new AccessPermission();
//add what ever perms you need blah blah...
ap.setCanModify(false);
ap.setCanExtractContent(false);
ap.setCanPrint(false);
ap.setCanPrintDegraded(false);
ap.setReadOnly();
StandardProtectionPolicy spp = new StandardProtectionPolicy(UUID.randomUUID().toString(), "", ap);
doc.protect(spp);
doc.save(os);
doc.close();
dataStream.close();
os.close();
现在,这将返回一个没有空白输出的正确文档
诀窍是先删除加密 我也有同样的问题,随机PDF返回空白。有什么想法吗?我从来没有弄清这个问题的根源。最后我不得不使用另一个图书馆!谢谢我为您找到了一个解决方案。文档链接供参考:您在单线程代码中使用
PipedOutputStream
和PipedInputStream
有点奇怪。对不起。在本例中,pipedinputstream ref实际上被传递到另一个线程(该代码位于固定的akka actors中)。我省略了上面代码中的发送。