PDF creation using iText – An example

The main class:

PdfGnerator.java

package com.matttiz.itext.pdf.generator;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.xml.parsers.ParserConfigurationException;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.matttiz.itext.pdf.vo.AddressVO;
import com.matttiz.itext.pdf.vo.GoogleMapBean;

public class PdfGenerator {

	protected static Font smallfont = new Font(Font.HELVETICA, 8, Font.NORMAL);
	protected static Font middlefont = new Font(Font.HELVETICA, 8, Font.BOLD);
	protected static Font sealfont = new Font(Font.HELVETICA, 6, Font.NORMAL);
	protected static Font bigfont = new Font(Font.HELVETICA, 12, Font.BOLD);

	public byte[] createTable(Document document, AddressVO addressVO, List<GoogleMapBean> googleMapBeanList)
			throws IOException, DocumentException, ParserConfigurationException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		PdfWriter.getInstance(document, baos);
		document.open();
		try {
			HeaderFooter header = new HeaderFooter(new Paragraph("This is the Document Header", FontFactory.getFont("Arial", 7)),
					true);
			document.setHeader(header);
			PdfPCell headerDetail = new PdfPCell(headerSection());
			PdfPTable additionTable = new PdfPTable(1);
			headerDetail.setBorder(0);
			additionTable.addCell(new PdfPCell(headerDetail));

			PdfPCell addressDetailsSectionCell = new PdfPCell(addressDetailsSection(addressVO));
			addressDetailsSectionCell.setBorder(0);
			additionTable.addCell(new PdfPCell(addressDetailsSectionCell));

			PdfPCell googleBeanListCell = new PdfPCell(googleMapSection(googleMapBeanList));
			googleBeanListCell.setBorder(0);
			additionTable.addCell(new PdfPCell(googleBeanListCell));

			additionTable.setTotalWidth(1024);
			additionTable.setWidthPercentage(100);
			additionTable.completeRow();
			document.add(additionTable);
		} catch (BadElementException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		document.close();
		return baos.toByteArray();
	}

	private PdfPTable headerSection() throws IOException, BadElementException {
		PdfPTable additionTable = new PdfPTable(6);
		PdfPCell imageCell = new PdfPCell();
		imageCell.setBorder(0);
		InputStream inps = this.getClass().getClassLoader().getResourceAsStream("mattiz.properties");
		Properties cache = new Properties();
		cache.load(inps);
		String imageUrl = cache.getProperty("MattizLogoLocation");
		Image img = Image.getInstance(imageUrl);
		if (img.getScaledWidth() > 70 || img.getScaledHeight() > 70) {

			img.scaleToFit(50, 50);
		}
		imageCell = new PdfPCell(img);
		imageCell.setBorder(0);
		additionTable.addCell(imageCell);
		PdfPTable imageAndHeaderTable = new PdfPTable(1);
		Color darkCyan = new Color(0, 139, 139);
		Font fontColor = new Font(BaseFont.FONT_TYPE_T1, 12f, 1, darkCyan);
		PdfPCell header1Cell = new PdfPCell(new Paragraph("Example iText PDF With Logo, Array and Individual Cells", fontColor));
		header1Cell.setBorder(0);
		header1Cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
		imageAndHeaderTable.addCell(header1Cell);
		PdfPCell header2Cell = new PdfPCell(
				new Paragraph("Cuppajava Mattiz", middlefont));
		header2Cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
		header2Cell.setBorder(0);
		imageAndHeaderTable.addCell(header2Cell);
		PdfPCell header3Cell = new PdfPCell(new Paragraph("Tips from A Mentor to His Protege", smallfont));
		header3Cell.setBorder(0);
		header3Cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
		imageAndHeaderTable.addCell(header3Cell);
		PdfPCell layoutCell = new PdfPCell(imageAndHeaderTable);
		layoutCell.setBorder(0);
		layoutCell.setColspan(5);
		additionTable.addCell(layoutCell);
		return additionTable;
	}

