iText in Action: Chapter 15: Page content and structure

part4.chapter15.ExtractImages

If you compile and execute this example, you'll get the following result:

You can download the full source code of ExtractImages, or read it here:

/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
 
package part4.chapter15;
 
import java.io.IOException;
 
import part3.chapter10.ImageTypes;
 
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
 
/**
 * Extracts images from a PDF file.
 */
public class ExtractImages {
 
    /** The new document to which we've added a border rectangle. */
    public static final String RESULT = "results/part4/chapter15/Img%s.%s";
 
    /**
     * Parses a PDF and extracts all the images.
     * @param src the source PDF
     * @param dest the resulting PDF
     */
    public void extractImages(String filename)
        throws IOException, DocumentException {
        PdfReader reader = new PdfReader(filename);
        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
        MyImageRenderListener listener = new MyImageRenderListener(RESULT);
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            parser.processContent(i, listener);
        }
        reader.close();
    }
 
    /**
     * Main method.
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new ImageTypes().createPdf(ImageTypes.RESULT);
        new ExtractImages().extractImages(ImageTypes.RESULT);
    }
}
 
Powered by GeSHi

The ExtractImages example is part of the book iText in Action (ISBN 9781935182610).

It's a small standalone application. You can use this example for inspiration, but please read the book if there's something you don't understand about the example. You'll find more info in Chapter 15. Note that this example depends on ImageTypes, MyImageRenderListener, and maybe some other examples.

Keywords for this example: Existing PDFs, Basic building blocks > Image, Image > java.awt.Image, Image > retrieving images, Parsing PDF > extracting images

If you want this example to work, you need the following jars: iText.jar

This example uses the following resources: bruno_ingeborg.jpg, map.jp2, info.png, close.bmp, movie.gif, butterfly.wmf, animated_fox_dog.gif, marbles.tif, amb.jb2, hitchcock.png.