Work with Images in PDF via Java

Manipulate images in PDF document. Use Aspose.PDF for Java to modify PDF documents programmatically

Most popular action with Images in Java

Add Image to PDF Document Using Java Library

In order to add Image in PDF, we’ll use Aspose.PDF for Java API which is a feature-rich, powerful, and easy-to-use conversion API for the Java platform. You can download its latest version directly from Maven and install it within your Maven-based project by adding the following configurations to the pom.xml.

Repository

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java AP</name>
    <url>https://releases.aspose.com/java/repo/</url>
</repository>

Dependency

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>

Add Image to PDF via Java


You need Aspose.PDF for Java to try the code in your environment.

  1. Create a Document object and open the input PDF document.
  2. Get the page you want to add an image.
  3. Add the image into the page’s Resources collection.
  4. Use the GSave operator to save the current graphical state.
  5. Use ConcatenateMatrix operator to specify where the image is to be placed.
  6. Use the Do operator to draw the image on the page.
  7. Use GRestore operator to save the updated graphical state.
  8. Save the PDF file.

Add Image in an Existing PDF File - Java

Example: Java


    Document pdfDocument = new Document(dataDir+ "AddImage.pdf");

    int lowerLeftX = 100;
    int lowerLeftY = 100;
    int upperRightX = 200;
    int upperRightY = 200;

    Page page = pdfDocument.Pages[1];

    FileStream imageStream = new FileStream(dataDir + "aspose-logo.jpg", FileMode.Open);

    page.Resources.Images.Add(imageStream);

    page.Contents.Add(new Aspose.Pdf.Operators.GSave());

    Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
    Matrix matrix = new Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY });

    page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(matrix));
    XImage ximage = page.Resources.Images[page.Resources.Images.Count];

    page.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name));

    page.Contents.Add(new Aspose.Pdf.Operators.GRestore());
    dataDir = dataDir + "AddImage_out.pdf";

    pdfDocument.Save(dataDir);