doc = PDDocument.load( inputFile );
//we will add the image to the first page.
PDPage page = doc.getPage(0);
PDImageXObject ximage;
if( image.toLowerCase().endsWith( ".jpg" ) )
{
ximage = JPEGFactory.createFromStream(doc, new FileInputStream(image));
}
else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
{
ximage = CCITTFactory.createFromRandomAccess(doc, new RandomAccessFile(new File(image),"r"));
}
else if (image.toLowerCase().endsWith(".gif") ||
image.toLowerCase().endsWith(".bmp") ||
image.toLowerCase().endsWith(".png"))
{
BufferedImage bim = ImageIO.read(new File(image));
ximage = LosslessFactory.createFromImage(doc, bim);
}
else
{
throw new IOException( "Image type not supported: " + image );
}
PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
//contentStream.drawImage(ximage, 20, 20 );
// better method inspired by http://stackoverflow.com/a/22318681/535646
float scale = 1f; // reduce this value if the image is too large
contentStream.drawXObject(ximage, 20, 20, ximage.getWidth()*scale, ximage.getHeight()*scale);
contentStream.close();
doc.save( outputFile );
}
finally