Search code examples
pdfbox

How to display an image in PdfBox 2.0.3?


Can someone give me an example on how to display image in PDF file using Apache PDFBox 2.0.3?

Thanks in advance


Solution

  • You might want to look at the pdfbox examples directory in the Apache SVN repository, in particular the aptly named example class AddImageToPDF with this pivotal method:

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