iText has a variety of API support for image manipulation in PDF file. You can Rotate, Reverse, Scale and do many other operations on an image using the iText library. Lets see how to add image in PDF using iText.
Important class – com.itextpdf.text.Image
Following are the methods that can be used
a)
setRotation(float r) Sets the rotation of the image in radians.
b)
setRotationDegrees(float deg) Sets the rotation of the image in degrees.
c)
scalePercent(float percent) Scale the image to a certain percentage.
d)
scalePercent(float percentX, float percentY) Scale the width and height of an image to a certain percentage.
e)
scaleToFit(float fitWidth, float fitHeight) Scales the image so that it fits a certain width and height.
Example
In the below example we have taken an image and displayed it in various ways.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package com.kscodes.examples.itext; import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.Image; import com.itextpdf.text.pdf.PdfWriter; public class ImageExample1 { public static void main(String args[]) { // Create a Document object Document document = new Document(); try { // Create a PdfWriter instance and use the document to write the pdf // to a specified location PdfWriter.getInstance(document, new FileOutputStream("K:\\Kscodes\\pdf\\itext-image.pdf")); // open the document document.open(); // Get instance of Image and then add it in document Image image = Image.getInstance("K:\\Kscodes\\Images\\java_logo.png"); document.add(image); // Image Rotation test Image image1 = Image.getInstance("K:\\Kscodes\\Images\\java_logo.png"); image1.setRotationDegrees(45); document.add(image1); // Image scaling test Image image2 = Image.getInstance("K:\\Kscodes\\Images\\java_logo.png"); image2.scaleToFit(75, 200); document.add(image2); // close the document document.close(); System.out.println("PDF created at the location !!!"); } catch (Exception e) { System.out.println("Exception occured :: " + e); } } } |
Output