2017-10-11 328 views
2

我想将一些图像转换为PDDocument对象,而不是保存到硬件。 如何从此PDDocument对象获取输入流? 我写的是吹,得到“创建InputStream调用没有数据被写入流之前。”错误。pdfbox将图像转换为pdf文件

源的部分是:

public ByteArrayOutputStream imagesToPdf(final List<ImageEntity> images) throws IOException { 

    final PDDocument doc = new PDDocument(); 

    final int count = images.size(); 
    InputStream in = null; 
    PDPageContentStream contentStream = null; 
    final ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    try { 

     for(int i = 0; i < count; i ++) { 

      final ImageEntity image = images.get(i); 

      byte[] byteCode = image.getByteCode(); 

      in = new ByteArrayInputStream(byteCode); 

      BufferedImage bi = ImageIO.read(in); 
      float width = bi.getWidth(); 
      float height = bi.getHeight(); 
      PDPage page = new PDPage(new PDRectangle(width, height)); 
      doc.addPage(page); 

      PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, byteCode, null); 
      contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true); 

      float scale = 1f; 
      contentStream.drawImage(pdImage, 0, 0, pdImage.getWidth()*scale, pdImage.getHeight()*scale); 

      IOUtils.closeQuietly(contentStream); 
      IOUtils.closeQuietly(in); 
     } 
     PDStream ps = new PDStream(doc); 
     is = ps.createInputStream(); 
     IOUtils.copy(is, baos); 
     return baos; 

    } finally { 

     IOUtils.closeQuietly(contentStream); 
     IOUtils.closeQuietly(in); 
    } 
} 

回答

1
new PDStream(doc) 

确实创建从中doc可序列化的形式作为你假设被检索的对象。它实际上做的是创建属于文档doc的PDF流对象

你想要做的仅仅是

doc.save(baos); 
+0

谢谢,它的工作原理。 – user1737352

+0

@ user1737352太棒了!在这种情况下,请将答案标记为已接受(点击左上角的勾号)。 – mkl

+0

抱歉,由于我的声望小于15,我无法点击左上方的三角形符号。 – user1737352