Showing posts with label PDF Renderer. Show all posts
Showing posts with label PDF Renderer. Show all posts

Tuesday, February 21, 2017

Create Thubmnail / Image From Each Page of a PDF Using Java

It is very important to make some thumbnails from pdf in our application. Using java it is now very easy to do this task. You have to open your pdf using java program then you can set which page (0...n) you want to make to thumbnail. Then you can save that as image to your server or desktop machine.

To complete this task you need to download PDFRenderer-0.9.1.jar.

You can download whole package from here.

Sample java code:

package com.pkm;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by pritom on 26/12/2016.
 */
public class ThumbnailFromPdf {
    public static void main(String[] args) throws Exception {
        File file = new File("src/com/pkm/PDF.pdf");
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        FileChannel fileChannel = randomAccessFile.getChannel();
        ByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
        PDFFile pdfFile = new PDFFile(byteBuffer);
        PDFPage pdfPage = pdfFile.getPage(0);
        Rectangle rectangle = new Rectangle(0, 0, (int) pdfPage.getBBox().getWidth(), (int) pdfPage.getBBox().getHeight());
        Image image = pdfPage.getImage(rectangle.width, rectangle.height, rectangle, null, true, true);
        ImageIO.write((RenderedImage) image, "png", new File("src/com/pkm/PDF.png"));
    }
}

Sample output would be like something depends on your pdf file: