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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:18:00  来源:igfitidea点击:

Java PDFBox, how to get File object from PDDocument

javapdfbox

提问by Milos Gavrilov

I am trying to retrieve a Fileor InputStreaminstance from PDDocumentwithout saving a PDDocumentto the file system.

我正在尝试从不将 a 保存到文件系统的情况下检索 aFileInputStream实例。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可以返回FileInputStream从现有的返回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 Fileor InputStreaminstance from PDDocumentwithout saving a PDDocumentto the file system.

[...]

Is there any method in PDFBoxwhich returns Fileor InputStreamfrom an existing PDDocument?

我正在尝试从不将 a 保存到文件系统的情况下检索 aFileInputStream实例。PDDocumentPDDocument

[...]

是否有任何方法PDFBox可以返回FileInputStream从现有的返回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)

看看这个 http://pdfbox.apache.org/apidocs/org/apache/pdfbox/pdmodel/PDDocument.html#save(java.io.OutputStream)