java解析pdf获取pdf中内容信息

本文对比分析了三种Java解析PDF的方法:使用pdfbox、国产框架Spire.PDF及iTika。详细介绍了各自的优缺点,包括功能特性、中文支持、解析格式及依赖。适合于寻找高效PDF解析方案的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java解析pdf获取pdf中内容信息

今日项目中需要将pdf中的数据获取到进行校验数据,于是前往百度翻来覆去找到以下几种办法,做个笔记,方便日后查询。

废话不多说,我要直接上代码装逼了

第一种 使用开源组织提供的开源框架 pdfbox

api ; https://pdfbox.apache.org/

特点:免费,功能强大,解析中文或许会存在乱码,默认格式有点乱,没有国产解析的那么美化。

想要按行读取:

  		PDFTextStripper stripper = new PDFTextStripper();
            stripper .setSortByPosition(sort); //sort设置为true 则按照行进行读取,默认是false

可以按照指定的模板,对pdf进行修改添加删除等操作,总之操作很骚,很强大。

1 pdfbox 需要带入依赖

  
            <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>

2 代码

package pdf;

import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.util.Iterator;

import javax.imageio.ImageIO;

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 {
   static String fileName = "/Users/pilgrim/Desktop/最近阅读pdf/CPU爆满排查.pdf";
    public static void main(String[] args) throws Exception {

        readFile();
        readPage();
        readTextImage();
        readRectangle();
    }

    /**
     * 一次获取整个文件的内容
     *
     * @throws Exception
     */
    public static void readFile() throws Exception {
        File file = new File(fileName);
        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);
        System.out.println("总页数:" + doc.getNumberOfPages());
        System.out.println("输出内容:");
        System.out.println(s);
        doc.close();
    }

    /**
     * 分页获取文字的内容
     *
     * @throws Exception
     */
    public static void readPage() throws Exception {
        File file = new File(fileName);
        RandomAccessFile is = new RandomAccessFile(file, "r");
        PDFParser parser = new PDFParser(is);
        parser.parse();
        PDDocument doc = parser.getPDDocument();
        PDFTextStripper textStripper = new PDFTextStripper();
        for (int i = 1; i <= doc.getNumberOfPages(); i++) {
            textStripper.setStartPage(i);
            textStripper.setEndPage(i);
            // 一次输出多个页时,按顺序输出
            textStripper.setSortByPosition(true);
            String s = textStripper.getText(doc);
            System.out.println("当前页:" + i);
            System.out.println("输出内容:");
            System.out.println(s);
        }
        doc.close();
    }

    /**
     * 读取文本内容和图片
     *
     * @throws Exception
     */
    public static void readTextImage() throws Exception {
        File file = new File(fileName);
        PDDocument doc = PDDocument.load(file);
        PDFTextStripper textStripper = new PDFTextStripper();
        for (int i = 1; i <= doc.getNumberOfPages(); i++) {
            textStripper.setStartPage(i);
            textStripper.setEndPage(i);
            String s = textStripper.getText(doc);
            System.out.println("第 " + i + " 页 :" + s);
            // 读取图片
            PDPage page = doc.getPage(i - 1);
            PDResources resources = page.getResources();
            // 获取页中的对象
            Iterable<COSName> xobjects = resources.getXObjectNames();
            if (xobjects != null) {
                Iterator<COSName> imageIter = xobjects.iterator();
                while (imageIter.hasNext()) {
                    COSName cosName = imageIter.next();
                    boolean isImageXObject = resources.isImageXObject(cosName);
                    if (isImageXObject) {
                        // 获取每页资源的图片
                        PDImageXObject ixt = (PDImageXObject) resources.getXObject(cosName);
                        File outputfile = new File("第 " + (i) + " 页" + cosName.getName() + ".jpg");
                        ImageIO.write(ixt.getImage(), "jpg", outputfile);
                    }
                }
            }
        }
        doc.close();
    }

    /**
     * 区域解析
     *
     * @throws Exception
     */
    public static void readRectangle() throws Exception {
        String filePath = fileName;
        File file = new File(filePath);
        PDDocument doc = PDDocument.load(file);
        // 这个四边形所在区域在 y轴向下为正,x轴向右为正。
        int x = 35;
        int y = 300;
        int width = 50;
        int height = 50;
        PDFTextStripperByArea stripper = new PDFTextStripperByArea();
        stripper.setSortByPosition(true);
        // 划定区域
        Rectangle2D rect = new Rectangle(x, y, width, height);
        stripper.addRegion("area", rect);
        PDPage page = doc.getPage(1);
        stripper.extractRegions(page);
        // 获取区域的text
        String data = stripper.getTextForRegion("area");
        data = data.trim();
        System.out.println(data);
        doc.close();
    }
}

