我正在使用 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/