当前位置: 首页 > news >正文

Java项目中整合多个pdf合并为一个pdf

一、Java项目中整合多个pdf合并为一个pdf

gitee笔记路径:https://gitee.com/happy_sad/drools

一、依赖导入

<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.6</version>
</dependency>
<dependency><groupId>org.kie</groupId><artifactId>kie-api</artifactId><version>7.6.0.Final</version>
</dependency>
<dependency><groupId>org.kie</groupId><artifactId>kie-internal</artifactId><version>7.6.0.Final</version>
</dependency>

二、设置端口

server.port=8082

三、设置已存在的多个pdf

注意:此次为模拟获取多个pdf,所以本人做两个pdf的合并实验,所以将两个pdf放入项目中的/resources/mergepdfs文件夹中,合并时遍历该文件夹下的所有文件,转换字节流

image-20240721160034444

四、controller

package com.jin.test.controller;import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;/*** @Package:com.jin.test.controller* @ClassName: MergepdfTestController* @Description: 项目中整合多个pdf合并为一个pdf* @Date: 2024/07/21 14:22* @Author: Jin*/
@Log4j2
@RestController
@RequestMapping("/mergepdf")
public class MergepdfTestController {@Autowiredprivate ResourceLoader resourceLoader;@RequestMapping("/download")public void downloadFile(HttpServletResponse response) throws Exception {List<byte[]> finalList = Collections.synchronizedList(new ArrayList<>());ArrayList<String> fileNames = new ArrayList<>();Resource folderResource = resourceLoader.getResource("classpath:" + "mergepdfs");if (folderResource.exists()) {try (Stream<Path> files = Files.list(Paths.get(folderResource.getURI()))) {files.forEach(filePath ->fileNames.add(filePath.toString()));}for (String fileNmae : fileNames) {File file = new File(fileNmae);FileInputStream fis = new FileInputStream(file);ByteArrayOutputStream bos = new ByteArrayOutputStream();int byteContent;while ((byteContent = fis.read()) != -1) {bos.write(byteContent);}byte[] bytes = bos.toByteArray();finalList.add(bytes);}byte[] finalByte = this.mergepdf(finalList);ServletOutputStream outputStream = response.getOutputStream();outputStream.write(finalByte);outputStream.flush();} else {System.out.println("Folder not found: " + "mergepdfs");}}/*** pdf合并方法* @param bytes* @return* @throws Exception*/public byte[] mergepdf(List<byte[]> bytes) throws Exception {ByteArrayOutputStream bos = new ByteArrayOutputStream();Document document = new Document();PdfCopy copy = new PdfCopy(document, bos);document.open();for (byte[] bs : bytes) {PdfReader reader = new PdfReader(bs);int pageTotal = reader.getNumberOfPages();log.info("pdf的页码数是 ==>{}", pageTotal);for (int pageNo = 1; pageNo <= pageTotal; pageNo++) {document.newPage();PdfImportedPage page = copy.getImportedPage(reader, pageNo);copy.addPage(page);}reader.close();}document.close();byte[] pdfs = bos.toByteArray();bos.close();copy.close();return pdfs;}
}

五、测试结果

1、Apifox请求

http://localhost:8082/mergepdf/download

image-20240721155308587

2、例子1.pdf页数为26

image-20240721155044665

3、例子2.pdf页数为2

image-20240721155123050

4、合并后的pdf页数为28

image-20240721155155625

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 【Java版数据结构】初识泛型
  • OpenKylin 系统中禁用 Win 键
  • html+css前端作业 王者荣耀官网1个页面(带报告)
  • Java面试八股之Spring框架的核心模块
  • Web动画(lottie篇)
  • Unity3D结合AI教育大模型 开发AI教师 AI外教 AI英语教师案例
  • 昇思25天学习打卡营第23天|LSTM+CRF序列标注
  • 图像生成中图像质量评估指标— LPIPS介绍
  • JCR一区级 | Matlab实现TTAO-Transformer-LSTM多变量回归预测
  • 分享几种电商平台商品数据的批量自动抓取方式
  • STM32CubeIDE(CAN)
  • Java设计模式—单例模式(Singleton Pattern)
  • W30-python03-pytest+selenium+allure访问百度网站实例
  • SpringBoot中如何使用RabbitMq
  • NVIDIA Drivers、CUDA、Pytorch安装
  • 【391天】每日项目总结系列128(2018.03.03)
  • 【跃迁之路】【669天】程序员高效学习方法论探索系列(实验阶段426-2018.12.13)...
  • 11111111
  • 2017-09-12 前端日报
  • Android路由框架AnnoRouter:使用Java接口来定义路由跳转
  • Angular6错误 Service: No provider for Renderer2
  • Hexo+码云+git快速搭建免费的静态Blog
  • Joomla 2.x, 3.x useful code cheatsheet
  • LeetCode刷题——29. Divide Two Integers(Part 1靠自己)
  • Mysql5.6主从复制
  • php ci框架整合银盛支付
  • PHP的Ev教程三(Periodic watcher)
  • Swift 中的尾递归和蹦床
  • use Google search engine
  • vue从创建到完整的饿了么(11)组件的使用(svg图标及watch的简单使用)
  • 给Prometheus造假数据的方法
  • 前端临床手札——文件上传
  • 如何使用 JavaScript 解析 URL
  • 收藏好这篇,别再只说“数据劫持”了
  • 一个SAP顾问在美国的这些年
  • 1.Ext JS 建立web开发工程
  • 2017年360最后一道编程题
  • ​LeetCode解法汇总2696. 删除子串后的字符串最小长度
  • # Redis 入门到精通(八)-- 服务器配置-redis.conf配置与高级数据类型
  • #{} 和 ${}区别
  • #图像处理
  • (22)C#传智:复习,多态虚方法抽象类接口,静态类,String与StringBuilder,集合泛型List与Dictionary,文件类,结构与类的区别
  • (二)原生js案例之数码时钟计时
  • (每日一问)设计模式:设计模式的原则与分类——如何提升代码质量?
  • (全部习题答案)研究生英语读写教程基础级教师用书PDF|| 研究生英语读写教程提高级教师用书PDF
  • (转载)虚函数剖析
  • .chm格式文件如何阅读
  • .net core 微服务_.NET Core 3.0中用 Code-First 方式创建 gRPC 服务与客户端
  • .NET(C#、VB)APP开发——Smobiler平台控件介绍:Bluetooth组件
  • .NetCore Flurl.Http 升级到4.0后 https 无法建立SSL连接
  • .Net的C#语言取月份数值对应的MonthName值
  • .net生成的类,跨工程调用显示注释
  • .pyc文件是什么?
  • @Transaction注解失效的几种场景(附有示例代码)
  • [ 环境搭建篇 ] 安装 java 环境并配置环境变量(附 JDK1.8 安装包)