第二种 使用国产的框架 Spire.PDF

#####包含两种版本
1 免费版
https://www.e-iceblue.cn/Downloads/Free-Spire-PDF-JAVA.html

友情提示: 免费版有 10 页的页数输出限制,在输出结果文档时只能输出前10页。将 PDF 文档转换为图片、Word、HTML、XPS等格式时,仅支持转换前 10 页。如超出限制,可升级到商业版,我们仅对免费版进行不定期维护。

2 商业版本
https://www.e-iceblue.cn/Introduce/Spire-PDF-JAVA.html

api
http://e-iceblue.cn/licensing/install-spirepdf-for-java-from-maven-repository.html

特点:商业版本收费,免费版本有限制,可供开发人员调试,解析格式友好,解析结果是按照行显示,对pdf 图形 ,水印 ,文本, 条形码等添加增删改操作,总之个人感觉比pdfbox顺手,但就是收费啊,谁让咱公司没钱呢。

主要功能

只需 Free Spire.PDF for Java,无需 Adobe Acrobat
Free Spire.PDF for Java 是一款完全独立的 PDF 类库。它的运行环境无需安装 Adobe Acrobat 或其他任何第三方组件。
多样化的PDF文档操作功能
Free Spire.PDF for Java 支持画文本、图片、表格、条形码、形状到 PDF,提取文本和图片,创建、填充和删除 PDF 表单,添加文本/图片水印到 PDF,添加、更新和删除 PDF 书签,操作超链接、附件和注释,以及添加图片/文本印章到 PDF 等。
文档信息设置
Free Spire.PDF for Java 支持设置 PDF 文档信息,例如文档属性设置,偏好设置(页面方向,页面大小,缩放比例等)。
高质量的文档转换功能
Free Spire.PDF for Java 支持将 PDF 文档高质量地转换为 Word、HTML、XPS、图片、SVG 和 PDF/A 格式,以及将 XPS 文档高质量地转换为 PDF 格式。
文档安全性设置
Free Spire.PDF for Java 支持给 PDF 文档添加和验证数字签名,加密和解密 PDF 文档,修改 PDF 文档的安全权限,以及检测签名后的 PDF 文档是否被修改。
易于集成
开发人员可以轻易地将 Free Spire.PDF for Java 集成到 Java(J2SE和J2EE)应用程序中。

api 更多功能如下图
在这里插入图片描述

在这里插入图片描述
1 仓库地址 和 依赖

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
</repositories>
<dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf.free</artifactId>
        <version>2.2.2</version>
    </dependency>
<

2 代码

//创建PdfDocument实例
PdfDocument doc = new PdfDocument();
//加载PDF文件
doc.loadFromFile("C:\\Users\\tizzy\\Desktop\\测试.pdf");

//创建StringBuilder实例
StringBuilder sb = new StringBuilder();

PdfPageBase page;
//遍历PDF页面,获取每个页面的文本并添加到StringBuilder对象
for(int i= 0;i<doc.getPages().getCount();i++){
    page = doc.getPages().get(i);
    sb.append(page.extractText(true));
}
FileWriter writer;
try {
    //将StringBuilder对象中的文本写入到文本文件
    writer = new FileWriter("ExtractText.txt");
    writer.write(sb.toString());
    writer.flush();
} catch (IOException e) {
    e.printStackTrace();
}

doc.close();

解析后格式内容如图

在这里插入图片描述

第三种 使用iTika 进行解析pdf

api : https://tika.apache.org/

对中文支持不是很友好,解析的格式和pdfbox类似

1依赖


        <!-- https://mvnrepository.com/artifact/org.apache.tika/tika-core -->
        <dependency>
            <groupId>org.apache.tika</groupId>
            <artifactId>tika-core</artifactId>
            <version>1.20</version>
        </dependency>

2 代码

public static String getPdfFileText(String fileName) throws IOException {
       PdfReader reader = new PdfReader(fileName);
       PdfReaderContentParser parser = new PdfReaderContentParser(reader);
       StringBuffer buff = new StringBuffer();
       TextExtractionStrategy strategy;
       for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            strategy = parser.processContent(i,
                      new SimpleTextExtractionStrategy());
            buff.append(strategy.getResultantText());
           }
       return buff.toString();
      }

解析后内容格式类似pdfbox

总结

几种方式各有利弊,开源也罢,闭源也罢,其中利弊自己权衡。

评论 50
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TizzyGoodhealth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值