java - 从服务调用 Jasper 文件

标签 java spring pdf

我是 Jasper 的新手,我想尝试从我的应用程序中使用 jasper 生成 pdf 文件。 这是场景:

我在 iReport 中构建了一个文件 (reportEmployee.jrxml),在我的应用程序中,我有一个链接,如果我们单击该链接,我的应用程序将创建 pdf 文件中的报告并将其保存到我的应用程序中本地存储。

我已经尝试过 Excel 和 Word,它可以工作,只有 pdf,我觉得做起来很困惑。

这是代码
1.在jsp文件上

<td><a href="<c:url value ="/savepdf"/>">Save to PDF</a></td>
<td><a href="<c:url value = "/save"/>">Save to Excel</a></td>
<td><a href="<c:url value = "/saveword"/>">Save to Word</a></td>

2. Controller

@RequestMapping("/savepdf")
public String dataEmployeePdf()
{
    employeeManager.dataEmployeePDFDownload();
    return "employ/editEmployeeList";
}

3. on EmployeeManagerImpl(EmployeeManager的实现)

@Override
public void dataEmployeePDFDownload() {
    // TODO Auto-generated method stub
    try
    {

        File file = new File("report/reportEmployee.jrxml"); 
        String absolutePath = file.getAbsolutePath();
        InputStream input = new FileInputStream(new File(absolutePath));
        JasperReport jasperReport = JasperCompileManager.compileReport(input);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null);
        JasperExportManager.exportReportToPdf(jasperPrint);
    }
    catch(JRException ex)
    {
        ex.getMessage();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
} 

我不需要通过我的应用程序从数据库发送数据,因为我已经制作了该文件(employeeReport.jrxml)来自动从数据库获取数据。 与保存到word和保存到excel的情况相同,当我们单击该链接时,它会将文件写入本地存储,如下所示

enter image description here

有人可以帮助我吗?我希望我没有转发此内容 谢谢

最佳答案

要下载文件,您必须将内容传递给 response.getOutputStream()。您可以向响应设置其他信息,例如用于设置文件名、编码等的 header 信息,或设置文件内容类型。

 @RequestMapping("/savepdf")
    public void dataEmployeePdf(HttpServletResponse response) {
        try {

            File file = new File("report/reportEmployee.jrxml");
            String absolutePath = file.getAbsolutePath();
            InputStream input = new FileInputStream(new File(absolutePath));
            JasperReport jasperReport = JasperCompileManager.compileReport(input);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null);
            JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());
        } catch (JRException ex) {
            ex.getMessage();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

关于java - 从服务调用 Jasper 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37802999/

相关文章:

java - 失败 : alter table add constraint: Table doesn't exist on create

spring - 以 Angular 更改日期输入字段格式

java - Eclipse 工作区错误

使用Python3.4提取PDF文本

php - 将 PDF 转换为 HTML

java - Apache Tomcat 中的异常 - 错误页面

java - 使用自己的注释更改查看实体 Bean 值的方式

java - 两个 Web 应用程序之间共享身份验证和 SSO

spring - ActiveMQ Failover transport + Spring JmsTemplate 常量重连

wordpress - 我正在使用 TCPDF 在我的 wordpress 插件中生成 pdf,但在执行时它在已发送的库 header 上有错误。