How to add .png images to pdf using Apache PDFBox

user3404729 picture user3404729 · Mar 11, 2014 · Viewed 13.8k times · Source

When I try to draw png images using pdfBox, the pages remain blank. Is there any way to insert png images using pdfBox?

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

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

        PDXObjectImage ximage = null;
        if( image.toLowerCase().endsWith( ".jpg" ) )
        {
            ximage = new PDJpeg(doc, new FileInputStream( image ) );
        }
        else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
        {
            ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r"));
        }
        else
        {
            BufferedImage awtImage = ImageIO.read( new File( image ) );
            ximage = new PDPixelMap(doc, awtImage);
  //          throw new IOException( "Image type not supported:" + image );
        }
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
        contentStream.drawImage( ximage, 20, 20 );
        contentStream.close();
        doc.save( outputFile );
    }
    finally
    {
        if( doc != null )
        {
            doc.close();
        }
    }
}

Answer

Kai picture Kai · Aug 15, 2017

There is a pretty nice utility class PDImageXObject to load Images from a java.io.File. As far as I know, it works well with jpg and png files.

PDImageXObject pdImage = PDImageXObject.createFromFileByContent(imageFile, doc);
contentStream.drawImage(pdImage, 20f, 20f);