【问题标题】:Getting error in generating pdf file in java spring在java spring中生成pdf文件时出错
【发布时间】:2018-06-01 13:27:25
【问题描述】:

我正在使用 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 在此我们通过服务层中的 Spring Data Repository 根据财政年度 ID 和班级 ID 获取数据

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

【问题讨论】:

  • 你想达到什么目的,你遇到了什么错误?您的 pdf 生成方法效果很好。试图将 pdf 文件添加到您的回复中或只是下载到磁盘? @bkumar
  • 我没有从数据库中获取 pdfcell 名称和数据
  • 据我了解,您正在尝试提供数据来填写表格。我提供了一个模拟数据,而不是您的 pdfList 从存储库 List&lt;AdmissionResultDetailEntity&gt; pdfList=resultDeclarationRepository.findByFinancialYearIdAndClassId(financialYearId, classId); 检索,它运行良好。
  • 我想您应该专注于从您的源中获取数据。在你的 for 循环中定义这个 ResultDeclarationDTO 的目的是什么。你甚至不使用任何地方。除此之外,您的代码正在运行

标签: java jquery spring jsp spring-mvc


【解决方案1】:

您的控制器代码有问题。您没有写入文件作为响应。

pdf 文件可能在服务器上生成,但未在响应中给出。我相信 "Student Result Details" 是创建的文件的名称。

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

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

希望对您有所帮助。享受:)

【讨论】:

  • 尊敬的先生,此代码不能作为文件输出流和响应都需要被 try -catch 方法包围,但它显示运行时错误
  • 感谢@bkumar 试用,但这只是一个想法,需要在那个地方做些什么。我相信您可以在使其工作时捕获异常。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多