1

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.

1

2 Answers 2

2

Your code to download is missing also that depends on file created is publicly available via your HTTP server or servlet container you can simply redirect to via response.sendRedirect(). If it's not, you'll need to manually copy it to response output stream:

Add the below code to your code.

OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
    out.write(buffer, 0, length);
}
in.close();
out.flush();

You'll need to handle the appropriate exceptions, of course.

Sign up to request clarification or add additional context in comments.

Comments

1

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.