java(springboot)实现将多张图片从上到下拼在一起转成一个pdf输出

发布时间 2023-06-09 14:36:14作者: 夏威夷8080

以下是一个将多张图片从上到下拼接在一起并转换成 PDF 文件的 Spring Boot 接口的示例代码:

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.util.List;

@Controller
public class ImagesToPdfController {

    @PostMapping(value = "/images-to-pdf", produces = MediaType.APPLICATION_PDF_VALUE)
    @ResponseBody
    public byte[] imagesToPdf(@RequestBody List<MultipartFile> imageFiles) throws Exception {
        if (CollectionUtils.isEmpty(imageFiles)) {
            throw new IllegalArgumentException("No images found.");
        }
        ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
        Document doc = new Document();
        PdfWriter.getInstance(doc, pdfOutputStream);
        doc.open();

        for (MultipartFile imageFile : imageFiles) {
            if (imageFile == null || imageFile.isEmpty()) {
                continue;
            }
            byte[] imageData = imageFile.getBytes();
            Image image = Image.getInstance(imageData);
            float width = doc.getPageSize().getWidth() - doc.leftMargin() - doc.rightMargin();
            float height = image.getHeight() * width / image.getWidth();
            image.scaleAbsolute(width, height);
            image.setAlignment(Image.ALIGN_CENTER);
            doc.add(image);
        }
        doc.close();
        return pdfOutputStream.toByteArray();
    }

}

示例代码使用了 iTextPDF 库将多张图片拼接成一个 PDF 文件。这个接口接收一个由多个图片文件组成的列表,将它们从上到下拼接在一起后转换为 PDF 文件并返回该文件的二进制数据流。

在实现中,我们遍历传入的图片文件列表,读取每个文件的内容并转换为 Image 对象,然后计算每张图片需要占用的页面区域大小,按照从上到下排列的方式添加到 PDF 文档中。最后,我们将文档关闭并将输出流中的二进制数据流返回即可。

请注意这里使用了 @ResponseBodyMediaType.APPLICATION_PDF_VALUE 注解来指定返回的是 PDF 文件类型。此外,为了简化代码,我没有对传入参数进行校验,实际应用中请根据需求进行修改。