How to read pdf document using Java and Itext

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 read a simple 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 read pdf


Place your pdf file in the project folder and give the file name accordingly.

package com.pretech;
import java.io.IOException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
public class JavaPDFReaderExample {
	public static void main(String[] args) {
		try {
			PdfReader reader = new PdfReader("J2EEMATERIAL.pdf");
			System.out.println("Total pages " + reader.getNumberOfPages());
			String page = PdfTextExtractor.getTextFromPage(reader, 2);
			System.out.println("PDF contents:\n\n" + page + "\n\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

3. Output



Total pages 60
PDF contents:

EJB Architecture        34
Types of Beans        35
Session Beans        36
- Stateless session beans      36
- State ful session bean      37
Entity bean         39
Life cycle of Entity Bean       40
Database synchronization       40
Transactions         42
Transaction attributes       43
Bean managed transacation      46
JDBC Transactions        47
JTA Transactions        47
Handling Exceptions       48
Bean-bean Communication      49
Security          50
Understanding EJB Security      51
Authorization        52
JNDI          55

How to get Package information for a given class in java

Example

package com.pretech;
public class PackageInfoExample {
	public static void main(String[] args) {
		Class<String> clazz = String.class;
		Package pack = clazz.getPackage();
		System.out.println(pack);
		System.out.println(pack.getImplementationTitle());
		System.out.println(pack.getName());
		System.out.println(pack.getSpecificationTitle());
	}
}

Output



package java.lang, Java Platform API Specification, version 1.7
Java Runtime Environment
java.lang
Java Platform API Specification


How to get class loaded location in Java

Example

package com.pretech;
import java.security.CodeSource;
public class ClassLoadLocation {
	public static void main(String[] args) {
		Class<ClassLoadLocation> clazz = ClassLoadLocation.class;
		CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
		System.out.println(clazz.getName()+ " class is loaded from : " + codeSource.getLocation());
	}
}

Output



com.pretech.ClassLoadLocation class is loaded from : file:/D:/Projects/stsworkspace/core-java/target/classes/


How to create Excel file using JExcel

JExcel is an open source API that allows to create and modify Excel documents in java. In this example we will see how to create a simple Excel file and adding values using JExcel.

1. Create a Maven project and add below dependency.

                  <dependency>
			<groupId>net.sourceforge.jexcelapi</groupId>
			<artifactId>jxl</artifactId>
			<version>2.6.12</version>
		</dependency>

2. Create a Main program to create Excel file

package com.pretech;
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Workbook;
import jxl.write.Boolean;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class JExcelSimpleExample {
	public static void main(String[] args) {
		WritableWorkbook workbook;
		try {
			//Creating WorkBook
			workbook = Workbook.createWorkbook(new File("JExcelExample.xls"));
			//Creating sheet
			WritableSheet sheet = workbook.createSheet("STUDENT_DETAILS", 0);
			//Addding cells
			sheet.addCell(new Label(0, 0, "STUDENT_ID"));
			sheet.addCell(new Label(1, 0, "STUDENT_NAME"));
			sheet.addCell(new Label(2, 0, "STUDENT_AGE"));
			sheet.addCell(new Label(3, 0, "EHS"));
			sheet.addCell(new Label(0, 1, "01"));
			sheet.addCell(new Label(1, 1, "SHIVA"));
			sheet.addCell(new Number(2, 1, 12));
			sheet.addCell(new Boolean(3, 1, true));
			sheet.addCell(new Label(0, 2, "02"));
			sheet.addCell(new Label(1, 2, "SANTHOSH"));
			sheet.addCell(new Number(2, 2, 11));
			sheet.addCell(new Boolean(3, 2, false));
			//Getting cell values
			Cell cell1 = sheet.getCell(0,1); 
		    Cell cell2 = sheet.getCell(1,1); 
		    Cell cell3 = sheet.getCell(2,1); 
		    Cell cell4 = sheet.getCell(3,1); 
		    
		    System.out.println(cell1.getContents()+"  "+cell2.getContents()+"  "+cell3.getContents()+"  "+cell4.getContents());
			workbook.write();
			workbook.close();
			System.out.println("Student Details file created");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RowsExceededException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WriteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

3. Output

Console

01  SHIVA  12  true
Student Details file created

JExcelExample.xls

image

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

How to create Calendar event in java ?

iCal4j is a Java API that provides support for the iCalendar specification. Here is one simple example to create calendar file using Ical4j.

1. Create a Maven project and add below dependency.

	         <dependency>
			<groupId>org.mnode.ical4j</groupId>
			<artifactId>ical4j</artifactId>
			<version>1.0.2</version>
		</dependency>

2. Create a Main class

package com.pretech;
import java.io.FileOutputStream;
import java.util.Date;
import net.fortuna.ical4j.data.CalendarOutputter;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.property.CalScale;
import net.fortuna.ical4j.model.property.ProdId;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Version;
import net.fortuna.ical4j.util.UidGenerator;
public class JavaCalendarExample {
	public static void main(String args[]) {
		try {
		
			Date sdata=new Date("01-JAN-2014");
			Date edata=new Date("01-FEB-2014");
			DateTime startTime = new DateTime(sdata.getTime());
			DateTime endTime = new DateTime(edata.getTime());
			VEvent newyearProgram = new VEvent(startTime, endTime, "New Year");
			net.fortuna.ical4j.model.Calendar cal = new net.fortuna.ical4j.model.Calendar();
			cal.getProperties()
					.add(new ProdId(
							"-//Mozilla.org/NONSGML Mozilla Calendar V1.1//EN"));
			cal.getProperties().add(Version.VERSION_2_0);
			cal.getProperties().add(CalScale.GREGORIAN);
			UidGenerator ug = new UidGenerator("uidGen");
			Uid uid = ug.generateUid();
			newyearProgram.getProperties().add(uid);
			cal.getComponents().add(newyearProgram);
			System.out.println("Calendar created "+cal.toString());
			CalendarOutputter out = new CalendarOutputter();
			out.output(cal, new FileOutputStream("C:\\newyear.ics"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

3. Output


1. Console :



Calendar created BEGIN:VCALENDAR
PRODID:-//Mozilla.org/NONSGML Mozilla Calendar V1.1//EN
VERSION:2.0
CALSCALE:GREGORIAN
BEGIN:VEVENT
DTSTAMP:20131124T094411Z
DTSTART:20140101T000000
DTEND:20140201T000000
SUMMARY:New Year
UID:20131124T094411Z-uidGen@fe80:0:0:0:c925:b5ba:6c70:2626%10
END:VEVENT
END:VCALENDAR


2. Open c:\newyear.ics  



image

How to create chart in Java?

JFreeChart Java chart library that makes it easy for developers to display professional quality charts in their applications. In this example we will see how to create a simple vertical bar chart using JFreeChart.

Example

package com.pretech;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
public class JavaVerticalBarExample {
	public static void main(String[] args) {
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		dataset.setValue(40, "Phone", "Apple");
		dataset.setValue(45, "Phone", "Samsung");
		dataset.setValue(38, "Phone", "Sony");
		dataset.setValue(17, "Phone", "Nokia");
		dataset.setValue(12, "Phone", "LG");
		JFreeChart chart = ChartFactory.createBarChart("Phone Sales chart",
				"Phone", "Sales", dataset, PlotOrientation.VERTICAL, false,
				true, false);
		ChartFrame chartFrame = new ChartFrame(
				"Pretech shop Phone Sales chart", chart);
		chartFrame.setVisible(true);
		chartFrame.setSize(500, 400);
	}
}

Output



image


How to run external application from java

Java Runtime that allows the application to interface with the environment in which the application is running. The getRunTime().exec() method allows to execute external application from java.

Example

package com.pretech;
import java.io.IOException;
public class JavaRunTimeExample {
	public static void main(String[] args) {
		try {
			Runtime.getRuntime().exec("notepad.exe c:/pretech.txt");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output



image


How to create Barcodes in Java

Itext PDF is an open source API that allows to create bar codes in pdf documents. In this example we will see how to create a simple Code 128 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 barcode

package com.vinod.test;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.Barcode128;
import com.itextpdf.text.pdf.PdfWriter;
public class JavaBarCodeExample {
    public static void main(String[] args) {
        try {
            Document document = new Document(new Rectangle(PageSize.A4));
            PdfWriter writer = PdfWriter.getInstance(document,
                    new FileOutputStream("MYBARCODE.pdf"));
            document.open();
            document.add(new Paragraph("HelloWorld"));
            Barcode128 barcode128 = new Barcode128();
            barcode128.setGenerateChecksum(true);
            barcode128.setCode("KKVINOD.COM");
            document.add(barcode128.createImageWithBarcode(
                    writer.getDirectContent(), null, null));
            document.close();
            System.out.println("PDF file created");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. Output


 

How to create pdf document in java?

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 a simple 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 com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
public class JavaPDFExample {
	public static void main(String[] args) {
		Document document = new Document(PageSize.A4);
		try {
			PdfWriter.getInstance(document, new FileOutputStream(
					"myfirstpage.pdf"));
			document.open();
			Paragraph paragraph = new Paragraph("Hello world..");
			document.add(paragraph);
			document.close();
			System.out.println("PDF file created");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}

3. Output



image


Java EnumMap Example

java.util.EnumMap is one of the specialized implementation of Map interface. It uses enum type as key and all keys must come from the same enum type. Here is one simple example of EnumMap.

Example

package com.pretech;
import java.util.EnumMap;
import java.util.Map;
import java.util.Set;
public class EnumMapExample {
	public static void main(String[] args) {
		Map<Days, String> enumMap = new EnumMap<Days, String>(Days.class);
		enumMap.put(Days.SUNDAY, "Holiday");
		enumMap.put(Days.MONDAY, "Monday");
		enumMap.put(Days.TUESDAY, "Tuesday");
		enumMap.put(Days.WEDNESDAY, "Wednesday");
		Set<Days> keySet = enumMap.keySet();
		for (Days days : keySet) {
			System.out.println("Day is :" + enumMap.get(days));
		}
	}
}
enum Days {
	SUNDAY, MONDAY, TUESDAY, WEDNESDAY
}

Output



Day is :Holiday
Day is :Monday
Day is :Tuesday
Day is :Wednesday

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts