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

java 读取pdf文件内容

一、引入maven

<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.25</version>
</dependency>

二、代码工具类

package com.jiayou.peis.utils;//import com.itextpdf.text.pdf.PdfReader;
//import com.itextpdf.text.pdf.parser.PdfTextExtractor;
//import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;import com.google.common.collect.Lists;
import com.jiayou.peis.entity.ImageObject;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
import org.apache.pdfbox.pdmodel.graphics.image.PDImage;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.text.PDFTextStripper;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;/*** PDF处理** @author Bob Ren (Copyright © 2015-2029 贵州家有在线网络有限公司)* @version 1.0.0* @date 2022-02-07 16:21*/
public class PdfUtils {//    /**
//     * 使用itextpdf提取PDF文本(解析不靠谱)
//     *
//     * @param inputStream
//     * @return
//     * @throws IOException
//     */
//    @Deprecated
//    public static String toText(InputStream inputStream) throws IOException {
//        try {
//            StringBuilder buf = new StringBuilder();
//            PdfReader reader = new PdfReader(inputStream);
//            int pageNum = reader.getNumberOfPages();
//            for(int i=1;i<=pageNum;i++){
//                // 读取第i页的文档内容
//                buf.append(PdfTextExtractor.getTextFromPage(reader, i, new SimpleTextExtractionStrategy()));
//            }
            return buf.toString();
//            return StrUtils.removeReturnChar(buf.toString());
//        } finally {
//            CloseUtils.closeQuietly(inputStream);
//        }
//    }public static String text(byte[] data) throws IOException {return PdfUtils.text(data, true);}public static String text(byte[] data, boolean sortByPosition) throws IOException {ByteArrayInputStream inputStream = new ByteArrayInputStream(data);return PdfUtils.text(inputStream, sortByPosition);}/*** 使用pdfbox提取PDF文本(解析正常,可使用)** @param file* @return* @throws IOException*/public static String text(File file, boolean sortByPosition) throws IOException {InputStream inputStream = new FileInputStream(file);return PdfUtils.text(inputStream, sortByPosition);}public static String text(File file) throws IOException {return PdfUtils.text(file, true);}public static String text(InputStream inputStream) throws IOException {return text(inputStream, true);}/*** 使用pdfbox提取PDF文本(解析正常,可使用)** @param inputStream* @return* @throws IOException*/public static String text(InputStream inputStream, boolean sortByPosition) throws IOException {PDDocument document = null;try {
//            document = PDDocument.load(inputStream);document = Loader.loadPDF(inputStream);PDFTextStripper textStripper = new PDFTextStripper();// Get total page count of the PDF documentint numberOfPages = document.getNumberOfPages();//set the first page to be extractedtextStripper.setStartPage(1);// set the last page to be extractedtextStripper.setEndPage(numberOfPages);// 获取文本内容textStripper.setSortByPosition(sortByPosition);textStripper.setShouldSeparateByBeads(true);return StrUtils.removeReturnChar(textStripper.getText(document));} finally {CloseUtils.closeQuietly(document, inputStream);}}/*** 使用pdfbox提取PDF文本(解析正常,可使用)** @param file* @return* @throws IOException*/public static List<ImageObject> images(File file) throws IOException {InputStream inputStream = new FileInputStream(file);return PdfUtils.images(inputStream);}public static List<ImageObject> images(byte[] data) throws IOException {ByteArrayInputStream inputStream = null;try {inputStream = new ByteArrayInputStream(data);return PdfUtils.images(inputStream);} finally {CloseUtils.closeQuietly(inputStream);}}/*** 使用pdfbox提取PDF图片列表** @param inputStream* @return* @throws IOException*/public static List<ImageObject> images(InputStream inputStream) throws IOException {List<ImageObject> imageList = Lists.newArrayList();PDDocument document = null;try {
//            document = PDDocument.load(inputStream);document = Loader.loadPDF(inputStream);// get resources for a pagePDResources pdResources = document.getPage(0).getResources();int i = 0;for (COSName csName : pdResources.getXObjectNames()) {
//                System.out.println(i+":"+csName);PDXObject pdxObject = pdResources.getXObject(csName);if (pdxObject instanceof PDImageXObject) {
//                    i++;PDStream pdStream = pdxObject.getStream();PDImageXObject image = new PDImageXObject(pdStream, pdResources);String imageSuffix = imageSuffix(image);// image storage location and image nameBufferedImage bufferedImage = image.getImage();ImageObject object = new ImageObject();object.setIndex(i++);object.setImage(bufferedImage);object.setSuffix(imageSuffix);imageList.add(object);}}} finally {CloseUtils.closeQuietly(document, inputStream);}return imageList;}/*** 获取图片后缀** @param pdImage* @return* @throws IOException*/private static String imageSuffix(PDImageXObject pdImage) throws IOException {String suffix = pdImage.getSuffix();if (suffix == null || "jb2".equals(suffix)) {suffix = "png";} else if ("jpx".equals(suffix)) {// use jp2 suffix for file because jpx not known by windowssuffix = "jp2";}if (hasMasks(pdImage)) {// TIKA-3040, PDFBOX-4771: can't save ARGB as JPEGsuffix = "png";}return suffix;}private static boolean hasMasks(PDImage pdImage) throws IOException {if (pdImage instanceof PDImageXObject) {PDImageXObject ximg = (PDImageXObject) pdImage;return ximg.getMask() != null || ximg.getSoftMask() != null;}return false;}/*** 保存图片到指定文件夹** @param imageList* @param dir* @param prefixName* @throws IOException*/public static void saveImage(List<ImageObject> imageList, String dir, String prefixName) throws IOException {File imgDir = new File(dir);FileUtils.forceMkdir(imgDir);for(ImageObject image:imageList){File imgFile = new File(dir, prefixName+"_"+image.getIndex()+"."+image.getSuffix());ImageIO.write(image.getImage(), image.getSuffix(), imgFile);}}
}

