Search code examples
angularjsspringspring-bootspring-mvcspring-restcontroller

Generate PDF Using Angularjs And RestController


I am created an rest API for generate the PDF file using itext API. Please help me out how to generate this and send to UI for download that PDF.

Here I am Using Angularjs,SpringBoot and Mysql as DB.

    @RequestMapping(value = "/generateGeneralLedgerReportPdf", method = 
     RequestMethod.GET)
    public void generateSalesReportPdf(@RequestParam("ledgerStartDate") 
     String ledgerStartDate,
        @RequestParam("ledgerEndDate") String ledgerEndDate) {

    try {

        SimpleDateFormat simpleDateFormat = new 
      SimpleDateFormat("yyyy-MM-dd");
        Date startDate = 
       simpleDateFormat.parse(ledgerStartDate);
        Date endDate = simpleDateFormat.parse(ledgerEndDate);

        List<GeneralLedger> listLedgerDetails = null;
        int count = 0;

        File file = new File("E:\\GeneralLedgerReport.pdf");

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

        //create PDF
        PdfPTable table = new PdfPTable(6); // 10 columns.
        table.setWidthPercentage(100); //Width 100%


        PdfPCell c1 = new PdfPCell(new Phrase("#"));
        c1.setHorizontalAlignment(Element.ALIGN_LEFT);
        c1.setBackgroundColor(BaseColor.GRAY);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("DATE"));
        c1.setHorizontalAlignment(Element.ALIGN_LEFT);
        c1.setBackgroundColor(BaseColor.GRAY);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("INCOME CATEGORY"));
        c1.setHorizontalAlignment(Element.ALIGN_LEFT);
        c1.setBackgroundColor(BaseColor.GRAY);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("AMOUNT"));
        c1.setHorizontalAlignment(Element.ALIGN_LEFT);
        c1.setBackgroundColor(BaseColor.GRAY);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("EXPENSE CATEGORY"));
        c1.setHorizontalAlignment(Element.ALIGN_LEFT);
        c1.setBackgroundColor(BaseColor.GRAY);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("AMOUNT"));
        c1.setHorizontalAlignment(Element.ALIGN_LEFT);
        c1.setBackgroundColor(BaseColor.GRAY);
        table.addCell(c1);



        listLedgerDetails = generalLedgerService.generateGeneralLedgerPdfByRange(startDate, endDate);

        if (!listLedgerDetails.isEmpty()) {
            for (GeneralLedger ledger : listLedgerDetails) {
                    count ++;

                    Double incomeAmount = ledger.getIncomeAmount();
                    if(incomeAmount==null) {
                        incomeAmount = 0.0d;
                    }

                    Double expenseAmount = ledger.getExpenseAmount();
                    if(expenseAmount==null) {
                        expenseAmount = 0.0d;
                    }

                    table.addCell(String.valueOf(count));
                    table.addCell(String.valueOf(ledger.getLedgerDate()));
                    table.addCell(ledger.getIncomeCategory());
                    table.addCell(String.valueOf(incomeAmount));
                    table.addCell(ledger.getExpenseCategory());
                    table.addCell(String.valueOf(expenseAmount));
            }
        }

        document.add(table);
        document.close();
        writer.close();

    }catch (Exception e) {
        e.printStackTrace();
    }


}

Angularjs

$scope.generateGeneralLedgerReportPdf = function(startDate,endDate){
    $http({
        url: 
 'service/generalLedger/generateGeneralLedgerReportPdf', 
        method: "GET",
        params: {ledgerStartDate:startDate,ledgerEndDate:endDate}
    })
    .success(function(response){ 
        console.log("Success");
    })
    .error(function(response) {
        console.log("Failed");
    });
   };

It is giving me proper OUTPUT but it is storing in local system E: drive. but i want to download in browser window.


Solution

  • I added only these lines of code and it worked for me.

            InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
                    String mimeType = 
              URLConnection.guessContentTypeFromStream(inputStream);
    
                    if(mimeType==null) {
                        mimeType = "application/octet-stream";
                    }
    
                    response.setContentType(mimeType);
                    response.setContentLength((int)file.length());
                    response.setHeader("Content-Disposition",String.format("attachment; fileName=\"%s\"", file.getName()));
    
                    FileCopyUtils.copy(inputStream, response.getOutputStream());