How to insert an Image in to pdf file using Itextpdf

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("https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-zLiwapTbIvBM0Ftt4IYOatGLgnEJkW9qSTFuN89256U8ngTA5_T4uXCDyboI-LQ4bKPTT4LWP3PhHVFeTbgTSPcQ6wdw_QOtuuoAxAFPyvr5SLZHWi61iMSzYDNUL09FeSBEeDaDoium/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

No comments:

Post a Comment

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts