Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add .png images to pdf using Apache PDFBox

Tags:

java

pdfbox

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();
        }
    }
}
like image 652
user3404729 Avatar asked Mar 11 '14 06:03

user3404729


1 Answers

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); 
like image 178
Kai Avatar answered Oct 26 '22 19:10

Kai