使用itext生成时,直接将pdf下载到浏览器

时间:2015-12-18 09:00:38

标签: java spring pdf-generation itext

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

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

这是我控制器中的代码。

@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());
    } 

1 个答案:

答案 0 :(得分:0)

您需要做的是将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;
}