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 File
or InputStream
instance from PDDocument
without saving a PDDocument
to the file system.
我正在尝试从不将 a 保存到文件系统的情况下检索 aFile
或InputStream
实例。PDDocument
PDDocument
PDDocument doc= new PDDocument();
...
doc.save("D:\document.pdf");
File f= new File("D:\document.pdf");
Is there any method in PDFBox
which returns File
or InputStream
from 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
File
orInputStream
instance fromPDDocument
without saving aPDDocument
to the file system.[...]
Is there any method in
PDFBox
which returnsFile
orInputStream
from an existingPDDocument
?
我正在尝试从不将 a 保存到文件系统的情况下检索 a
File
或InputStream
实例。PDDocument
PDDocument
[...]
是否有任何方法
PDFBox
可以返回File
或InputStream
从现有的返回PDDocument
?
Obviously PDFBox cannot return a meaningful File
object without saving a PDDocument
to the file system.
显然,如果不将 a保存到文件系统,PDFBox 就无法返回有意义的File
对象。PDDocument
It does not offer a method providing an InputStream
directly 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)