当前位置:网站首页>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 !");
}
}
}
边栏推荐
- Mongodb cluster and sharding
- 十九岁的总结
- Cross validation (CV) learning notes
- 实时黄金交易平台哪个可靠安全?
- 2022/7/23
- I'm also drunk. Eureka delayed registration and this pit!
- [solution] the Microsoft edge browser has the problem of "unable to access this page"
- [Hardware Engineer] about signal level driving capability
- WPF 实现用户头像选择器
- Methods of de duplication and connection query in MySQL database
猜你喜欢
随机推荐
Hcip first day experiment
OSPF---开放式最短优先路径协议
Crawler framework crawler
【解决方案】Microsoft Edge 浏览器 出现“无法访问该页面”问题
WPF implements user avatar selector
Go defer and recover simple notes
【Cadence Allegro PCB设计】永久修改快捷键(自定义)~亲测有效~
Installation steps and usage of NVM under windows10 system
What financial products can you buy to make money with only 1000 yuan?
服务器端架构设计期末复习知识点总结
我也是醉了,Eureka 延迟注册还有这个坑!
如何看一本书
【硬件工程师】DC-DC隔离式开关电源模块为什么会用到变压器?
PostgreSQL passwords are case sensitive. Is there parameter control?
Several implementations of PHP to solve concurrency problems
How to rectify the unqualified EMC of electronic products?
Redis源码与设计剖析 -- 17.Redis事件处理
我也是醉了,Eureka 延迟注册还有这个坑!
Mock服务moco系列(一)- 简介、第一个Demo、Get请求、Post请求
期货开户哪家最好最安全