	private PdfPTable addressDetailsSection(AddressVO addressVO) throws IOException, BadElementException {
		PdfPTable additionTable = new PdfPTable(3);

		PdfPCell c001 = new PdfPCell(new Paragraph(" ", middlefont));
		c001.setColspan(3);
		c001.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
		c001.setBorder(0);
		additionTable.addCell(c001);

		PdfPCell c01 = new PdfPCell(new Paragraph("Postal Address", middlefont));
		c01.setColspan(3);
		c01.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
		c01.setBorder(0);
		additionTable.addCell(c01);

		PdfPCell c02 = new PdfPCell(new Paragraph("____________", middlefont));
		c02.setColspan(3);
		c02.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
		c02.setBorder(0);
		additionTable.addCell(c02);

		PdfPCell c1 = new PdfPCell(getLabelAndDataParagraph("Address Line 1: ", addressVO.getAddressLine1()));
		c1.setBorder(0);
		additionTable.addCell(c1);
		PdfPCell c2 = new PdfPCell(getLabelAndDataParagraph("Address Line 2: ", addressVO.getAddressLine2()));
		c2.setBorder(0);
		additionTable.addCell(c2);
		PdfPCell c3 = new PdfPCell(getLabelAndDataParagraph("City: ", addressVO.getCity()));
		c3.setBorder(0);
		additionTable.addCell(c3);

		PdfPCell c4 = new PdfPCell(getLabelAndDataParagraph("State: ", addressVO.getState()));
		c4.setBorder(0);
		additionTable.addCell(c4);

		PdfPCell c5 = new PdfPCell(getLabelAndDataParagraph("State: ", addressVO.getState()));
		c5.setBorder(0);
		additionTable.addCell(c5);

		PdfPCell c6 = new PdfPCell(getLabelAndDataParagraph("Country: ", addressVO.getCountry()));
		c6.setBorder(0);
		additionTable.addCell(c6);

		PdfPCell c7 = new PdfPCell(getLabelAndDataParagraph("Pin Code: ", addressVO.getPinCode()));
		c7.setBorder(0);
		additionTable.addCell(c7);

		PdfPCell c8 = new PdfPCell(getLabelAndDataParagraph("Land Mark: ", addressVO.getLandMark()));
		c8.setBorder(0);
		additionTable.addCell(c8);
		return additionTable;
	}

	private PdfPTable googleMapSection(List<GoogleMapBean> googleMapBeanList) throws IOException, BadElementException {
		PdfPTable additionTable = new PdfPTable(3);
		PdfPCell titleCell = new PdfPCell(new Paragraph("Geographical Locations", middlefont));
		titleCell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
		titleCell.setColspan(3);
		titleCell.setBorder(0);
		additionTable.addCell(titleCell);
		PdfPTable subTable2 = null;
		PdfPCell headerCell1 = new PdfPCell(new Paragraph("Location", middlefont));
		headerCell1.setColspan(1);
		additionTable.addCell(headerCell1);
		PdfPCell headerCell2 = new PdfPCell(new Paragraph("Latitude", middlefont));
		headerCell2.setColspan(1);
		additionTable.addCell(headerCell2);
		PdfPCell headerCell3 = new PdfPCell(new Paragraph("Longitude", middlefont));
		headerCell3.setColspan(1);
		additionTable.addCell(headerCell3);
		if (googleMapBeanList.size() > 0) {
			subTable2 = new PdfPTable(3);
			for (GoogleMapBean googleMapBean : googleMapBeanList) {
				PdfPCell locationInnerCell = new PdfPCell(new Paragraph(googleMapBean.getLocation(), smallfont));
				locationInnerCell.setColspan(1);
				subTable2.addCell(locationInnerCell);
				PdfPCell latitudeInnerCell = new PdfPCell(new Paragraph(googleMapBean.getLatitude() + "", smallfont));
				latitudeInnerCell.setColspan(1);
				subTable2.addCell(latitudeInnerCell);
				PdfPCell longitudeInnerCell = new PdfPCell(new Paragraph(googleMapBean.getLongitude() + "", smallfont));
				longitudeInnerCell.setColspan(1);
				subTable2.addCell(longitudeInnerCell);
			}
		} else {
			subTable2 = new PdfPTable(3);
			PdfPCell blankCell = new PdfPCell(new Paragraph("No Records Found", smallfont));
			blankCell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
			blankCell.setBorder(0);
			blankCell.setColspan(3);
			subTable2.addCell(blankCell);
		}
		PdfPCell subTableCell = new PdfPCell(subTable2);
		subTableCell.setColspan(3);
		additionTable.addCell(subTableCell);
		return additionTable;
	}

	private Paragraph getLabelAndDataParagraph(String label, String data) {
		Chunk chunk1 = new Chunk(label, middlefont);
		Chunk chunk2 = new Chunk(data, smallfont);
		Paragraph merged = new Paragraph();
		merged.add(chunk1);
		merged.add(chunk2);
		return merged;
	}

