Dynamically generate PDF using servlet

Dynamically generate PDF using servlet

To dynamically generate PDF using servlet below are needed:

  • Eclipse 3.2 or above (Download eclipse from here) — We are using Eclipse Kepler for this demo
  • JDK 1.6 or above (Download from here)
  • Tomcat 6 or above (Please follow link to install and configure tomcat in eclipse: Configure and Run Tomcat server in eclipse)
  • We will use itext to generate PDF please download jar form from its website here
  • Note: You could also download project in bottom where itext jar is already included

After all set up and configuration you will see below generated PDF:

Dynamically generate PDF using servlet

Please follow below steps:

  • Create dynamic web project in eclipse name: GeneratePDFReport (Please use this link if you are not familiar how to create dynamic project in eclipse: Create Dynamic Web Project Eclipse)
  • Once you create dynamic project it should look as below structure:

Dynamically generate PDF using servlet

 

  • Create package name com.javahonk inside src folder
  • Create servlet class name ReportServlet.java inside com.javahonk package and copy paste below code:
package com.javahonk;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ReportServlet
 */
@WebServlet("/ReportServlet")
public class ReportServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReportServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, 
     * HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

    final ServletContext servletContext = request.getSession()
            .getServletContext();
    final File tempDirectory = (File) servletContext
            .getAttribute("javax.servlet.context.tempdir");
    final String temperotyFilePath = tempDirectory.getAbsolutePath();

    String fileName = "Generate_Report_"+System.currentTimeMillis()+".pdf";
    response.setContentType("application/pdf");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Cache-Control", "max-age=0");
    response.setHeader("Content-disposition", "attachment; " +
            "filename="+ fileName);

    try {

        GeneratePDF.createPDF(temperotyFilePath+"\\"+fileName);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos = convertPDFToByteArrayOutputStream(
                temperotyFilePath+"\\"+fileName);
        OutputStream os = response.getOutputStream();
        baos.writeTo(os);
        os.flush();
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, 
     * HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request,HttpServletResponse 
            response) throws ServletException, IOException {        
    }

    private static ByteArrayOutputStream 
        convertPDFToByteArrayOutputStream(String fileName) {

        InputStream inputStream = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {

            inputStream = new FileInputStream(fileName);

            byte[] buffer = new byte[1024];
            baos = new ByteArrayOutputStream();

            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return baos;
    }
}

 

  • Please see below line of in above class we will get absolute path from servlet context and will generate our PDF inside this folder and later convert generated PDF to ByteArrayOutputStream then write it OutputStream and show to the user
final File tempDirectory = (File) servletContext
            .getAttribute("javax.servlet.context.tempdir");
    final String temperotyFilePath = tempDirectory.getAbsolutePath();
  • Now create GeneratePDF.java class inside com.javahonk package which will generate PDF file copy paste below code to it:
package com.javahonk;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class CreatePDF {
	
	private static Font TIME_ROMAN = new Font(Font.FontFamily.TIMES_ROMAN, 18,Font.BOLD);
	private static Font TIME_ROMAN_SMALL = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);

	/**
	 * @param args
	 */
	public static Document createPDF(String file) {

		Document document = null;

		try {
			document = new Document();
			PdfWriter.getInstance(document, new FileOutputStream(file));
			document.open();

			addMetaData(document);

			addTitlePage(document);

			createTable(document);

			document.close();

		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return document;

	}

	private static void addMetaData(Document document) {
		document.addTitle("Generate PDF report");
		document.addSubject("Generate PDF report");
		document.addAuthor("Java Honk");
		document.addCreator("Java Honk");
	}

	private static void addTitlePage(Document document)
			throws DocumentException {

		Paragraph preface = new Paragraph();
		creteEmptyLine(preface, 1);
		preface.add(new Paragraph("PDF Report", TIME_ROMAN));

		creteEmptyLine(preface, 1);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
		preface.add(new Paragraph("Report created on "
				+ simpleDateFormat.format(new Date()), TIME_ROMAN_SMALL));
		document.add(preface);

	}

	private static void creteEmptyLine(Paragraph paragraph, int number) {
		for (int i = 0; i < number; i++) {
			paragraph.add(new Paragraph(" "));
		}
	}

	private static void createTable(Document document) throws DocumentException {
		Paragraph paragraph = new Paragraph();
		creteEmptyLine(paragraph, 2);
		document.add(paragraph);
		PdfPTable table = new PdfPTable(3);

		PdfPCell c1 = new PdfPCell(new Phrase("First Name"));
		c1.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(c1);

		c1 = new PdfPCell(new Phrase("Last Name"));
		c1.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(c1);

		c1 = new PdfPCell(new Phrase("Test"));
		c1.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(c1);
		table.setHeaderRows(1);

		for (int i = 0; i < 5; i++) {
			table.setWidthPercentage(100);
			table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
			table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
			table.addCell("Java");
			table.addCell("Honk");
			table.addCell("Success");
		}

		document.add(table);
	}

}

 

  • Create index.jsp inside WebContent folder and copy paste below code:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Generate PDF</title>
</head>
<body>
<form action="ReportServlet">
<input type="submit" value="Generate PDF report">
</form>

</body>
</html>

 

  • Please don’t forget to include itext…..jar which is already included in project below for download.
  • Final project structure should be as below:

Dynamically generate PDF using servlet

 

  • Now we are ready to generate PDF using tomcat server. If you haven’t done tomcat set up in eclipse yet please use this link: Configure and Run Tomcat server in eclipse. Now right click project –>Run As –> Run on server.
  • You will see below jsp page:

Dynamically generate PDF using servlet

 

  • Click Generate PDF report. You will see below pop-up with Open, Save and Cancel button. For demo we have clicked Open button to open generated PDF file:

Dynamically generate PDF using servlet

 

  • Once you clicked Open button finally you will see below generated PDF file:

Dynamically generate PDF using servlet

 

  • That’s it dynamically generate PDF using servlet created successfully.

Dynamically generate PDF using servlet GeneratePDFReport

2 thoughts on “Dynamically generate PDF using servlet”
  1. thanks boss…… this step by step tutorial helped me to clarify, most of my doubts…. code is working fine… keep posting …. welldone..:)

Leave a Reply

Your email address will not be published. Required fields are marked *