DEV Community

carlwils
carlwils

Posted on

Insert Images in PDF in Java

Image is an important part of PDF documents, and inserting images at appropriate positions on a PDF page can make the document more attractive. This article will share how to insert an image into an existing PDF document using Free Spire.PDF for Java.

Import Jar Dependency (2 Methods)

Method 1: Download the free library and unzip it. Then add the Spire.Pdf.jar file to your Java application as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml file.

<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

Sample Code

Free Spire.PDF for Java provides the PdfPageBase.getCanvas().drawImage() method to add images to the PDFs when creating as well as insert images into existing PDFs. The following code shows how to insert an image into an exixting PDF document, and to avoid covering the text content, I set the transparency to the inserted image.

import com.spire.pdf.*;
import com.spire.pdf.graphics.PdfImage;

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

        //Create PDF document
        PdfDocument pdf = new PdfDocument();

        //Load the PDF document from disk
        pdf.loadFromFile("D:\\Files\\input.pdf");

        //Get a specified page
        PdfPageBase page = pdf.getPages().get(0);

        //Load an image
        PdfImage image = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\Olympics.jpg");

        //Set the width and height of image
        float width = image.getWidth() * 0.75f;
        float height = image.getHeight() * 0.75f;

        //Define a position to draw image
        double x = (page.getCanvas().getClientSize().getWidth()-width) /2;
        float y = 300f;

        //Set image transparency
        page.getCanvas().setTransparency(0.5f);

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

        //Save the document
        pdf.saveToFile("insertImage.pdf", FileFormat.PDF);
        pdf.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

InsertPDFImage

Discussion (0)