Java基于PDFbox读取处理PDF文件

「这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战

前言

  嗨,大家好,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开发者和爱好者。公众号【Java全栈架构师】维护者,欢迎关注阅读交流。

猜你喜欢

转载自juejin.im/post/7062278312667643918
今日推荐