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:

 

  • 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

One thought 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 *