【问题标题】:How can I create and display JSp Template as PDF如何创建 JSp 模板并将其显示为 PDF
【发布时间】:2018-11-21 15:15:24
【问题描述】:

我有一个要求,我必须生成 PDF。我们可以在完整的浏览器中显示该 PDf,也可以在 iframe 中将其显示为预览。我想使用带有一些动态数据的 HTML 和 JSP 创建一个 JSP 模板。每当我单击生成 pfd 时,我都希望此模板以 pdf 格式出现在 iFrame 中。我应该怎么做以及如何将动态jsp转换为pdf?

【问题讨论】:

    标签: java spring-mvc jsp spring-boot servlets


    【解决方案1】:

    您可以做的第一件事是使用org.apache.pdfbox

    查看更多信息和许多示例https://pdfbox.apache.org/

    当用户单击生成按钮时,您需要逐步创建 pdf,使其看起来像模板。您不能将包含数据的 jsp 模板的一部分直接“复制”到 pdf 中。

    您可以将输出创建为文件或字节数组:

    protected void create(Object model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    
        ByteArrayOutputStream baos = createTemporaryOutputStream();
    
        PDDocument document = newDocument();
    
        // Build PDF document.
        buildPdfDocument(model, document, request, response);
        document.save(baos);
        document.close();
    
    
        final String filename = "pdf-as-byte-stream.pdf";
    
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    
        writeToResponse(response, baos);
    }
    

    通过上述解决方案,pdf 将在浏览器中全屏显示。 但是因为您想将其显示为 iframe,您需要将字节流保存到文件中,然后将 iframe 指向该文件。

    <iframe src="https://www.yoursite.com/pdf/dgxedg37gd3wedb3d83vd3dgv3dt3.pdf"></iframe>
    

    (确保为 pdf 生成唯一名称)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-01
      • 2013-11-14
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      • 2011-08-10
      • 1970-01-01
      • 2014-09-29
      相关资源
      最近更新 更多