How to add an image to PDF in Java applications

This article will demonstrate how to add an image to PDF file by using Spire.PDF for Java in Java applications. When we use page.getCanvas().drawImage() method to draw image to the PDF file, we could set the size and position of the image.

import com.spire.pdf.*;

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

        //Create a Pdf document
        PdfDocument pdf = new PdfDocument();

        //Add one page to the pdf document
        PdfPageBase page = pdf.getPages().add();

        //Load an image
        PdfImage image = PdfImage.fromFile("logo.png");

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

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

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

        String result = "output/DrawImage.pdf";

        //Save the document
        pdf.saveToFile(result, FileFormat.PDF);

Effective screenshot after adding image to PDF:

How to add an image to PDF in Java applications