Spring MVC - 在浏览器中打开一个空白PDF

时间:2016-11-21 09:54:21

标签: java html spring-mvc pdf servlets

我想在我的应用程序中在浏览器中打开一个空白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

1 个答案:

答案 0 :(得分:0)

   @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
}