相关文章:

  • 说一说ajax的请求过程?
  • dd命令用法学习,是一个功能强大的工具
  • docker搭建waline评论系统
  • Vue 3响应式对象: ref和reactive
  • Ubuntu 20.04 上安装和使用 Docker
  • Spring MVC的常用注解
  • Kubernetes(K8s)从入门到精通系列之十八:使用 Operator Lifecycle Manager(OLM) 安装operator
  • 保姆级教学安装Linux操作系统,以及Linux的语法入门
  • 论文阅读——ELECTRA
  • 一台服务器最大能支持多少条 TCP 连接
  • 9.Vue2-监听属性的用法
  • 地面文物古迹保护方案,用科技为文物古迹撑起“智慧伞”
  • 常见MySQL数据库无法启动的解决方案
  • 使用Ubuntu虚拟机离线部署RKE2高可用集群
  • 汇编运算符和表达式
  • 收藏网友的 源程序下载网
  • [分享]iOS开发 - 实现UITableView Plain SectionView和table不停留一起滑动
  • android 一些 utils
  • CentOS 7 修改主机名
  • docker-consul
  • Effective Java 笔记(一)
  • JS正则表达式精简教程(JavaScript RegExp 对象)
  • markdown编辑器简评
  • Nodejs和JavaWeb协助开发
  • Vue2 SSR 的优化之旅
  • 服务器之间,相同帐号,实现免密钥登录
  • 复杂数据处理
  • 看域名解析域名安全对SEO的影响
  • 离散点最小(凸)包围边界查找
  • 提升用户体验的利器——使用Vue-Occupy实现占位效果
  • 吴恩达Deep Learning课程练习题参考答案——R语言版
  • 掌握面试——弹出框的实现(一道题中包含布局/js设计模式)
  • 追踪解析 FutureTask 源码
  • 测评:对于写作的人来说,Markdown是你最好的朋友 ...
  • 分布式关系型数据库服务 DRDS 支持显示的 Prepare 及逻辑库锁功能等多项能力 ...
  • ​3ds Max插件CG MAGIC图形板块为您提升线条效率!
  • # 手柄编程_北通阿修罗3动手评:一款兼具功能、操控性的电竞手柄
  • #微信小程序(布局、渲染层基础知识)
  • (1)(1.8) MSP(MultiWii 串行协议)(4.1 版)
  • (2)STL算法之元素计数
  • (HAL库版)freeRTOS移植STMF103
  • (附源码)spring boot校园拼车微信小程序 毕业设计 091617
  • (附源码)springboot青少年公共卫生教育平台 毕业设计 643214
  • (附源码)ssm基于jsp高校选课系统 毕业设计 291627
  • (机器学习的矩阵)(向量、矩阵与多元线性回归)
  • (四)汇编语言——简单程序
  • (心得)获取一个数二进制序列中所有的偶数位和奇数位, 分别输出二进制序列。
  • (转)ObjectiveC 深浅拷贝学习
  • .NET 分布式技术比较
  • .net 无限分类
  • .NET设计模式(8):适配器模式(Adapter Pattern)
  • ?php echo $logosrc[0];?,如何在一行中显示logo和标题?
  • @ 代码随想录算法训练营第8周(C语言)|Day53(动态规划)
  • @select 怎么写存储过程_你知道select语句和update语句分别是怎么执行的吗?
  • [ C++ ] template 模板进阶 (特化,分离编译)