使用 Angularjs 和 RestController 生成 PDF

Generate PDF Using Angularjs And RestController

我创建了一个休息 API 用于使用 itext API 生成 PDF 文件。请帮助我了解如何生成此文件并将其发送至 UI 以下载该 PDF。

这里我使用Angularjs、SpringBoot和Mysql作为数据库。

    @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");
    });
   };

它给我正确的输出,但它存储在本地系统 E: 驱动器中。但我想在浏览器中下载 window.

您还缺少要下载的代码,这取决于创建的文件是否可通过您的 HTTP 服务器或 servlet 容器公开获得,您只需通过 response.sendRedirect() 重定向即可。 如果不是,您需要手动将其复制到响应输出流:

将以下代码添加到您的代码中。

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

当然,您需要处理适当的异常。

我只添加了这几行代码,它对我有用。

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