Java基于PDFbox实现读取处理PDF文件

 更新时间:2022年02月09日 10:06:15   作者:小阿杰  
PDFbox是一个开源的、基于Java的、支持PDF文档生成的工具库,它可以用于创建新的PDF文档,修改现有的PDF文档,还可以从PDF文档中提取所需的内容。本文将具体介绍一下PDFbox读取处理PDF文件的示例代码,感兴趣的可以学习一下

前言

嗨,大家好,2022年春节已经接近尾声,各地都陆陆续续开工了。近期有朋友做一个小项目正好使用Java读取PDF文件信息。因此记录一下相关过程。

pdfbox介绍

PDFbox是一个开源的、基于Java的、支持PDF文档生成的工具库,它可以用于创建新的PDF文档,修改现有的PDF文档,还可以从PDF文档中提取所需的内容。Apache PDFBox还包含了数个命令行工具。

PDF文件的数据时一系列基本对象的集合:数组,布尔型,字典,数字,字符串和二进制流。

开发环境

本次Java基于PDFbox读取处理PDF文件的版本信息如下:

JDK1.8

SpringBoot 2.3.0.RELEASE

PDFbox 1.8.13

PDFbox依赖

在初次使用PDFbox的时候需要引入PDFbox依赖。本次使用的依赖包如下:

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

快速开始

本示例是将指定目录下的PDF文件中的信息读取出来,存储到新的指定路径的txt文本文件当中。

class PdfTest {

    public static void main(String[] args) throws Exception {
       String filePath ="C:\\Users\\Admin\\Desktop\\cxy1.pdf";
   
        List<String> list = getFiles(basePath);
        for (String filePath : list) {
            long ltime = System.currentTimeMillis();
            String substring = filePath.substring(filePath.lastIndexOf("\\") + 1, filePath.lastIndexOf("."));
            String project = "(juejin.cn)";
            String textFromPdf = getTextFromPdf(filePath);
            String s = writterTxt(textFromPdf, substring + "--", ltime, basePath);
            StringBuffer stringBuffer = readerText(s, project);
            writterTxt(stringBuffer.toString(), substring + "-", ltime, basePath);
        }
        System.out.println("******************** end ************************");
    }

