【问题标题】:Spring MVC - opens a blank PDF in browserSpring MVC - 在浏览器中打开一个空白 PDF
【发布时间】:2017-04-04 16:17:23
【问题描述】:

我想在我的应用程序的浏览器中打开一个空白 PDF。我正在使用 Spring Web 模型-视图-控制器 (MVC) 框架。

这里是代码

    @Override
        public ModelAndView handleRequest(HttpServletRequest request,
                HttpServletResponse response) throws Exception {
    byte[] data = "No file attached".getBytes();
    String fileName = "NofileFound.pdf";
            response.setHeader("Content-Disposition","attachment; filename="+fileName);
            response.setContentType("application/pdf");         
            OutputStream out = response.getOutputStream();       

Document document = new Document();         
            PdfWriter writer = PdfWriter.getInstance(new Document(), new FileOutputStream("NofileFound.pdf"));
            document.open();
            document.add(new Paragraph("test"));
            document.close();
            writer.close();

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, byteArrayOutputStream);         
            data = byteArrayOutputStream.toByteArray();

            out.write(data);
            out.flush();
            out.close();        
            return null;
    }

但是当我打开文件时,我得到了这个错误:

not a supported file type

【问题讨论】:

  • 你不能像这样制作空白的pdf。您必须使用某种第三类库,例如 iText、PDFBox 等。
  • 删除行 response.setHeader("Content-Disposition","attachment; filename="+fileName);
  • @YeWin - 你确定你的解决方案会奏效吗?我怀疑!
  • 我也怀疑,为什么我只是发表评论并想通过 OP 尝试一次。如果不行,我必须告诉其他可能的解决方案。
  • 还可以想象一下,如果创建 pdf 就像创建一个简单的文本文件那么容易,为什么会有付费图书馆。它们将毫无用处。 ;)

标签: java html spring-mvc pdf servlets


【解决方案1】:
   @Override
        public ModelAndView handleRequest(HttpServletRequest request,
                HttpServletResponse response) throws Exception {

    response.setContentType("application/pdf");
    Document document = new Document();
    PdfWriter.getInstance(document, response.getOutputStream());
    document.open();
    document.add(new Paragraph("empty pdf"));
    document.close();

    return null
}

【讨论】:

    猜你喜欢
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 2021-11-19
    • 2014-12-16
    • 2011-06-12
    • 1970-01-01
    • 2016-03-14
    相关资源
    最近更新 更多