Friday, 21 October 2016

Itext: Image object

Image class is used to add images to PDF document. Let me try to add some image to PDF document.

Image image1 = Image.getInstance("lion.jpeg");
document.add(image1);

Above statements adds an image to PDF document.
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

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

public class TestImage {
  public static void main(String args[]) throws DocumentException, MalformedURLException, IOException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("my_images.pdf"));
    document.open();

    Image image1 = Image.getInstance("lion.jpeg");
    document.add(image1);

    document.add(new Paragraph("\n\n"));

    String imageUrl = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7FbvPS4KetmkmLCmmAttnMdAHFwW6QktGMrDOh2gBmGGlOU2q2IGFRtsTd7C61tVgV5_hypbzpuZm6ZqzujN6Zva0uPfH39LS25spURGXuttQi8mgYLndgdcpcewn1I42X4vsvnqWM5Ry/s1600/Flying+Car.jpg";
    Image image2 = Image.getInstance(new URL(imageUrl));
    image2.scalePercent(40);
    document.add(image2);

    document.close();
  }
}


Run above application, you can able to see following kind of pdf document.




Previous                                                 Next                                                 Home

No comments:

Post a Comment