PDFBox:将文档转换为PDDocument

3

我使用iText创建了一个文档,并希望将其(保存为PDF文件)转换为图像。为此,我使用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内部执行此操作。

因此,我的问题是:如何将Document转换为PDDocument?

非常感谢任何帮助!

1个回答

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);

当然,文件不应该太大,否则会出现内存问题。

谢谢您的回答!我现在使用它来保存PDF文件:PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfName));。根据您的回答,我能否轻松地将new FileOutputStream()替换为new ByteArrayOutputStream(); - bashoogzaad
我尝试了上面的方法,它有效,所以您可以更新上面的答案! - bashoogzaad
谢谢 :-) 还有一件事:缩放实际上并不是必需的。如果您知道您喜欢默认PDFBox渲染的2/3大小,则可以使用较小的dpi。没有参数的方法的dpi为96。因此,96 * 2/3 = 64。因此,请使用PDFBox进行此调用:page.convertToImage(BufferedImage.TYPE_INT_RGB, 64); - Tilman Hausherr
我使用http://itextpdf.com/examples/iia.php?id=24中的内容完成了答案,以添加虚拟itext文档的创建。 - Tilman Hausherr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接