Create thumbnails using PDFRenderer and ImgScalr

public static boolean createThumbnail(File inputFile, File targetFile)
{
try
{
BufferedImage img = null;
if (inputFile != null && targetFile != null && inputFile.getName().toLowerCase().endsWith(".pdf"))
{
img = convertPdfToImage(inputFile);
} else
{
img = ImageIO.read(inputFile);
}
BufferedImage thumbImg = createThumbnail(img);
ImageIO.write(thumbImg, "png", targetFile);
return true;
} catch (Exception e)
{

}
return false;
}

private static BufferedImage createThumbnail(BufferedImage img)
{
BufferedImage result = null;
if (img.getWidth() < img.getHeight())
{
result = resize(img, Method.QUALITY, Mode.FIT_TO_HEIGHT, 128, OP_ANTIALIAS);
} else
{
result = resize(img, Method.QUALITY, Mode.FIT_TO_WIDTH, 128, OP_ANTIALIAS);
}
return result;
}

private static BufferedImage convertPdfToImage(File pdfFile) throws IOException
{
RandomAccessFile raf = null;
FileChannel channel = null;
try
{
raf = new RandomAccessFile(pdfFile, "r");
channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
PDFPage page = pdffile.getPage(0);

Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
Image image = page.getImage(rect.width, rect.height, rect, null, true, true);
BufferedImage img = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
Graphics2D bufImageGraphics = img.createGraphics();
bufImageGraphics.drawImage(image, 0, 0, null);
return img;
} finally
{
if (channel != null)
{
channel.close();
}
if (raf != null)
{
raf.close();
}
}
}