HanG321 Blog

[Java] PDF to JPG

http://forum.java.sun.com/thread.jspa?threadID=359395&start=30&tstart=0

Here is a quick test sample that I ran with for PDF to JPG conversion.
I only had to convert the 1st page, so if you wanted multi-pages you will have to adapt the above example.
I use the ImageIO and jpedal jars.

Quick overview.
give the decoder the filename of the pdf to open
Grab the 1st page, and resize it to a thumbnail version
save the image.

import org.jpedal.*;

import java.io.*;

import javax.imageio.*;
import javax.imageio.stream.*;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;

import java.util.*;

public class PdfToJpgTest
{

    public static void PDFToJpg(String filepath)
    {
        try
        {
            PdfDecoder decoder = new PdfDecoder();
            decoder.openPdfFile(filepath);
            if (decoder.isFileViewable())
            {
                //just grab the first page, and render it as an image.
                BufferedImage thumbnailImage = getThumbnailImage(decoder.getPageAsImage(1));
                saveImage(thumbnailImage,"1.jpg");
            }
        }
        catch (Exception err)
        {
            err.printStackTrace();
        }
    }

    public static void saveImage(Image image, String fileName)
    {
        File fileToSave = new File(fileName);
        try
        {
            ImageIO.write((RenderedImage)image,"jpg", fileToSave);
        }
        catch (Exception err)
        {
            err.printStackTrace();
        }
    }

    private static BufferedImage getThumbnailImage(BufferedImage image)
    {
        BufferedImage resizedImage = null;
        Graphics g = image.getGraphics();
        int resizeWidth = 0;
        int resizeHeight = 0;
        resizeHeight = 256;
        resizeWidth = (image.getWidth() * resizeHeight) / image.getHeight();
        resizedImage = new BufferedImage(resizeWidth, resizeHeight, BufferedImage.TYPE_INT_RGB);
        resizedImage.createGraphics().drawImage(image, 0, 0, resizeWidth, resizeHeight, null);
        return resizedImage;
    }

    public static void main(String args[])
    {
        System.out.println("Staring PDF to JPG test");
        PDFToJpg("Winter 2006.pdf");
        System.out.println("Ending PDF to JPG test");

    }
}

 

Exit mobile version