How do I scale an image in PDF document using iText?

The com.itextpdf.text.Image class represent an image of a graphic element such as JPEG, PNG or GIF that can be inserted into a PDF document. There are some methods of the com.itextpdf.text.Image class that can be used to scale the image. These methods include the following: scaleAbsolute(), scaleAbsoluteHeight(), scaleAbsoluteWidth(), scalePercent() and scaleToFit().

These are signatures of those APIs:

  • scaleAbsolute(float newWidth, fload newHeight) – Scales the image to an absolute width and an absolute height.
  • scaleAbsoluteHeight(float newHeight) – Scales the image to an absolute height.
  • scaleAbsoluteWidht(float newWidth) – Scales the image to an absolute width.
  • scalePercent(float percent) – Scales the image to a certain percentage.
  • scalePercent(float percentX, float percentY) – Scales the image to a certain percentage of width and height.
  • scaleToFit(float fitWidth, float fitHeight) – Scales the image to fit a certain width and height.

Here is a code snippet that shows how to use the scaleAbsolute(), scalePercent() and scaleToFit() methods.

package org.kodejava.itextpdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileOutputStream;
import java.io.IOException;

public class ImageScalingDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("ImageScaling.pdf"));
            doc.open();

            // Scale the image to an absolute width and an absolute
            // height
            String filename = "kodejava-itextpdf/src/main/resources/java.png";
            Image image = Image.getInstance(filename);
            image.scaleAbsolute(200f, 200f);
            doc.add(image);

            // The following line to prevent the "Server returned
            // HTTP response code: 403" error.
            System.setProperty("http.agent", "Chrome");

            // Scale the image to a certain percentage
            String url = "https://kodejava.org/wp-content/uploads/2017/01/kodejava.png";
            image = Image.getInstance(url);
            image.scalePercent(200f);
            doc.add(image);

            // Scales the image so that it fits a certain width and
            // height
            image = Image.getInstance(url);
            image.scaleToFit(100f, 200f);
            doc.add(image);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

Maven Central

Wayan

1 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.