Crionics LOGO

TUTORIALS

 

 Printer Tutorial:
How to convert a PDF to a GIF, PNG or JPEG

As easy as 1, 2, 3...

 

Open the document you wish to print

In this tutorial, we will show you how to generate a graphical representation of a page taken from a PDF document.

First, let's open the document...

PdfDocument doc = new PdfDocument("mydocument.pdf");

Our next step is to get the printer module. This module gives access to a set of easy-to-use methods to print documents to physical printers or graphics.

// Get the printer module:
PrinterModule pm = doc.getPrinterModule();

 

Rendering from a page to an awt.Image

There are two methods to generate a gfx from the PrintModule class:

public BufferedImage convertToImage(int pageIdx) throws PdfException, IOException
and
public BufferedImage convertToImage(int pageIdx, int dpi) throws PdfException, IOException

The second method accepts an extra parameter - the dpi (DotPerInch) - which can be used to control the size (zoom factor) of the generated image. The default DPI is set to the industry standard 72 pixels per inch.

The code below will convert page one of a document to an awt.Image:

// Convert page 1 to a graphical representation:
BufferedImage image = pm.convertToImage(1);

// We can close the document at this point to save resources:
doc.close();

 

Converting the awt.Image to a standard gfx format

Once the BufferedImage is generated, things get really easy. The next step is to encode the awt.Image to a graphical format.
In this example we used JPEG because it is part of the standard JDK. But you can also install an external codec library such as JAI (Java Advanced Imaging) and convert to a vast number of other formats. The latest version of the JDK also knows how to generate PNG.

FileOutputStream fos = new FileOutputStream("mygfx.jpg");
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(fos);
jpeg.encode(image);
fos.close();


© 2000-2007 Crionics Inc. Report issues with this page