当前位置:网站首页>Itextpdf realizes the merging of multiple PDF files into one PDF document
Itextpdf realizes the merging of multiple PDF files into one PDF document
2022-07-25 17:50:00 【Suddenly】
1、 introduce POM
<dependencies>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
</dependencies>
2、 Write a tool class
public class PdfUtils {
/** * establish pdf file * * @param response * @param fileName * @return */
public static Document createDocument(HttpServletResponse response, String fileName) {
try {
response.reset();
response.setHeader("Content-Type", "application/pdf-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
} catch (Exception e) {
e.printStackTrace();
}
// Set size
return new Document(PageSize.A4, 50, 50, 80, 50);
}
/** * Merge pdf * * @param response * @param document * @param byteList */
public static void mergePdf(HttpServletResponse response, Document document, List<byte[]> byteList) {
try {
OutputStream os = response.getOutputStream();
// Create with any page pdf Templates
document = new Document(new PdfReader(byteList.get(0)).getPageSize(1));
PdfCopy copy = new PdfCopy(document, os);
// Open the document
document.open();
// Traverse pdf file
for (byte[] bytes : byteList) {
// Read pdf
PdfReader reader = new PdfReader(bytes);
// Get pages
int numberOfPages = reader.getNumberOfPages();
// Start with the first page
for (int i = 1; i <= numberOfPages; i++) {
// New document page
document.newPage();
// Copy operation
PdfImportedPage page = copy.getImportedPage(reader, i);
copy.addPage(page);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("PDF Merger failed !");
} finally {
if (document != null) {
document.close();
}
}
}
}
3、 Code implementation
Support upload MultipartFile File or through Local files Path Merge with PDF
@RestController
@RequestMapping("/test")
public class PdfController {
/** * Upload files for merging * * @param files * @param response */
@PostMapping("pdfStream")
public void pdf(@RequestParam("files") MultipartFile[] files, HttpServletResponse response) {
try {
// Judge whether the document is compliant 、 And convert it into an input stream
List<byte[]> byteList = new ArrayList<>();
for (MultipartFile file : files) {
// The restricted format can only be pdf
if (file == null) {
throw new RuntimeException(" The file cannot be empty !");
}
String originalFilename = file.getOriginalFilename();
String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
if (!substring.equals("pdf")) {
throw new RuntimeException(" Can only upload pdf Format file !");
}
// Get input stream
// Get input stream
InputStream inputStream = file.getInputStream();
byte[] bytes = inputStreamToByte(inputStream);
byteList.add(bytes);
}
// 1. Set the output stream name
String fileName = " Merge files .pdf";
Document document = PdfUtils.createDocument(response, fileName);
// 2. Open merge
PdfUtils.mergePdf(response, document, byteList);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
/** * Local file conversion and merging * * @param response */
@GetMapping("pdfPath")
public void pdfPath(HttpServletResponse response) {
try {
// Load local file
List<String> paths = new ArrayList<>();
paths.add("C:\\Users\\LiGezZ\\Desktop\\1.pdf");
paths.add("C:\\Users\\LiGezZ\\Desktop\\2.pdf");
// Judge whether the document is compliant 、 And convert it into an input stream
List<byte[]> byteList = new ArrayList<>();
for (String path : paths) {
File file = new File(path);
// The restricted format can only be pdf
if (!file.exists()) {
throw new RuntimeException(" file does not exist !");
}
if (file.length() <= 0) {
throw new RuntimeException(" The file cannot be empty !");
}
String name = file.getName();
String substring = name.substring(name.lastIndexOf(".") + 1);
if (!substring.equals("pdf")) {
throw new RuntimeException(" Can only upload pdf Format file !");
}
// Get input stream
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = inputStreamToByte(inputStream);
byteList.add(bytes);
}
// 1. Set the output stream name
String fileName = " Merge files .pdf";
Document document = PdfUtils.createDocument(response, fileName);
// 2. Open merge
PdfUtils.mergePdf(response, document, byteList);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
private byte[] inputStreamToByte(InputStream inputStream) {
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
os.flush();
return os.toByteArray();
} catch (Exception e) {
throw new RuntimeException("InputStream switch views !");
}
}
}
边栏推荐
- C# Linq 去重&去重求和
- MySQL数据库中去重与连接查询的方法
- With 8 years of product experience, I have summarized these practical experience of continuous and efficient research and development
- 11、照相机与透镜
- 【解决方案】Microsoft Edge 浏览器 出现“无法访问该页面”问题
- With 8 years of product experience, I have summarized these practical experience of continuous and efficient research and development
- Trooper
- Redis source code and design analysis -- 18. Analysis of redis network connection Library
- 交友活动记录
- 论文阅读_多任务学习_MMoE
猜你喜欢

11. Camera and lens

Interviewer: talk about log The difference between fatal and panic

SVN客户端(TortoiseSVN)安装及使用说明

Memory and packet buffer management of LwIP

Redis源码与设计剖析 -- 16.AOF持久化机制

Highlights

Thesis reading_ Multi task learning_ MMoE

Ultimate doll 2.0 | cloud native delivery package

绘制pdf表格 (二) 通过itext实现在pdf中绘制excel表格样式设置中文字体、水印、logo、页眉、页码

Redis源码与设计剖析 -- 15.RDB持久化机制
随机推荐
Is there a method in PostgreSQL that only compiles statements but does not execute them?
EDI 对接CommerceHub OrderStream
走马卒
Mock服务moco系列(二)- Json格式、File文件、Header、Cookie、解决中文乱码
HCIP第一天实验
PHP解决并发问题的几种实现
new与malloc
[Hardware Engineer] can't select components?
New and malloc
[Hardware Engineer] Why do DC-DC isolated switching power modules use transformers?
Does PgSQL have a useful graphical management tool?
绘制pdf表格 (二) 通过itext实现在pdf中绘制excel表格样式设置中文字体、水印、logo、页眉、页码
mongodb 集群及分片
Mock服务moco系列(三)- 重定向、正则表达式、延迟、模板、事件、分模块设计
实时黄金交易平台哪个可靠安全?
如何看一本书
H5测试点(思维导图)
OSPF---开放式最短优先路径协议
window10系统下nvm的安装步骤以及使用方法
MySQL数据库中去重与连接查询的方法