Monday, October 28, 2013

Creating PDF in spring MVC

Maven Dependency :

Add following dependency in your pom.xml 
        
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.3.4</version>
        </dependency>


Controller code :

    @RequestMapping(value = "/generatePDF/{empId}",method = RequestMethod.GET)
    private void downloadPDF(@PathVariable Integer empId,
                                    HttpServletResponse response,
                                    HttpServletRequest request, ModelMap model) 
                                    throws IOException {
        
        List<TaskEntry> taskEntryList =  taskEntryService.retrieveAllTask(empId);\
       //here TaskEntry is your Domain of respective class
       //here taskEntryService is your service layer from which you are accessing Data.
       String orignalFileName="sample.pdf";

        try {
            Document document = new Document();
            response.setHeader("Content-Disposition", "outline;filename=\"" +orignalFileName+ "\"");
            PdfWriter.getInstance(document, response.getOutputStream());

            document.open();
            document.add(createFirstTable(taskEntryList ));
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }






public PdfPTable createFirstTable(List<TaskEntry> taskEntryList ) throws ParseException {
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
        String fromDate=sdf.format(pdfForm.getFromDate());
        String toDate=sdf.format(pdfForm.getToDate());
        // a table with three columns
        PdfPTable table = new PdfPTable(2);
        // the cell object
        PdfPCell cell;
        // we add a cell with colspan 3
        cell = new PdfPCell(new Phrase("TASK DETAILS"));
        cell.setColspan(2);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("From"+fromDate+"TO"+toDate));
        cell.setColspan(2);
        table.addCell(cell);
        table.addCell("DATE:");
        table.addCell("TASK:");
        for(TaskEntry taskEntry: taskEntryList)  
       {
           table.addCell(taskEntry.task);
        }
        return table;
    }

For any query Do comment

1 comment:

  1. HTTP Status 415 -

    type Status report

    message

    description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().

    ReplyDelete