You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring MVC项目的JSP页面中展示iText生成的PDF文件?

看你已经理清了大体思路:用JSP的<object>标签调用Spring MVC控制器,通过iText生成PDF并输出到响应流。我来帮你把细节补全,确保PDF能在浏览器里正常展示:

完整实现步骤

1. 完善控制器的PDF生成逻辑

你目前的控制器方法只开了个头,还需要设置正确的响应头、完成iText的PDF生成流程,这里是完整的可运行代码:

@RequestMapping(value = "/view-pdf", method = RequestMethod.GET)
protected void viewPdf(HttpServletResponse response) throws IOException, DocumentException {
    // 核心:告诉浏览器这是PDF类型的内容
    response.setContentType("application/pdf");
    // 设置为inline,让浏览器直接渲染而不是默认下载(如果需要下载可以改成attachment)
    response.setHeader("Content-Disposition", "inline; filename=\"my-generated-pdf.pdf\"");
    
    // 获取响应输出流,用try-with-resources自动管理资源
    try (ServletOutputStream out = response.getOutputStream()) {
        // 初始化iText文档和Writer
        Document document = new Document();
        PdfWriter.getInstance(document, out);
        
        // 打开文档并添加内容
        document.open();
        // 这里替换成你的业务内容,比如从数据库取数据生成表格、图片等
        document.add(new Paragraph("这是通过iText生成的测试PDF"));
        document.add(new Paragraph("生成时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
        
        // 关闭文档,自动刷新输出流
        document.close();
    }
}

2. 优化JSP中的标签兼容性

不同浏览器对<object>标签的支持有差异,建议添加宽度高度、备用文本和<embed>降级方案:

<object data="<c:url value="/view-pdf" />" type="application/pdf" width="100%" height="700px">
    <!-- 浏览器不支持PDF预览时的备用方案 -->
    <p>你的浏览器无法直接预览PDF,<a href="<c:url value="/view-pdf" />">点击下载</a>查看</p>
    <embed src="<c:url value="/view-pdf" />" type="application/pdf" width="100%" height="700px" />
</object>

3. 必看的注意事项

  • 依赖确认:确保项目里已经引入iText的依赖,如果用Maven的话,添加到pom.xml:
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version> <!-- 选择你需要的稳定版本 -->
</dependency>
  • 异常处理:实际项目中不要直接抛出异常,建议添加try-catch块捕获DocumentException和IOException,返回友好的错误页面。
  • 流管理:用try-with-resources语法(像上面代码那样)自动管理输出流,避免资源泄漏。

这样调整后,你的页面就能正常展示iText生成的PDF了。

内容的提问来源于stack exchange,提问作者saidfagan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:09:26