	public static void main(String[] args) {
		try {
			Document document = new Document();
			PdfWriter.getInstance(document, new FileOutputStream(".\\output\\data.pdf")).setStrictImageSequence(true);
			AddressVO addressVO = new BeanPopulatorUtil().populateAddress();
			List<GoogleMapBean> googleMapBeanList = new BeanPopulatorUtil().populateGoogleMapLocations();//new ArrayList();
			new PdfGenerator().createTable(document, addressVO, googleMapBeanList);
			System.out.println("CREATING... ");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

BeanPopulatorUtil.java that creates the demo data

package com.matttiz.itext.pdf.generator;

import java.util.ArrayList;
import java.util.List;

import com.matttiz.itext.pdf.vo.AddressVO;
import com.matttiz.itext.pdf.vo.GoogleMapBean;

public class BeanPopulatorUtil {

	public List<GoogleMapBean> populateGoogleMapLocations() {
		List<GoogleMapBean> googleMapLocations = new ArrayList<GoogleMapBean>();
		GoogleMapBean googleMapBean1 = new GoogleMapBean();
		googleMapBean1.setLatitude(-33.890542);
		googleMapBean1.setLongitude(151.274856);
		googleMapBean1.setLocation("Bondi Beach");
		GoogleMapBean googleMapBean2 = new GoogleMapBean();
		googleMapBean2.setLatitude(-33.923036);
		googleMapBean2.setLongitude(151.259052);
		googleMapBean2.setLocation("Coogee Beach");
		GoogleMapBean googleMapBean3 = new GoogleMapBean();
		googleMapBean3.setLatitude(-34.028249);
		googleMapBean3.setLongitude(151.157507);
		googleMapBean3.setLocation("Cronulla Beach");
		GoogleMapBean googleMapBean4 = new GoogleMapBean();
		googleMapBean4.setLatitude(-33.80010128657071);
		googleMapBean4.setLongitude(151.28747820854187);
		googleMapBean4.setLocation("Manly Beach");
		GoogleMapBean googleMapBean5 = new GoogleMapBean();
		googleMapBean5.setLatitude(-33.950198);
		googleMapBean5.setLongitude(151.259302);
		googleMapBean5.setLocation("Maroubra Beach");
		googleMapLocations.add(googleMapBean1);
		googleMapLocations.add(googleMapBean2);
		googleMapLocations.add(googleMapBean3);
		googleMapLocations.add(googleMapBean4);
		googleMapLocations.add(googleMapBean5);
		return googleMapLocations;
	}

	public AddressVO populateAddress(){
		AddressVO addressVO = new AddressVO();
		addressVO.setAddressLine1("Park Lane");
		addressVO.setAddressLine2("May Fair");
		addressVO.setCity("London");
		addressVO.setCountry("U.K.");
		addressVO.setLandMark("Big Eye.");
		addressVO.setPinCode("689 585");
		addressVO.setState("England");
		return addressVO;
	}
}

GoogleMapBean.java

package com.matttiz.itext.pdf.vo;

public class GoogleMapBean {

	private double latitude;
	private double longitude;
	private String location;

	public double getLatitude() {
		return latitude;
	}

	public void setLatitude(double latitude) {
		this.latitude = latitude;
	}

	public double getLongitude() {
		return longitude;
	}

	public void setLongitude(double longitude) {
		this.longitude = longitude;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}
}

AddressVO.java

package com.matttiz.itext.pdf.vo;

public class AddressVO {

	private String addressLine1;
	private String addressLine2;
	private String city;
	private String state;
	private String country;
	private String pinCode;
	private String landMark;

	public String getAddressLine1() {
		return addressLine1;
	}

	public void setAddressLine1(String addressLine1) {
		this.addressLine1 = addressLine1;
	}

	public String getAddressLine2() {
		return addressLine2;
	}

	public void setAddressLine2(String addressLine2) {
		this.addressLine2 = addressLine2;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public String getPinCode() {
		return pinCode;
	}

	public void setPinCode(String pinCode) {
		this.pinCode = pinCode;
	}

	public String getLandMark() {
		return landMark;
	}

	public void setLandMark(String landMark) {
		this.landMark = landMark;
	}

}

mattiz.properties

MattizLogoLocation=resources/cuppajavamattiz.gif

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: