DEV Community


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.

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.*;

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

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

        //Load the PDF document from disk

        //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

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

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


Top comments (0)

Dark Mode

🌚 Friends don't let friends browse without dark mode.

Just kidding, it's a personal preference. But you can change your theme, font, etc. in your settings.