DEV Community

Alexis
Alexis

Posted on

Java - How to Insert, Replace, Remove or Extract Images in PDF

Compared with text, images are usually easier to convey meaning and can make your PDF documents more appealing. Since images play an important role in PDF, knowing how to insert, replace, remove, or extract images from PDF can be a real benefit for every developer. This article will show you how accomplish these tasks in Java by using Free Spire.PDF for Java.

Add Spire.Pdf.jar as dependency

If you are working on a maven project, you can include the dependency in pom.xml file using this:

<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.free</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

If you are not using maven, then you can find the required jar files from the zip file available in this location. Include all the jar files into the application lib folder to run the sample code given in this tutorial.

Insert an Image to PDF at a Specified Location

The drawImage() method is used to draw an image with a specified width and height at a specified position on a PDF page. Therefore, you do not need to resize images in advance before drawing. The following are the main steps to insert an image to a new PDF document in Java.

  • Create a PdfDocument object.
  • Add a page to PDF using PdfDocument.getPages().add() method.
  • Load an image using PdfImage.fromFile() method.
  • Specify the image size and position in the page.
  • Draw the image on the page using PdfPageBase.getCanvas.drawImage() method.
  • Save the document to a PDF file.
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;

public class InsertImage {

    public static void main(String[] args) {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Set page margins
        doc.getPageSettings().setMargins(30);

        //Add a page
        PdfPageBase page = doc.getPages().add();

        //Load an image from path
        PdfImage image = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\java-logo.jpg");

        //Specify the image width and height in PDF
        float width = image.getWidth() * 0.5f;
        float height = image.getHeight() * 0.5f;

        //Specify a position to draw image
        double x = 0f;
        float y = 0f;

        //Draw image on page canvas
        page.getCanvas().drawImage(image, x, y, width, height);

        //Save the document
        doc.saveToFile("output/InsertImage.pdf", FileFormat.PDF);
    }
}
Enter fullscreen mode Exit fullscreen mode

InsertImage

Replace an Image in PDF with Another Image

To replace an image in PDF, use replaceImage() method. This method will automatically resize the new image replaced in so that it does affect the readability of other elements surrounded. The following are the steps.

  • Create a PdfDocument object.
  • Load an existing PDF document using PdfDocument.loadFromFile() method.
  • Get a specific page using PdfDocument.getPages().get() method.
  • Load an image using PdfImage.fromFile() method.
  • Replace a specific image in the document with the new image using PdfDocument.replaceImage() method.
  • Save the document to a PDF file.
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;

public class ReplaceImage {
    public static void main(String[] args) {

        //Load the PDF file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Java-Programming.pdf");

        //Get the first page
        PdfPageBase page = doc.getPages().get(0);

        //Load an image
        PdfImage image = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\java-logo.png");

        //Replace the first image in the first page with the loaded image
        page.replaceImage(0, image);

        //Save the file
        doc.saveToFile("output/ReplaceImage.pdf", FileFormat.PDF);
    }
}
Enter fullscreen mode Exit fullscreen mode

replaceImage

Remove a Specified Image in PDF

An image in a PDF document can be easily removed by using deleteImage() method. Here come the steps.

  • Create a **PdfDocument **object.
  • Load an existing PDF document using PdfDocument.loadFromFile() method.
  • Get a specific page using PdfDocument.getPages().get() method.
  • Delete a particular image by its index using PdfPageBase.deleteImage(int imageIndex) method.
  • Save the document to a PDF file.
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

public class RemoveImage {
    public static void main(String[] args) {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Load the sample PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Java-Programming.pdf");

        //Get the specified page
        PdfPageBase page = doc.getPages().get(0);

        //Delete a particular image by its index
        page.deleteImage(0);

        //Save the file
        doc.saveToFile("output/DeleteImage.pdf", FileFormat.PDF);
    }
}
Enter fullscreen mode Exit fullscreen mode

RemoveImage

Extract Images from PDF

Images of a PDF page can be extracted by using extractImages() method. The following are the steps to extract all images from a PDF document using Free Spire.PDF.

  • Create a PdfDocument object.
  • Load an existing PDF document using PdfDocument.loadFromFile() method.
  • Get a specific page using PdfDocument.getPages().get() method.
  • Loop through all the pages in the document, and use PdfPageBase.extractImages() method to extract images from a specific page.
  • Save the images in a local folder as .png files.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

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

public class ExtractImages {

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

        //Create a PdfDocument instance
        PdfDocument doc = new PdfDocument();

        //Load a PDF sample file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Java-Programming.pdf");

        //Declare an int variable
        int index = 0;

        //Loop through all pages
        for (Object page : doc.getPages()) {

             PdfPageBase pageBase = (PdfPageBase) page;

            //Extract images from the given page
            for (BufferedImage image : pageBase.extractImages()) {

                //Specify the file path and name
                File output = new File("C:\\Users\\Administrator\\Desktop\\ExtractedImages\\" + String.format("Image_%d.png", index++));

                //Save images as .png files
                ImageIO.write(image, "PNG", output);
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

ExtractImage

Discussion (0)