2014-11-08 54 views
2

我已經用iText創建了一個文檔,並且我想將此文檔(將其保存爲PDF文件)轉換爲圖像。爲此我使用PDFBox,它需要一個PDDocument作爲輸入。我使用以下代碼:PDFBox:將文檔轉換爲PDDocument

@SuppressWarnings("unchecked") 
public static Image convertPDFtoImage(String filename) { 

    Image convertedImage = null; 

    try { 

     File sourceFile = new File(filename); 
     if (sourceFile.exists()) { 

      PDDocument document = PDDocument.load(filename); 
      List<PDPage> list = document.getDocumentCatalog().getAllPages(); 
      PDPage page = list.get(0); 

      BufferedImage image = page.convertToImage(); 

      //Part where image gets scaled to a smaller one 
      int width = image.getWidth()*2/3; 
      int height = image.getHeight()*2/3; 
      BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); 
      Graphics2D graphics2D = scaledImage.createGraphics(); 
      graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 
      graphics2D.drawImage(image, 0, 0, width, height, null); 
      graphics2D.dispose(); 

      convertedImage = SwingFXUtils.toFXImage(scaledImage, null); 

      document.close(); 

     } else { 
      System.err.println(sourceFile.getName() +" File not exists"); 
     } 

    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return convertedImage; 
} 

此刻,我從已保存的文件中加載文檔。但我想從Java內部執行此操作。

所以我的問題是:如何將文檔轉換爲PDDocument?

任何幫助,非常感謝!

回答

1

你可以做的是將itext文件保存到ByteArrayOutputStream中,將其轉換爲ByteArrayInputStream。

Document document = new Document(); 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
PdfWriter writer = PdfWriter.getInstance(document, baos); 
document.open(); 
document.add(new Paragraph("Hello World!")); 
document.close(); 
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); 
PDDocument document = PDDocument.load(bais); 

當然這個文件不應該太大,否則你會遇到內存問題。

+0

謝謝你的回答!我現在用它來保存帶有iText的PDF文件:'PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(pdfName));'。我可以通過交換新的FileOutputStream()與'new ByteArrayOutputStream();'來輕鬆地改變它嗎? – bashoogzaad 2014-11-08 18:53:37

+0

我嘗試了上述,它的工作,所以你可以用它更新上述答案! – bashoogzaad 2014-11-08 19:04:03

+0

謝謝:-)還有一件事:縮放並不是真的需要。如果您知道您更喜歡默認PDFBox渲染的2/3,那麼您可以使用更小的dpi。無參數方法的dpi爲96.因此96 * 2/3 = 64。因此,使用PDFBox進行此調用:page.convertToImage(BufferedImage.TYPE_INT_RGB,64); – 2014-11-08 23:20:57