Sunday, February 10, 2013

Export to PDF using spring 3.2 & itextpdf-5.3.4


We used to extends AbstractPdfView an override the method protected void buildPdfDocument(Map model, Document document, PdfWriter writer, HttpServletRequest   request, HttpServletResponse response), But not anymore if we are using latest itextpdf Library. So in this class there is nothing spring specific, the spring in title is misnomer.

Controller class:

GeneratePdf.java :

package com.spring.package.controller;

import java.io.File;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

@Controller
public class GeneratePdf{
      
       @RequestMapping(value = "/report.htm")
       public void pdfReport(ModelMap model, HttpServletResponse response, HttpServletRequest     request, OutputStream outputStream) throws Exception
       {
              response.setContentType("application/pdf");
              response.setHeader("Content-Disposition", "attachment; filename=file.pdf");
             
              Document document = new Document();
              PdfWriter.getInstance(document, outputStream);
              document.open();

              document.addTitle("Bank Statement");
              document.addSubject("Bank Statement");
              document.addKeywords("Report, PDF, iText");
              document.addAuthor("Satyam");
              document.addCreator("Satyam");

              document.add(new Paragraph(" "));
              document.add(new Paragraph(" "));
              document.add(new Paragraph(" "));

              Map<String,String> data = new HashMap<String,String>();
              data.put("1/20/2010", "$100,000");
              data.put("1/21/2010", "$200,000");
              data.put("1/22/2010", "$300,000");
              data.put("1/23/2010", "$400,000");
              data.put("1/24/2010", "$500,000");
             
              PdfPTable  table = new PdfPTable(2);
              table.addCell("Month");
              table.addCell("Amount");
             
              for (Map.Entry<String, String> entry : data.entrySet()) {

                     table.addCell(entry.getKey());
                     table.addCell(entry.getValue());
                    
        }
             
              document.add(table);
              document.close();
             
       }
}

In this method we can modularize the creation of pdf in some other utility class and will call it in our controller.

Call the above controller from your jsp by three ways:

1.  Form Submit
<form:form method="POST" commandName="user" action="report.htm">
       <table>
              <tr><td colspan="2"><input type="submit" value="show pdf"></div></td></tr>
       </table>
</form:form>

2. Ajax Call
<input type="button" value="Generate Pdf" onclick="doAjaxPost()">

Script Entry :

function doAjaxPost() { 
         // get the form values 
         var name = $('#name').val();
         var data;
         var url = "/SpringExportPdf/report.htm";
         $.ajax({

                type: "POST", url: url,
                data: "name=" + name, success: function(response, status, xhr){
                  var ct = xhr.getResponseHeader("content-type") || "";
                  if (ct.indexOf('xml') > -1) {
                         alert("xml");
                    // handle xml here
                  }
                  if (ct.indexOf('pdf') > -1) {
                     window.open(url);
                     //alert("pdf");
                  }   
                },
                   error: function(error, status){
                     window.alert("Problem retrieving PDF.\nThe error status is: " + status);
                 }
              });
       } 

For those who are trying to generate or retrieve the pdf file from ajax call must know that in the end you will have to hit the GET request only because ajax response only gives you text.

3.  Simple Get Call

<a href="/SpringExportPdf/report.htm">Show Pdf</a>


And we are done.


3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Why do I still have error message says "Missing artifact com.itextpdf:itextpdf:jar:5.3.5" even though I put

      dependency
      groupId com.itextpdf /groupId
      artifactId itextpdf /artifactId
      version 5.3.5 /version
      /dependency

      Delete
    2. Try different version, like 5.3.4.
      It might be due to the unavailability of the version you are trying in central repository.

      Delete