Apache PDFbox开发指南之PDF文档读取

转载请注明来源:http://blog.csdn.net/loongshawn/article/details/51542309

相关文章:

1、介绍

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

官网地址:https://pdfbox.apache.org/index.html

PDFBox 2.0.1 API在线文档:https://pdfbox.apache.org/docs/2.0.1/javadocs/

2、特征

Apache PDFBox主要有以下特征:
PDF读取、创建、打印、转换、验证、合并分割等特征。

3、开发实战

3.1、场景说明

读取PDF文本内容,样例中为读取体检报告文本内容。

3.2、所需jar包

pdfbox-2.0.1.jar下载地址

fontbox-2.0.1.jar下载地址

将上述两jar包添加到工程库中,如下:
这里写图片描述

3.3、代码编写

创建PdfReader类,编写下述功能函数。

package com.loongshaw;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

public class PdfReader {

    public static void main(String[] args){

        File pdfFile = new File("/Users/dddd/Downloads/0571888890423433356rrrr_182-93201510313223336-2.pdf");
        PDDocument document = null;
        try
        {
            // 方式一:
            /** InputStream input = null; input = new FileInputStream( pdfFile ); //加载 pdf 文档 PDFParser parser = new PDFParser(new RandomAccessBuffer(input)); parser.parse(); document = parser.getPDDocument(); **/

            // 方式二:
            document=PDDocument.load(pdfFile);

            // 获取页码
            int pages = document.getNumberOfPages();

            // 读文本内容
            PDFTextStripper stripper=new PDFTextStripper();
            // 设置按顺序输出
            stripper.setSortByPosition(true);
            stripper.setStartPage(1);
            stripper.setEndPage(pages);
            String content = stripper.getText(document);
            System.out.println(content);     
        }
        catch(Exception e)
        {
            System.out.println(e);
        }

    }

}

3.4、过程说明

PDF文件加载有两种方式,无明显差异,方式二代码较简洁:

// 方式一: 
        InputStream input = null;
        input = new FileInputStream( pdfFile );
        //加载 pdf 文档
        PDFParser parser = new PDFParser(new RandomAccessBuffer(input));
        parser.parse();
        document = parser.getPDDocument();
 // 方式二:
        document=PDDocument.load(pdfFile);                  

3.5、执行结果

这里写图片描述

4、小结

本文仅介绍了利用Apache PDFbox相关开发包读取PDF文本,其他复杂功能暂未涉及,需要大家自己线下探索、尝试。

转载于:https://my.oschina.net/abcijkxyz/blog/724793

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值