Searching...
Monday, 25 November 2013

How to insert an Image in to pdf file using Itextpdf

10:38

Itext PDF is an open source API that allows to create and modify pdf documents in java. In this example we will see how to create and and insert an image in a pdf document using Itext.

1. Create a Maven project and add below dependency.

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

2. Create a Main program to create pdf

package com.pretech;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
public class JavaPDFImageExample {
	public static void main(String[] args) {
		Document document = new Document(PageSize.A4);
		try {
			PdfWriter.getInstance(document, new FileOutputStream(
					"myfirstpdfimage.pdf"));
			document.open();
			Paragraph paragraph = new Paragraph("Welcome to Mongodb..");
			document.add(paragraph);
			document.add(Image
					.getInstance("http://4.bp.blogspot.com/-GN-IQMgqO_c/UgDl3Tg_yuI/AAAAAAAABQ8/o5_LFDUFd-A/s1600/mongodb-tutorials.png"));
			document.close();
			System.out.println("PDF file created");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

3. Output



image

0 comments: