package jframe;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.text.Document;

import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

public class PDFReader {

    /**
     * @DESCRIPTION FILE_PATH:所在文件夹
     */
    public static final String FILE_PATH = "D:\\上传报告\\20230116_mNGS正式版报告";
    public static int count = 0;

    //    private static
    public static void main(String[] args) throws Exception {
//        folderMethod1(FILE_PATH);
        init();
    }

    /**
     * 初始化界面窗口
     */
    public static void init() {
        // 创建 JFrame 实例
        JFrame frame = new JFrame("pdf文件重命名");
        // Setting the width and height of frame
        frame.setSize(500, 350);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        /* 创建面板,这个类似于 HTML 的 div 标签
         * 我们可以创建多个面板并在 JFrame 中指定位置
         * 面板中我们可以添加文本字段,按钮及其他组件。
         */
        JPanel panel = new JPanel();
        // 添加面板
        frame.add(panel);
        /*
         * 调用用户定义的方法并添加组件到面板
         */
        placeComponents(panel);

        // 设置界面可见

        frame.setVisible(true);
    }

    /**
     * 设置窗口的面板
     */
    private static void placeComponents(JPanel panel) {

        /* 布局部分我们这边不多做介绍
         * 这边设置布局为 null
         */
        panel.setLayout(null);

        // 创建 JLabel
        JLabel userLabel = new JLabel("文件夹路径:");
        /* 这个方法定义了组件的位置。
         * setBounds(x, y, width, height)
         * x 和 y 指定左上角的新位置,由 width 和 height 指定新的大小。
         */
        userLabel.setBounds(10, 20, 80, 25);
        panel.add(userLabel);

        /*
         * 创建文本域用于用户输入
         */
        JTextField userText = new JTextField(50);
        userText.setBounds(100, 20, 300, 25);


        //实例化文本框
//        JTextArea jta = new JTextArea();
        JTextPane jta = new JTextPane();
        //在文本框上添加滚动条
        JScrollPane jsp = new JScrollPane(jta);

        //设置矩形大小.参数依次为(矩形左上角横坐标x,矩形左上角纵坐标y,矩形长度,矩形宽度)
        jsp.setBounds(10, 70, 450, 180);
        //默认的设置是超过文本框才会显示滚动条,以下设置让滚动条一直显示
        jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        //把滚动条添加到容器里面
        panel.add(jsp);
        panel.add(userText);


        // 创建登录按钮
        JButton loginButton = new JButton("开始执行");
        loginButton.setBounds(10, 270, 120, 25);
        loginButton.addActionListener(e -> {
            try {
                String filePath = userText.getText();
                Thread thread = new Thread(() -> {
                    try {
                        folderMethod1(filePath, jta, jsp);
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                });
                thread.start();
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        });
        panel.add(loginButton);
    }

    /**
     * 寻找文件下的所有pdf
     */

    public static void folderMethod1(String path, JTextPane jta, JScrollPane jsp) throws Exception {

        File file = new File(path);
        LinkedList<File> list = new LinkedList<>();
        //保存所有pdf文件的对象
        LinkedList<File> pdfList = new LinkedList<File>();
        //该路径对应的文件或文件夹是否存在
        if (file.exists()) {
            //如果该路径为---文件或空文件夹
            if (null == file.listFiles()) {
//                System.out.println(file.getAbsolutePath());
                if (file.getAbsolutePath().endsWith(".pdf")) {
                    pdfList.add(file);
                }
            }
            //如果该路径为非空文件夹
            else {
                //将该路径下的所有文件(文件或文件夹)对象加入队列
                list.addAll(Arrays.asList(file.listFiles()));
                //遍历该队列
                while (!list.isEmpty()) {
                    File firstF = list.removeFirst();
                    //这里不论是文件夹还是文件,只需判断是否以“.pdf”结尾
                    if (firstF.getAbsolutePath().endsWith(".pdf")) {
                        pdfList.add(firstF);
                    }
                    File[] files = firstF.listFiles();

                    if (null == files) {
                        //System.out.println(firstF.getAbsolutePath());
                        continue;
                    }
                    for (File f : files) {
                        if (f.isDirectory()) {
                            //System.out.println("文件夹:" + f.getAbsolutePath());
                            list.add(f);
                        } else {
                            //System.out.println("文件:" + f.getAbsolutePath());
                            if (f.getAbsolutePath().endsWith(".pdf")) {
                                pdfList.add(f);
                            }
                        }
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
        //输出所有pdf文件的路径
        for (File f : pdfList) {
            readFile(f.getAbsolutePath(), jta, jsp);
//            System.out.println(f.getAbsolutePath());
        }
    }

    /**
     * 修改文件名
     */

    public static Boolean reNameFile(String oldPath, String newPath) {
        boolean result = new File(oldPath).renameTo(new File(newPath));
        System.out.println("重命名的结果:" + result);
        return result;
    }


    /**
     * 一次获取整个文件的内容
     *
     * @throws Exception
     */
    public static void readFile(String filePath, JTextPane jta, JScrollPane jsp) throws Exception {

        File file = new File(filePath);
        RandomAccessFile is = new RandomAccessFile(file, "r");
        PDFParser parser = new PDFParser(is);
        parser.parse();
        PDDocument doc = parser.getPDDocument();
        PDFTextStripper textStripper = new PDFTextStripper();
        String s = textStripper.getText(doc).replaceAll(" ", "");
        Document document = jta.getDocument();
        File file1 = new File(filePath);
        count++;
        try {
            System.out.println("====================================start");
            System.out.println("姓 名:" + s.substring(s.indexOf("姓名"), s.indexOf("样本ID号")));
            String substring = s.substring(s.indexOf("样本ID号") + 5, s.indexOf("样本类型"));
            System.out.println("样本ID号:" + substring);


            String parent = file1.getParent() + "\\";
            String newName = parent + substring.trim() + ".pdf";



            document.insertString(document.getLength(), "==============第:" + count + "个文件start=================\n", null);
            document.insertString(document.getLength(), "姓 名:" + s.substring(s.indexOf("姓名") + 2, s.indexOf("样本ID号")) + "\n", null);
            document.insertString(document.getLength(), "样本ID号:" + substring + "\n", null);
            document.insertString(document.getLength(), "未修改:" + file1.getAbsolutePath() + "\n", null);
            document.insertString(document.getLength(), "修改为:" + newName + "\n", null);
            JScrollBar scrollBar = jsp.getVerticalScrollBar();    //得到竖直方向的滚动条
            scrollBar.setValue(scrollBar.getMaximum());        //设置滚动条为最大值

            System.out.println("未修改:" + file1);
            System.out.println("修改为:" + newName);
            doc.close();
            Boolean result = reNameFile(filePath, newName);
            document.insertString(document.getLength(), "修改结果:" + (result ? "修改成功" : "修改失败") + "\n", null);
            document.insertString(document.getLength(), "==============第:" + count + "个文件end==============\n", null);

            System.out.println("====================================end");
        } catch (Exception e) {
            document.insertString(document.getLength(), file1.getAbsolutePath()+"文件模板格式发生改变,请自己手动修改一下\n", null);
        }finally {
            doc.close();
        }


    }


}

以下是maven 依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>modify_pdf</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>fontbox</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>jempbox</artifactId>
            <version>1.8.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>xmpbox</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>preflight</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox-tools</artifactId>
            <version>2.0.0</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>jframe.PDFReader</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>