java - 使用itext生成pdf后直接下载到浏览器

标签 java spring pdf-generation itext

我正在使用 itext 从 html 字符串生成 pdf 文件。我在控制台中收到此错误:

Uncaught Error: Syntax error, unrecognized expression: %PDF-1.4

这是我的 Controller 中的代码。

@RequestMapping(value = "/print",method = RequestMethod.POST)
public void  print(String html,HttpServletResponse response,HttpServletRequest request) throws IOException,DocumentException {
    try{
        Document document = new Document();
        // step 2
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        // step 3
        document.open();
        document.add(new Paragraph(html));
        // step 5
        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control",
                "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        OutputStream os = response.getOutputStream();
        baos.writeTo(os);
        os.flush();
    }
    catch(DocumentException e) {
        throw new IOException(e.getMessage());
    } 

最佳答案

您需要做的是将 PDF 文件的字节直接流式传输到输出流并刷新响应。在 Spring 中你可以这样做:

@RequestMapping(value="/displayProcessFile/{processInstanceId}", method=RequestMethod.GET)
public ResponseEntity<byte[]> displayProcessFile(@PathVariable String processInstanceId) throws UnauthorizedUserAccessException{
    Document processFile=null;
    try {
        processFile = documentService.retrieveProcessFile(Long.parseLong(processInstanceId));
    } catch (ProcessFileNotFoundExpection e) {
        e.printStackTrace();
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    headers.add("content-disposition", "attachment;filename=" + processFile.getDocName());
    ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(processFile.getContent(), headers, HttpStatus.OK);
    return response;
}

关于java - 使用itext生成pdf后直接下载到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34351863/

相关文章:

spring - 使用 Spring @ContextConfiguration 进行事务测试 - 清除数据库问题

c# - 主要内容重叠在页 footer 分 PDF 文档 iTextSharp

java - 使用 itext 创建的 pdf 文档的第一页上看不到标题

grails - 无法使用 grails 渲染插件加载 CSS

java - 解析@PropertySource中的占位符

java - 为对象分配一个空值,然后尝试拆箱

java - 如何停止我的刽子手程序中的循环?

java - 在使用 java 或 java API 提取 YouTube 视频评论的多种方法?

Spring 3 MVC-将带有前缀的请求参数映射到单个bean

java - 尝试使用 Oracle JdbcOdbcDriver 时出现 classNotFoundException