简体   繁体   English

Java PDFBox,如何从PDDocument获取File对象

[英]Java PDFBox, how to get File object from PDDocument

I am trying to retrieve a File or InputStream instance from PDDocument without saving a PDDocument to the file system. 我正在尝试从PDDocument检索FileInputStream实例,而不将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是否有任何方法可以从现有PDDocument返回FileInputStream

I solved it: 我解决了:

PDDocument doc=new PDDocument();        
PDStream ps=new PDStream(doc);
InputStream is=ps.createInputStream();

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();

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) 看看这个http://pdfbox.apache.org/apidocs/org/apache/pdfbox/pdmodel/PDDocument.html#save(java.io.OutputStream)

I am trying to retrieve a File or InputStream instance from PDDocument without saving a PDDocument to the file system. 我正在尝试从PDDocument检索FileInputStream实例,而不将PDDocument保存到文件系统。

[...] [...]

Is there any method in PDFBox which returns File or InputStream from an existing PDDocument ? PDFBox是否有任何方法可以从现有PDDocument返回FileInputStream

Obviously PDFBox cannot return a meaningful File object without saving a PDDocument to the file system . 显然,如果不将PDDocument保存到文件系统中, PDFBox无法返回有意义的File对象。

It does not offer a method providing an InputStream directly either but it is easy to write code around it that does. 它也没有提供直接提供InputStream的方法,但是很容易围绕它编写代码。 eg: 例如:

InputStream docInputStream = null;

try (   ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PDDocument doc = new PDDocument()   )
{
    [...]
    doc.save(baos);
    docInputStream = new ByteArrayInputStream(baos.toByteArray());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM