2017-10-11 332 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