java(springboot)实现将多张图片从上到下拼在一起转成一个pdf输出
以下是一个将多张图片从上到下拼接在一起并转换成 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 文档中。最后,我们将文档关闭并将输出流中的二进制数据流返回即可。
请注意这里使用了 @ResponseBody
和 MediaType.APPLICATION_PDF_VALUE
注解来指定返回的是 PDF 文件类型。此外,为了简化代码,我没有对传入参数进行校验,实际应用中请根据需求进行修改。
标签:
springboot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2018-06-09 定时执行线程池ScheduledExecutorService的使用
2018-06-09 thread.join() 方法存在的必要性是什么?