将PDF文档全部页面导出为A4尺寸使用PDFBOX的图像(PDF文档包含不同的页面尺寸,如A3和Letter)

时间:2019-04-29 12:32:33

标签: java pdf pdfbox

我尝试使用下面从此处处理的代码:link

但是该代码用于将多个不同大小的图像添加到pdf中。

我只是想进行相反的处理,以将不同大小的pdf文档页面导出到图像,就像上面的链接一样。

private static void exportPDF_To_Images(File sourceDir, String destinationDir) {
    try {
        File outputfile = null;
        File destinationFile = new File(destinationDir);
        if (!destinationFile.exists())
            destinationFile.mkdir();

        PDDocument document = PDDocument.load(sourceDir, MemoryUsageSetting.setupTempFileOnly());

        PDFRenderer pdfRenderer = new PDFRenderer(document);
        String fileName = "Export_Image";

        for (int page = 0; page < document.getNumberOfPages(); ++page) {

            outputfile = new File(destinationDir + File.separator + fileName + "_" + (page + 1) + ".png");
            BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300);

            ImageIOUtil.writeImage(bim, destinationDir + File.separator + fileName + "_" + (page + 1) + ".png", 300);

            PDImageXObject image = PDImageXObject.createFromFile(destinationDir + File.separator + fileName + "_" + (page + 1) + ".png", document);
            PDRectangle pageSize = PDRectangle.A4;

            int originalWidth = image.getWidth();
            int originalHeight = image.getHeight();
            float pageWidth = pageSize.getWidth();
            float pageHeight = pageSize.getHeight();
            float ratio = Math.min(pageWidth / originalWidth, pageHeight / originalHeight);
            float scaledWidth = originalWidth * ratio;
            float scaledHeight = originalHeight * ratio;
            float x = (pageWidth - scaledWidth) / 2;
            float y = (pageHeight - scaledHeight) / 2;

            PDPage pdpage = new PDPage(pageSize);
            document.addPage(pdpage);

            try (PDPageContentStream contents = new PDPageContentStream(document, pdpage)) {
                contents.drawImage(image, x, y, scaledWidth, scaledHeight);
            }
            System.out.println("Added: " + destinationDir + File.separator + fileName + "_" + (page + 1) + ".png");

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

0 个答案:

没有答案