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

企业级-封装Java对内卷PDF利用关键字分页导出标题

提供 PDF 文件 File入参,根据需要将其中内卷文件需要分页利用关键字读取分页,转成 XML
使用 依赖:itextpdfpdfbox

1、导入依赖

<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.21</version>
</dependency><!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.13.3</version>
</dependency>

2、封装代码:PdfPaginationUtil

package com.gwssi.common.servicesupport.test.generator.service.impl;
import com.gwssi.util.Md5TokenGenerator;
import com.gwssi.util.PDFencodeUtil;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.SimpleBookmark;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;/*** @Auther: fyp* @Date: 2024/6/17* @Description:* @Package: com.gwssi.common.servicesupport.test.generator.service.impl* @Version: 1.0*/
public class PdfPaginationUtil {private static final String[] keyWords = new String[]{"1", "2", "3"};private static final String[] keyTitleWords = new String[]{"4", "5", "6"};public List<Map<String,Object>> transToXml(File file) {//1.给定文件PdfReader reader = null;try {InputStream is = new FileInputStream(file);reader = new PdfReader(is);} catch (IOException e) {throw new RuntimeException(e);}//2.定义一个byte数组,长度为文件的长度byte[] pdfData = new byte[(int) file.length()];//3.IO流读取文件内容到byte数组FileInputStream inputStream = null;try {inputStream = new FileInputStream(file);inputStream.read(pdfData);} catch (IOException e) {throw new RuntimeException(e);} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException e) {throw new RuntimeException(e);}}}List<Map<String,Object>> elecFileItemList =new LinkedList<>();Map<String,Object> elecFileItemMap= new HashMap<>();List<HashMap<String, Object>> list = SimpleBookmark.getBookmark ( reader ) ;List<Map<String,Object>>innerfileItemList =new LinkedList<>();String elecFileName = file.getName();for (int i = 0; i < list.size(); i++) {Map<String, Object> innerfileItemMap = new HashMap<>();HashMap<String, Object> currentBookmark = list.get(i);String currentBookmarkName = PDFencodeUtil.showBookmark(currentBookmark);int currentBookmarkPage = PDFencodeUtil.getPageNumbers(currentBookmark);int beginPageNum = currentBookmarkPage;int endPageNum;if (i < list.size() - 1) {HashMap<String, Object> nextBookmark = list.get(i + 1);int nextBookmarkPage = PDFencodeUtil.getPageNumbers(nextBookmark);endPageNum = nextBookmarkPage - 1;} else {try {endPageNum = PDFencodeUtil.getNumberOfPages(file); // You need to determine the total number of pages in your PDF.} catch (IOException e) {throw new RuntimeException(e);}}// 申请书 或 申请表 有卷内文件if (currentBookmarkName.contains("某一页需要分页唯一关键字")) {try {PDDocument document = PDDocument.load(file);int numPages = document.getNumberOfPages();Map<String, Object> titleAndPageInfo = new HashMap<>();for (int page = beginPageNum; page <= endPageNum; page++) {Map<String, Object> szqmInnerfileItemMap = new HashMap<>();Map<String, Object> keywordPositionMap = new HashMap<>();Map<String, Object> nextKeywordPositionMap = new HashMap<>();PDFTextStripper stripper = new PDFTextStripper() {@Overrideprotected void writeString(String text, List<TextPosition> textPositions) throws IOException {for (TextPosition textPosition : textPositions) {// 检查当前文本是否包含关键字for (String keyword : keyWords) {if (text.contains(keyword)) {// 获取关键字的x和y坐标Float x = textPosition.getXDirAdj();Float y = textPosition.getYDirAdj();// 将关键字的x和y坐标存储到Map中Map<String, Float> coordinates = new HashMap<>();coordinates.put("x", x);coordinates.put("y", y);keywordPositionMap.put(keyword, coordinates);}}}super.writeString(text, textPositions);}};PDFTextStripper nextStripper = new PDFTextStripper() {@Overrideprotected void writeString(String text, List<TextPosition> textPositions) throws IOException {for (TextPosition textPosition : textPositions) {// 检查当前文本是否包含关键字for (String keyword : keyWords) {if (text.contains(keyword)) {// 获取关键字的x和y坐标Float x = textPosition.getXDirAdj();Float y = textPosition.getYDirAdj();// 将关键字的x和y坐标存储到Map中Map<String, Float> coordinates = new HashMap<>();coordinates.put("x", x);coordinates.put("y", y);nextKeywordPositionMap.put(keyword, coordinates);}}}super.writeString(text, textPositions);}};// 当前页stripper.setStartPage(page);stripper.setEndPage(page);String text = stripper.getText(document);// 下一页nextStripper.setStartPage(page + 1);nextStripper.setEndPage(page + 1);String nextText = nextStripper.getText(document);int beginPage = page;boolean containTitle = false;boolean nextContainTitle = false;for (int idx = 0;  idx < keyWords.length; idx++) {// 当前页 有关键字 (标题)if (text.contains(keyWords[idx])) {// 记录关键字位置HashMap map = (HashMap) keywordPositionMap.get(keyWords[idx]);Float x = (Float)  map.get("x");Float y = (Float)  map.get("y");if (y < 200) {System.out.println("Keyword " + keyWords[idx] + " found on page: " + (idx + 1));titleAndPageInfo.put("title", keyTitleWords[idx]);titleAndPageInfo.put("beginPage", beginPage);// 初始化 endPagetitleAndPageInfo.put("endPage", beginPage);containTitle = true;}}// 下一页 有关键字 (标题)// 到达 申请书 下一页 关键字 找不到,根据是否到 申请书最后一页判断if (nextText.contains(keyWords[idx])) {HashMap map = (HashMap) nextKeywordPositionMap.get(keyWords[idx]);Float x = (Float) map.get("x");Float y = (Float) map.get("y");if (y < 200) {nextContainTitle = true;}}}// 下一页 存在 关键字,endPage 已获取到if (nextContainTitle) {szqmInnerfileItemMap.put("innerfileTitle", titleAndPageInfo.get("title"));szqmInnerfileItemMap.put("elecFileName", elecFileName);szqmInnerfileItemMap.put("beginPageNum", titleAndPageInfo.get("beginPage"));szqmInnerfileItemMap.put("endPageNum", titleAndPageInfo.get("endPage"));innerfileItemList.add(szqmInnerfileItemMap);// 下一页没有 关键字,且 是 申请书 最后一页} else if (!nextContainTitle && page == endPageNum) {titleAndPageInfo.put("endPage", endPageNum);szqmInnerfileItemMap.put("innerfileTitle", titleAndPageInfo.get("title"));szqmInnerfileItemMap.put("elecFileName", elecFileName);szqmInnerfileItemMap.put("beginPageNum", titleAndPageInfo.get("beginPage"));szqmInnerfileItemMap.put("endPageNum", titleAndPageInfo.get("endPage"));innerfileItemList.add(szqmInnerfileItemMap);} else {titleAndPageInfo.put("endPage", beginPage + 1);}}} catch (Exception e) {e.printStackTrace();}} else {innerfileItemMap.put("innerfileTitle", currentBookmarkName);innerfileItemMap.put("elecFileName", elecFileName);innerfileItemMap.put("beginPageNum", beginPageNum);innerfileItemMap.put("endPageNum", endPageNum);innerfileItemList.add(innerfileItemMap);}}elecFileItemMap.put("elecFileID", Md5TokenGenerator.generate(file.getPath()));elecFileItemMap.put("elecFileName",elecFileName);elecFileItemMap.put("elecFileSavePath", "文件下载地址");elecFileItemMap.put("elecFileType","szqm");elecFileItemMap.put("innerfileItemList",innerfileItemList);elecFileItemList.add(elecFileItemMap);return elecFileItemList;}}

相关文章:

