Springboot 整合 itext 实现PDF文件合并,识别图片则转成PDF拼接

目录


前言

本文实现 Springboot 整合 itext 实现PDF文件合并,图片转PDF拼接。


一、引用依赖

xml 复制代码
<dependency>
     <groupId>com.itextpdf</groupId>
     <artifactId>itext7-core</artifactId>
     <version>8.0.5</version>
     <type>pom</type>
</dependency>

二、使用步骤

1.Controller

代码如下(示例):

java 复制代码
import com.ruoyi.tools.service.IPdfHandlerService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/pdf")
public class PdfHandlerController {

private final IPdfHandlerService pdfHandlerService;

@PostMapping(value = "/generateFromFiles", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void uploadFiles(@RequestPart("files") List<MultipartFile> files, HttpServletResponse response) throws Exception {
    byte[] pdfBytes = pdfHandlerService.generatePdfFromFiles(files);
    response.setContentType("application/pdf");
    response.setContentLength(pdfBytes.length);
    //把字节数组写入输出流中
    response.getOutputStream().write(pdfBytes);
}

2.Service接口

java 复制代码
import org.springframework.web.multipart.MultipartFile;
import java.util.List;

public interface IPdfHandlerService {

    byte[] generatePdfFromFiles(List<MultipartFile> files);
}

3.实现类

java 复制代码
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.ruoyi.tools.service.IPdfHandlerService;
import lombok.SneakyThrows;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;

@Service
public class PdfHandlerServiceImpl implements IPdfHandlerService {

    @SneakyThrows
    public byte[] generatePdfFromFiles(List<MultipartFile> files) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = new PdfWriter(baos);
        PdfDocument pdfDoc = new PdfDocument(writer);
        Document document = new Document(pdfDoc);

        for (MultipartFile file : files) {
            if (isPdf(file)) {
                PdfDocument sourcePdf = new PdfDocument(new PdfReader(file.getInputStream()));
                int n = sourcePdf.getNumberOfPages();
                for (int i = 1; i <= n; i++) {
                    PdfPage page = sourcePdf.getPage(i);
                    PdfFormXObject pageCopy = page.copyAsFormXObject(pdfDoc);
                    Rectangle pageSize = page.getPageSize();

                    PdfPage newPage = pdfDoc.addNewPage();
                    newPage.setMediaBox(pageSize);
                    new PdfCanvas(newPage).addXObjectAt(pageCopy, 0, 0);
                    newPage.setRotation(page.getRotation());
                }
                sourcePdf.close();
                continue;
            }

            if (isImage(file)) {
                // 创建一个新的 A4 页面
                PdfPage newPage = pdfDoc.addNewPage(PageSize.A4);
                Image img = new Image(ImageDataFactory.create(file.getBytes()));
                // 设置图片大小以适应 A4 页面
                img.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
                // 获取当前页面编号
                int pageNumber = pdfDoc.getNumberOfPages();
                // 设置图片位置为页面中心
                img.setFixedPosition(pageNumber,
                    (PageSize.A4.getWidth() - img.getImageScaledWidth()) / 2,
                    (PageSize.A4.getHeight() - img.getImageScaledHeight()) / 2);
                // 添加图片到文档
                document.add(img);
                continue;
            }

            //可以删掉此提示
            document.add(new Paragraph(file.getOriginalFilename() + "仅支持PDF和图片的拼接"));

        }

        document.close();
        return baos.toByteArray();
    }

    @SneakyThrows
    private boolean isPdf(MultipartFile file) {
        String contentType = file.getContentType();
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());

        if (contentType != null && contentType.equals("application/pdf")) {
            return true;
        }

        if ("pdf".equalsIgnoreCase(extension)) {
            byte[] fileHeader = new byte[4];
            try (ByteArrayInputStream bis = new ByteArrayInputStream(file.getBytes())) {
                int bytesRead = bis.read(fileHeader);
                if (bytesRead != fileHeader.length) {
                    return false;
                }
            }
            return new String(fileHeader).startsWith("%PDF");
        }

        return false;
    }

    @SneakyThrows
    private boolean isImage(MultipartFile file) {
        String contentType = file.getContentType();
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());

        if (contentType != null && contentType.startsWith("image")) {
            return true;
        }

        if (extension != null) {
            switch (extension.toLowerCase()) {
                case "jpg":
                case "jpeg":
                case "png":
                case "gif":
                case "bmp":
                    return true;
                default:
                    return false;
            }
        }

        return false;
    }

}

三、请求接口及结果

http://localhost:8080/pdf/generateFromFiles

相关推荐
向前看-3 小时前
验证码机制
前端·后端
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭4 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
超爱吃士力架5 小时前
邀请逻辑
java·linux·后端
AskHarries7 小时前
Spring Cloud OpenFeign快速入门demo
spring boot·后端
isolusion7 小时前
Springboot的创建方式
java·spring boot·后端
Yvemil78 小时前
《开启微服务之旅:Spring Boot Web开发举例》(一)
前端·spring boot·微服务
zjw_rp8 小时前
Spring-AOP
java·后端·spring·spring-aop
TodoCoder8 小时前
【编程思想】CopyOnWrite是如何解决高并发场景中的读写瓶颈?
java·后端·面试
凌虚9 小时前
Kubernetes APF(API 优先级和公平调度)简介
后端·程序员·kubernetes
星河梦瑾9 小时前
SpringBoot相关漏洞学习资料
java·经验分享·spring boot·安全