Insert Images in PDF in Java

Picture is a vital a part of PDF paperwork, and inserting photographs at acceptable positions on a PDF web page could make the doc extra enticing. This text will share tips on how to insert a picture into an exixting PDF doc utilizing Free Spire.PDF for Java.

Import Jar Dependency (2 Strategies)

Methodology 1: Obtain the free library and unzip it. Then add the Spire.Pdf.jar file to your Java utility as dependency.
Methodology 2: Straight add the jar dependency to maven challenge by including the next configurations to the pom.xml file.

        <url> material/teams/public/</url>
Enter fullscreen mode

Exit fullscreen mode

Pattern Code

Free Spire.PDF for Java supplies the web page.getCanvas().drawImage() technique so as to add photographs to the PDFs when creating in addition to insert photographs into current PDFs. The next code reveals tips on how to insert a picture into an exixting PDF doc, and to keep away from masking the textual content content material, I set the transparency to the inserted picture.

import com.spire.pdf.*;

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

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

        //Load the PDF doc from disk

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

        //Load a picture
        PdfImage picture = PdfImage.fromFile("C:CustomersAdministratorDesktopOlympics.jpg");

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

        //Outline a place to attract picture
        double x = (web page.getCanvas().getClientSize().getWidth()-width) /2;
        float y = 300f;

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

        //Draw picture on web page canvas
        web page.getCanvas().drawImage(picture, x, y, width, peak);

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

Exit fullscreen mode

Add a Comment

Your email address will not be published. Required fields are marked *