java - PDFBox:将文档转换为 PDDocument

标签 java document pdfbox

我用 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 内部执行此操作。

所以我的问题是:如何将文档转换为 PDDocument?

非常感谢任何帮助!

最佳答案

您可以做的是将 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);

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

关于java - PDFBox:将文档转换为 PDDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26818654/

相关文章:

java - 在PDFBox中,如何创建具有 "rollover"/"mouse over"效果的链接注释?

java - 如何设置单元格的背景颜色?

asp.net-mvc - 使用RavenDB的类似Twitter的模型

java - 如何在android中显示内容(例如数学等类(class)),例如 "bac 2016"(digischool应用程序)

java - 按分隔符分割 PDF?

java - 将 Zip 文件作为 InputStream,然后分离其中的每个文件,然后将其转换为图像。 java 语

java - Spring 4.3.0.RELEASE + Hibernate 5.2.0.Final + JPA 存储库

java - java的设置方法不起作用

java - 为什么使用 "new Throwable().getStackTrace()[1].getMethodName()"获取结果被称为昂贵?

Android 如何在图库中查看 SD 卡中的文档?