2014-11-08 164 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