如何在PdfBox 2.0.3中显示图像

时间:2016-10-03 05:50:17

标签: pdfbox

有人可以举例说明如何使用Apache PDFBox 2.0.3在pdf上显示图像。

提前致谢

1 个答案:

答案 0 :(得分:2)

您可能希望使用以下关键方法查看pdfbox examples directory in the Apache SVN repository,特别是恰当命名的示例类AddImageToPDF

public void createPDFFromImage( String inputFile, String imagePath, String outputFile )
        throws IOException
{
    // the document
    PDDocument doc = null;
    try
    {
        doc = PDDocument.load( new File(inputFile) );

        //we will add the image to the first page.
        PDPage page = doc.getPage(0);

        // createFromFile is the easiest way with an image file
        // if you already have the image in a BufferedImage, 
        // call LosslessFactory.createFromImage() instead
        PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true);

        // contentStream.drawImage(ximage, 20, 20 );
        // better method inspired by http://stackoverflow.com/a/22318681/535646
        // reduce this value if the image is too large
        float scale = 1f;
        contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth()*scale, pdImage.getHeight()*scale);

        contentStream.close();
        doc.save( outputFile );
    }
    finally
    {
        if( doc != null )
        {
            doc.close();
        }
    }
}