Springboot整合itext實(shí)現(xiàn)PDF文件合并
前言
本文實(shí)現(xiàn) Springboot 整合 itext 實(shí)現(xiàn)PDF文件合并,圖片轉(zhuǎn)PDF拼接。
一、引用依賴
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>8.0.5</version>
<type>pom</type>
</dependency>
二、使用步驟
1.Controller
代碼如下(示例):
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);
//把字節(jié)數(shù)組寫入輸出流中
response.getOutputStream().write(pdfBytes);
}
2.Service接口
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
public interface IPdfHandlerService {
byte[] generatePdfFromFiles(List<MultipartFile> files);
}
3.實(shí)現(xiàn)類
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)) {
// 創(chuàng)建一個(gè)新的 A4 頁面
PdfPage newPage = pdfDoc.addNewPage(PageSize.A4);
Image img = new Image(ImageDataFactory.create(file.getBytes()));
// 設(shè)置圖片大小以適應(yīng) A4 頁面
img.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
// 獲取當(dāng)前頁面編號(hào)
int pageNumber = pdfDoc.getNumberOfPages();
// 設(shè)置圖片位置為頁面中心
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;
}
}
三、請(qǐng)求接口及結(jié)果
http://localhost:8080/pdf/generateFromFiles

以上就是Springboot整合itext實(shí)現(xiàn)PDF文件合并的詳細(xì)內(nèi)容,更多關(guān)于Springboot itext PDF合并的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- SpringBoot3集成iText實(shí)現(xiàn)PDF導(dǎo)出功能
- SpringBoot集成iTextPDF的實(shí)例
- SpringBoot整合iText7導(dǎo)出PDF及性能優(yōu)化方式
- SpringBoot使用itext填充pdf表單及導(dǎo)出pdf的流程
- SpringBoot集成itext實(shí)現(xiàn)html轉(zhuǎn)PDF
- SpringBoot集成itextpdf實(shí)現(xiàn)根據(jù)模板動(dòng)態(tài)生成PDF
- SpringBoot使用iText7實(shí)現(xiàn)將HTML轉(zhuǎn)成PDF并添加頁眉頁腳水印
- SpringBoot集成itext導(dǎo)出PDF的過程
相關(guān)文章
Spring Boot 對(duì)接深度求索接口實(shí)現(xiàn)知識(shí)問答功能
本文詳細(xì)介紹了如何使用 Spring Boot 對(duì)接深度求索接口,實(shí)現(xiàn)知識(shí)問答功能,通過整合深度求索 API,我們可以輕松地在 Spring Boot 項(xiàng)目中實(shí)現(xiàn)智能問答功能,2025-02-02
spring mvc中的@ModelAttribute注解示例介紹
在Spring mvc中,注解@ModelAttribute是一個(gè)非常常用的注解,下面這篇文章主要給大家介紹了關(guān)于spring mvc中@ModelAttribute注解的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。2017-09-09
Mybatis collection查詢集合屬性報(bào)錯(cuò)的解決方案
這篇文章主要介紹了Mybatis collection查詢集合屬性報(bào)錯(cuò)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
SpringBoot整合Kafka完成生產(chǎn)消費(fèi)的方案
網(wǎng)上找了很多管理kafka整合springboot的教程,但是很多都沒辦法應(yīng)用到生產(chǎn)環(huán)境,很多配置都是缺少,或者不正確的,只能當(dāng)個(gè)demo,所以本文給大家介紹了SpringBoot整合Kafka完成生產(chǎn)消費(fèi)的方案,需要的朋友可以參考下2024-12-12
SpringBoot3實(shí)戰(zhàn)教程之實(shí)現(xiàn)接口簽名驗(yàn)證功能
接口簽名是一種重要的安全機(jī)制,用于確保 API 請(qǐng)求的真實(shí)性、數(shù)據(jù)的完整性以及防止重放攻擊,這篇文章主要介紹了SpringBoot3實(shí)戰(zhàn)教程之實(shí)現(xiàn)接口簽名驗(yàn)證功能,需要的朋友可以參考下2025-04-04
SpringBoot基于docx4j實(shí)現(xiàn)DOCX轉(zhuǎn)PDF的具體方案
在日常項(xiàng)目開發(fā)中,我們經(jīng)常遇到用戶上傳 Word( .docx)文件,希望后臺(tái)自動(dòng)生成 PDF,用于下載、歸檔或在線預(yù)覽,本文將介紹一個(gè)完全開源、部署簡(jiǎn)單、純 Java 的實(shí)現(xiàn)方案,感興趣的小伙伴可以跟著小編一起來看看2025-11-11

