Java PDFBox,如何从 PDDocument 获取 File 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16892625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java PDFBox, how to get File object from PDDocument
提问by Milos Gavrilov
I am trying to retrieve a Fileor InputStreaminstance from PDDocumentwithout saving a PDDocumentto the file system.
我正在尝试从不将 a 保存到文件系统的情况下检索 aFile或InputStream实例。PDDocumentPDDocument
PDDocument doc= new PDDocument();
...
doc.save("D:\document.pdf");
File f= new File("D:\document.pdf");
Is there any method in PDFBoxwhich returns Fileor InputStreamfrom an existing PDDocument?
是否有任何方法PDFBox可以返回File或InputStream从现有的返回PDDocument?
回答by Milos Gavrilov
I solved it:
我解决了:
PDDocument doc=new PDDocument();
PDStream ps=new PDStream(doc);
InputStream is=ps.createInputStream();
回答by Tomasz Przybylski
I solve it in this way ( It's creating a file but in temporary-file directory ):
我以这种方式解决它(它正在创建一个文件,但在临时文件目录中):
final PDDocument document = new PDDocument();
final File file = File.createTempFile(filename, ".pdf");
document.save(file);
and if you need
如果你需要
document.close();
回答by mkl
I am trying to retrieve a
FileorInputStreaminstance fromPDDocumentwithout saving aPDDocumentto the file system.[...]
Is there any method in
PDFBoxwhich returnsFileorInputStreamfrom an existingPDDocument?
我正在尝试从不将 a 保存到文件系统的情况下检索 a
File或InputStream实例。PDDocumentPDDocument[...]
是否有任何方法
PDFBox可以返回File或InputStream从现有的返回PDDocument?
Obviously PDFBox cannot return a meaningful Fileobject without saving a PDDocumentto the file system.
显然,如果不将 a保存到文件系统,PDFBox 就无法返回有意义的File对象。PDDocument
It does not offer a method providing an InputStreamdirectly either but it is easy to write code around it that does. e.g.:
它也不提供InputStream直接提供 的方法,但很容易围绕它编写代码。例如:
InputStream docInputStream = null;
try ( ByteArrayOutputStream baos = new ByteArrayOutputStream();
PDDocument doc = new PDDocument() )
{
[...]
doc.save(baos);
docInputStream = new ByteArrayInputStream(baos.toByteArray());
}
回答by fGo
What if you first create the outputstream
如果您首先创建输出流会怎样
PDDocument doc= new PDDocument();
File f= new File("D:\document.pdf");
FileOutputStream fOut = new FileOutputStream(f);
doc.save(fOut);
Take a look at this http://pdfbox.apache.org/apidocs/org/apache/pdfbox/pdmodel/PDDocument.html#save(java.io.OutputStream)

