There some methods of the com.itextpdf.text.Image
class that can be use to scale the image. These methods include the following: scaleAbsolute()
, scaleAbsoluteWidth()
, scaleAbsoluteHeight()
, scalePercent()
and scaleToFit()
.
package org.kodejava.example.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 = "other-sample/src/main/resources/java.gif";
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
<!-- http://repo1.maven.org/maven2/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
If I need to scale the image to 794 px (width) and 559 px (height), what should I need to use, just like 100f, 200f?