在java spring中生成pdf文件时出错

问题描述 投票:2回答:2

我正在使用java spring arch,JSP,jQuery和Ajax生成PDF文件。生成PDF文件,但错误文件已损坏,未正确解码。我面临着如何从实体数据库中设置PDF单元格值的问题。

这是代码

service implementation在这里我必须使用SQL获取数据,即学生姓名,班级名称,标记。所有变量都在实体中,我需要使用实体在pdf单元格中设置数据,似乎我在这里遗漏了一些东西,请指正

 @Override
        public Document getPdfResultDetails(Long financialYearId, Long classId) {

            Document  document =new Document(PageSize.A4);
            try {
                PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("Student Result Details"));
                document.open();
                document.add(new Paragraph("Student Exam Result Details ") );


                PdfPTable table=new PdfPTable(5);
                table.setWidthPercentage(100.0f);
                table.setWidths(new float[] {3.0f, 2.0f, 2.0f, 2.0f, 1.0f});
                table.setSpacingBefore(10f);
                table.setSpacingAfter(10f);
                float[] colWidth={2f,2f,2f};


                PdfPCell studentNameList=new PdfPCell(new Paragraph("Student Name"));
                PdfPCell financialYearList=new PdfPCell(new Paragraph("Financial year"));
                PdfPCell marksObtainedList=new PdfPCell(new Paragraph("Marks Obtained"));
                PdfPCell resultList=new PdfPCell(new Paragraph("Result"));
                PdfPCell classNameList=new PdfPCell(new Paragraph("Class Name"));


                table.addCell(studentNameList);
                table.addCell(financialYearList);
                table.addCell(marksObtainedList);
                table.addCell(resultList);
                table.addCell(classNameList);
                List<ResultDeclarationDTO> resultDeclarationDTO=new ArrayList<ResultDeclarationDTO>();
                List<AdmissionResultDetailEntity> pdfList=resultDeclarationRepository.findByFinancialYearIdAndClassId(financialYearId, classId);
                if (pdfList==null)
                 return null;
                for (AdmissionResultDetailEntity admissionResultDetailEntity :  pdfList){
                    ResultDeclarationDTO resultExamDeclarationDTO=new ResultDeclarationDTO();

                    table.addCell(admissionResultDetailEntity.getObtainMarks()+"");

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


            } catch (DocumentException e) {
                // TODO: handle exception
                e.printStackTrace();
            }catch (FileNotFoundException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            return document;

        }}

controller class在这里我们根据财务年度id和class id获取数据,通过Spring数据存储库在服务层

 @RequestMapping(value = "/downloadStudentResult", method = RequestMethod.GET)
        public ModelAndView downloadStudentResult(HttpServletResponse response,@RequestParam(name = "financialYearId", required = false) Long financialYearId,
                @RequestParam(name = "classId", required = false) Long classId) {

      try {
          Document document=resultDeclarationService.getPdfResultDetails(financialYearId, classId);
          response.setHeader("Content-disposition", "attachment; filename=StudentResult.pdf");
          response.flushBuffer();

    } 

      catch (Exception e) {
        // TODO: handle exception
    }


            return new ModelAndView();
        }
    }

JSP file (jQuery is also being used)

<div align="center">
        <h1>Students Result Document</h1>
        <h3><a href="/downloadStudentResult">Download Students Result Document</a></h3>
    </div>
$(document).ready(function(){


    callDataTableFunction();
    callPdfFileFunction();
    });
function callPdfFileFunction(){
    //$('#dataTableDiv').show();
    $.ajax({
        type: "POST",
        url: "/downloadStudentResult",
        processdata: true,
        success: function(data)
        {
            createPdfFile(data);
        },
        error: function(data){
            showErrorAlert("#showAlert", data);
        }
    }); 
}
java jquery spring jsp spring-mvc
2个回答
1
投票

您的控制器代码存在问题。你没有写文件作为回应。

pdf文件可以在服务器上生成,但不作为响应给出。我相信“学生成绩详细信息”是创建的文件的名称。

在您的控制器代码中执行以下操作:

File pdfFile = new File(<path to pdf>);

response.setContentType("application/pdf");  
response.setHeader("Content-disposition", "attachment; filename=StudentResult.pdf");
response.setContentLength((int) pdfFile.length());

FileInputStream fileInputStream = new FileInputStream(pdfFile);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
    responseOutputStream.write(bytes);
}

希望这有帮助。请享用 :)


0
投票

您可以参考Spring MVC PDF Download在spring mvc中下载pdf文件,但有一点需要注意的是在生成文件之前设置响应content-typeheader,否则您可能会在我面对这个问题时得到一个乱码页面:garblend page in spring mvc

© www.soinside.com 2019 - 2024. All rights reserved.