  • shell脚本监控docker容器和supervisor 运行情况
  • python-docx顺序读取word内容
  • 服务器主机托管服务内容科普
  • vscode连接ssh远程服务器
  • Jenkins 发测试邮件报错 553 Mail from must equal authorized user
  • SQL_CALC_FOUND_ROWS 和 FOUND_ROWS()实现对复杂sql实现分页与总条数查询
  • React实现H5手势密码
  • 水电站机组振动摆度在线监测系统详解
  • 南开大学漏洞报送证书【文尾有福利】
  • C#.Net筑基-集合知识全解
  • 《python》paramiko+paramiko实现远程通过ssh通道连接数据库
  • Spring MVC学习记录(基础)
  • leaflet,canvas渲染目标,可加载大批量数据
  • 配电室数据中心巡检3d可视化搭建的详细步骤
  • OCC介绍及框架分析
  • 【JavaScript】通过闭包创建具有私有属性的实例对象
  • ES6系列(二)变量的解构赋值
  • in typeof instanceof ===这些运算符有什么作用
  • java取消线程实例
  • js作用域和this的理解
  • leetcode388. Longest Absolute File Path
  • mysql中InnoDB引擎中页的概念
  • Redis字符串类型内部编码剖析
  • sessionStorage和localStorage
  • Vue 动态创建 component
  • 表单中readonly的input等标签,禁止光标进入(focus)的几种方式
  • - 概述 - 《设计模式(极简c++版)》
  • 汉诺塔算法
  • 利用DataURL技术在网页上显示图片
  • 每天一个设计模式之命令模式
  • 如何借助 NoSQL 提高 JPA 应用性能
  • 通过npm或yarn自动生成vue组件
  • 为物联网而生:高性能时间序列数据库HiTSDB商业化首发!
  • 云栖大讲堂Java基础入门(三)- 阿里巴巴Java开发手册介绍
  • AI算硅基生命吗,为什么?
  • 数据库巡检项
  • ​如何使用QGIS制作三维建筑
  • ​一文看懂数据清洗:缺失值、异常值和重复值的处理
  • ​用户画像从0到100的构建思路
  • # Maven错误Error executing Maven
  • # wps必须要登录激活才能使用吗?
  • #vue3 实现前端下载excel文件模板功能
  • #常见电池型号介绍 常见电池尺寸是多少【详解】
  • $.ajax()方法详解
  • (+4)2.2UML建模图
  • (1)bark-ml
  • (C#)Windows Shell 外壳编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令...
  • (C++20) consteval立即函数
  • (Matalb回归预测)PSO-BP粒子群算法优化BP神经网络的多维回归预测
  • (react踩过的坑)Antd Select(设置了labelInValue)在FormItem中initialValue的问题
  • (react踩过的坑)antd 如何同时获取一个select 的value和 label值
  • (十六)、把镜像推送到私有化 Docker 仓库
  • (原創) 如何讓IE7按第二次Ctrl + Tab時,回到原來的索引標籤? (Web) (IE) (OS) (Windows)...
  • (终章)[图像识别]13.OpenCV案例 自定义训练集分类器物体检测
  • (转)总结使用Unity 3D优化游戏运行性能的经验