2017-08-30 111 views
0

我需要在内存中创建PDF文档我正在使用pdfbox。在内存中创建pdf文档

这是我的代码,但它在磁盘上创建文档。

public PDDocument generatePDF(String name, String v1, String v2, String v3, String v4) { 
     PDPageContentStream contentStream = null; 
     PDDocument document = null; 
     try { 
      document = new PDDocument(); 
      PDPage page = new PDPage(); 
      document.addPage(page); 
      contentStream = new PDPageContentStream(document, page); 


      fillDataInPDF(...); 
      corpPDF(page); 
     } catch (IOException err) { 
      LOG.error("Error occured ."); 
     } finally { 
      if (contentStream != null) { 
       try { 
        contentStream.close(); 
       } catch (IOException e) { 
        LOG.error("Error occured ."); 
       } 
      } 
     } 
     return document; 
    } 
+0

好的。我赞同你在记忆中创造它的欲望。你真的做到了,或做了一些没有用的东西? –

+0

我已经创建了磁盘,不知道如何在内存中继续。 – singhal

+2

您的代码示例中没有任何内容会暗示它是在光盘上创建的。 –

回答

0

正如@ M.Prokhorov在你的问题中留言已经说过,没有什么您的代码示例中,将表明,它是在光盘上创建。特别是PDDocument构造此处使用

document = new PDDocument(); 

document = new PDDocument(MemoryUsageSetting.setupMainMemoryOnly()); 

设置缓冲存储器使用的简短形式,只使用不以限制主存储器(没有临时文件)尺寸。

因此,除非有一些隐藏在fillDataInPDFcorpPDF写入到一个文件,你的方法完全在内存中创建一个PDF对象模型。

正如我不认为你会隐藏这么明显的文件写入,您的要求,该文件在磁盘上创建最有可能意味着你的方法generatePDF的来电者是序列化模型作为PDF文件保存到磁盘,例如这样

PDDocument doc = generatePDF(name, v1, v2, v3, v4); 
doc.save("SOME_FILE_PATH_ON_DISC"); 

由于@TilmanHausherr指出您可以保存PDF为ByteArrayOutputStream和一个可以转换为字节数组,例如而不是上面你应该使用

PDDocument doc = generatePDF(name, v1, v2, v3, v4); 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
doc.save(baos); 
byte[] pdfBytes = baos.toByteArray(); 

所以保留序列化的PDF文件在内存中。