    public static List<String> getFiles(String path) {
        List<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                if (tempList[i].toString().contains(".pdf") || tempList[i].toString().contains(".PDF")) {
                    files.add(tempList[i].toString());
                }
                //文件名,不包含路径
                //String fileName = tempList[i].getName();
            }
            if (tempList[i].isDirectory()) {
                //这里就不递归了,
            }
        }
        return files;
    }

    public static String getTextFromPdf(String filePath) throws Exception {
        String result = null;
        FileInputStream is = null;
        PDDocument document = null;
        try {
            is = new FileInputStream(filePath);
            PDFParser parser = new PDFParser(is);
            parser.parse();
            document = parser.getPDDocument();
            PDFTextStripper stripper = new PDFTextStripper();
            result = stripper.getText(document);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Map<String, String> map = new HashMap<String, String>();
        return result;
    }


    public static String writterTxt(String data, String text, long l, String basePath) {
        String fileName = null;
        try {
            if (text == null) {
                fileName = basePath + "javaio-" + l + ".txt";
            } else {
                fileName = basePath + text + l + ".txt";
            }

            File file = new File(fileName);
            //if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            //true = append file
            OutputStream outputStream = new FileOutputStream(file);
//            FileWriter fileWritter = new FileWriter(file.getName(), true);
//            fileWritter.write(data);
//            fileWritter.close();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            outputStreamWriter.write(data);
            outputStreamWriter.close();
            outputStream.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileName;
    }

    public static StringBuffer readerText(String name, String project) {
        // 使用ArrayList来存储每行读取到的字符串
        StringBuffer stringBuffer = new StringBuffer();
        try {
            FileReader fr = new FileReader(name);
            BufferedReader bf = new BufferedReader(fr);
            String str;
            // 按行读取字符串
            while ((str = bf.readLine()) != null) {
                str = replaceAll(str);
                if (str.contains("D、") || str.contains("D.")) {
                    stringBuffer.append(str);
                    stringBuffer.append("\n");
                    stringBuffer.append("参考: \n");
                    stringBuffer.append("参考: \n");
                    stringBuffer.append("\n\n\n\n");
                } else if (str.contains("A、") || str.contains("A.")) {
                    stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                    stringBuffer.append("。" + project + "\n");
                    stringBuffer.append(str + "\n");
                } else if (str.contains("B、") || str.contains("C、") || str.contains("B.") || str.contains("C.")) {
                    stringBuffer.append(str + "\n");
                } else {
                    stringBuffer.append(str);
                }

            }
            bf.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuffer;
    }

    public static String replaceAll(String str) {
        return str.replaceAll("网", "");
    }
}

结语

好了,以上就是Java中继承相关概念介绍,感谢您的阅读,希望您喜欢,如有不足之处,欢迎评论指正。

到此这篇关于Java基于PDFbox实现读取处理PDF文件的文章就介绍到这了,更多相关Java读取处理PDF内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java异常处理运行时异常(RuntimeException)详解及实例

    Java异常处理运行时异常(RuntimeException)详解及实例

    这篇文章主要介绍了 Java异常处理运行时异常(RuntimeException)详解及实例的相关资料,需要的朋友可以参考下http://time.qq.com/?pgv_ref=aiotime
    2017-05-05
  • Java实现图片切割功能

    Java实现图片切割功能

    这篇文章主要为大家详细介绍了Java实现图片切割功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • Java中实现可拖放图片剪裁入门教程

    Java中实现可拖放图片剪裁入门教程

    这篇文章主要介绍了Java中实现可拖放图片剪裁入门教程,本文写给新手,分步骤讲解如何实现图片裁剪,并对每步的代码作注释,需要的朋友可以参考下
    2015-01-01
  • Java使用elasticsearch基础API使用案例讲解

    Java使用elasticsearch基础API使用案例讲解

    这篇文章主要介绍了Java使用elasticsearch基础API使用案例讲解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • java事务的概念浅析

    java事务的概念浅析

    在本篇内容里小编给大家整理的是一篇关于java事务的概念浅析,有兴趣的朋友们可以参考学习下。
    2020-12-12
  • 解决springboot 多线程使用MultipartFile读取excel文件内容报错问题

    解决springboot 多线程使用MultipartFile读取excel文件内容报错问题

    这篇文章主要介绍了解决springboot 多线程使用MultipartFile读取excel文件内容报错问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • Java+MySQL前后端连接新手小白教程

    Java+MySQL前后端连接新手小白教程

    Java作为一种广泛使用的编程语言之一,在开发Web应用程序时经常需要连接MySQL数据库进行数据操作,下面这篇文章主要给大家介绍了关于Java+MySQL前后端连接的相关资料,需要的朋友可以参考下
    2024-03-03
  • springboot如何实现导入其他配置类

    springboot如何实现导入其他配置类

    这篇文章主要介绍了springboot如何实现导入其他配置类问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • Hyperlane 文件分块上传服务端的解决方案

    Hyperlane 文件分块上传服务端的解决方案

    在现代Web应用中,文件上传是一个核心功能,尤其是对于大文件,传统的上传方式常常因网络中断或超时而失败,为了解决这一痛点,我们推出了基于 Hyperlane 的文件分块上传服务端代码,为开发者提供了一个高效、可靠的大文件上传解决方案,感兴趣的朋友一起看看吧
    2025-04-04
  • springboot后台session的存储与取出方式

    springboot后台session的存储与取出方式

    这篇文章主要介绍了springboot后台session的存储与取出方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-06-06

最新评论