需求是浏览器里直接将服务器上的图片文件(JPG,PNG,TIF)输出PDF, TIF还可能是多页的,这里需要把TIF合并,项目是用的Spring/SpringBoot
首先引入itextpdf依赖,编辑pom.xml
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
配置Controller,输出的格式是PDF,这样浏览器能认出是PDF文档
@Controller
@RequestMapping("/api")
public class ApiController {
@RequestMapping(value = "/drawings_{no}.pdf", method = RequestMethod.GET)
public String drawings(@PathVariable("no") String no, HttpServletRequest request, HttpServletResponse response) {
try {
//processDrawings就是处理输出PDF的,我们在下一个方法介绍
byte[] contents = processDrawings(no);
String filename = "drawings_" + no + ".pdf";
response.setContentType("application/pdf");
//比较关键的是Content-Disposition是inline而不是attachment,这样提示浏览器来显示文档而不是下载
response.setHeader("Content-Disposition", "inline; fileName=" + filename);
response.setContentLength(contents.length);
response.getOutputStream().write(contents);
response.getOutputStream().flush();
} catch (Exception e) {
//request.setAttribute("message", "无法输出图号为: " + no + " 的图纸" + (e.getMessage() == null ? "" : ("<br/>" + e.getMessage())));
//return "forward:/message";
throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
}
return null;
}
}
itextpdf处理图像文件输出为PDF的方法 详见我的博客 https://blog.terrynow.com/2021/01/20/spring-springboot-output-pdf-from-jpg-png-tif-images/
更多开发和运维过程中遇到的坑已经解决问题的方案、干货分享请访问 https://blog.terrynow.com/