Java/Spring/SpringBoot利用itextpdf将JPG/PNG/TIF等输出为PDF(解决TIF多页合并问题)

这篇博客介绍了如何在Spring/SpringBoot项目中利用iTextPDF库将JPG,PNG,TIF图片文件转换为PDF,并且处理多页TIF文件的合并。通过配置Controller,设置响应头为'Content-Disposition: inline',确保浏览器能够直接显示生成的PDF文档。详细步骤和代码示例可在作者的博客中找到。
摘要由CSDN通过智能技术生成

需求是浏览器里直接将服务器上的图片文件(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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值