Skip to main content

How to Extract Images and Image Information from PDF in Java

 PDF files are widely used for storing reports, manuals, e-books, and other documents that combine text and visual content. Besides text, PDF documents often contain various image resources, including charts, diagrams, screenshots, scanned pages, and illustrations.

When processing PDF files programmatically, extracting images is often only part of the requirement. In many cases, developers also need additional information about those images, such as:

  • Which page contains the image
  • How many images exist on each page
  • The width and height of extracted images
  • The relationship between extracted images and the original document

This information is useful in scenarios such as document archiving, content analysis, and image resource management.

This article explains how to extract images from PDF files and retrieve image-related information using Java.


Preparing the Environment

Create a Java project and add the PDF processing dependency through Maven.

Add the following configuration to pom.xml:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>12.9.0</version>
    </dependency>
</dependencies>

Then import the required classes:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.utilities.PdfImageHelper;
import com.spire.pdf.utilities.PdfImageInfo;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

Extract Images from PDF Files

Images in PDF documents are usually stored as page resources. To extract them, load the PDF file, iterate through each page, and retrieve the image information from each page.

The following example extracts all images from a PDF file and saves them as PNG images:

public class ExtractImages {

    public static void main(String[] args) throws Exception {

        PdfDocument pdf = new PdfDocument();

        pdf.loadFromFile("Sample.pdf");

        PdfImageHelper imageHelper = new PdfImageHelper();

        int imageIndex = 0;

        for (int i = 0; i < pdf.getPages().getCount(); i++) {

            PdfPageBase page = pdf.getPages().get(i);

            PdfImageInfo[] imageInfos =
                    imageHelper.getImagesInfo(page);

            if (imageInfos != null) {

                for (PdfImageInfo imageInfo : imageInfos) {

                    BufferedImage image =
                            imageInfo.getImage();

                    ImageIO.write(
                            image,
                            "PNG",
                            new File("Image-" + imageIndex + ".png")
                    );

                    imageIndex++;
                }
            }
        }

        pdf.dispose();
    }
}

After execution, each extracted image will be saved as an independent PNG file.

For example:

Image-0.png
Image-1.png
Image-2.png

This approach is suitable for processing PDF files that contain multiple embedded images, such as reports, brochures, and technical documents.

Get the Number of Images in Each PDF Page

Before extracting images, you may want to check how many images exist in each page.

The following example counts images page by page:

public class CountImages {

    public static void main(String[] args) {

        PdfDocument pdf = new PdfDocument();

        pdf.loadFromFile("Sample.pdf");

        PdfImageHelper imageHelper = new PdfImageHelper();

        for (int i = 0; i < pdf.getPages().getCount(); i++) {

            PdfPageBase page = pdf.getPages().get(i);

            PdfImageInfo[] imageInfos =
                    imageHelper.getImagesInfo(page);

            int count = imageInfos == null ? 0 : imageInfos.length;

            System.out.println(
                    "Page " + (i + 1)
                    + " contains "
                    + count
                    + " images"
            );
        }

        pdf.dispose();
    }
}

Output example:

Page 1 contains 3 images
Page 2 contains 5 images
Page 3 contains 1 images

This allows you to quickly understand how images are distributed throughout a PDF document.

Get Image Dimensions

Besides extracting image files, you can also retrieve the width and height of each image.

This information can help determine image quality or filter images based on specific requirements.

Example:

public class GetImageSize {

    public static void main(String[] args) {

        PdfDocument pdf = new PdfDocument();

        pdf.loadFromFile("Sample.pdf");

        PdfImageHelper imageHelper = new PdfImageHelper();

        for (int i = 0; i < pdf.getPages().getCount(); i++) {

            PdfPageBase page = pdf.getPages().get(i);

            PdfImageInfo[] imageInfos =
                    imageHelper.getImagesInfo(page);

            if (imageInfos != null) {

                for (PdfImageInfo imageInfo : imageInfos) {

                    BufferedImage image =
                            imageInfo.getImage();

                    System.out.println(
                            "Width: "
                            + image.getWidth()
                            + ", Height: "
                            + image.getHeight()
                    );
                }
            }
        }

        pdf.dispose();
    }
}

Output example:

Width: 1200, Height: 800
Width: 640, Height: 480

With image dimensions, you can identify high-resolution images or classify extracted resources for further processing.

Extract Images with Page Information

In practical applications, saving image files alone is often not enough.

For example, a PDF report may contain dozens of images. During later processing, you may need to know which page each image came from.

You can include page numbers in the output filenames:

public class ExtractImagesWithPageInfo {

    public static void main(String[] args) throws Exception {

        PdfDocument pdf = new PdfDocument();

        pdf.loadFromFile("Sample.pdf");

        PdfImageHelper imageHelper = new PdfImageHelper();

        for (int pageIndex = 0;
             pageIndex < pdf.getPages().getCount();
             pageIndex++) {

            PdfPageBase page =
                    pdf.getPages().get(pageIndex);

            PdfImageInfo[] imageInfos =
                    imageHelper.getImagesInfo(page);

            if (imageInfos != null) {

                for (int imageIndex = 0;
                     imageIndex < imageInfos.length;
                     imageIndex++) {

                    BufferedImage image =
                            imageInfos[imageIndex].getImage();

                    String fileName =
                            "Page-"
                            + (pageIndex + 1)
                            + "-Image-"
                            + (imageIndex + 1)
                            + ".png";

                    ImageIO.write(
                            image,
                            "PNG",
                            new File(fileName)
                    );
                }
            }
        }

        pdf.dispose();
    }
}

The generated files will keep their original page references:

Page-1-Image-1.png
Page-1-Image-2.png
Page-2-Image-1.png

This naming approach makes it easier to trace extracted images back to their original locations.

Conclusion

Extracting images from PDF files is not only about saving image files. In real-world applications, information such as image count, dimensions, and page references can be equally important.

By processing PDF pages and retrieving image information in Java, developers can automate image extraction and resource analysis for document management, content analysis, and data processing workflows.

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...