简体   繁体   English

PDFBox:将文档转换为PDDocument

[英]PDFBox: Convert Document to PDDocument

I have created a Document with iText, and I would like to convert this document (which is saved as a PDF file) to an image. 我用iText创建了一个Document,我想把这个文件(保存为PDF文件)转换成图像。 For this I use PDFBox, which wants a PDDocument as input. 为此我使用PDFBox,它想要一个PDDocument作为输入。 I use the following code: 我使用以下代码:

@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;
}

At the moment, I load the document from the file which has been saved. 此刻,我从已保存的文件中加载文档。 But I would like to perform this internally from within Java. 但我想在Java内部执行此操作。

So my question is: how can I convert a Document to a PDDocument? 所以我的问题是:如何将文档转换为PDDocument?

Any help is greatly appreciated! 任何帮助是极大的赞赏!

What you could do is to save the itext file into a ByteArrayOutputStream, convert that one to a ByteArrayInputStream. 你可以做的是将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);

Of course the file shouldn't be too big, or you'll have memory problems. 当然文件不应该太大,否则你会遇到内存问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM