如何在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中的
相关产品推荐
相关产品推荐

