您的位置:首页 > 编程语言 > Java开发

java解析PDF文件,并获取到指定数据.Eg

2017-11-24 15:38 597 查看
    在工作中,需要将PDF文件中的部分数据读取出来,那怎样获取到有用的数据呢?废话少说,直接上货!



import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import org.apache.pdfbox.pdfparser.PDFParser;

import org.apache.pdfbox.pdmodel.PDDocument;

import org.apache.pdfbox.util.PDFTextStripper;

/* 2017.11.24
* 解析pdf文件中的编号
* */
public class getInfoFromPDF {
private static String result = null;  // 用来保存pdf文件中的信息
   private static FileInputStream is = null;  // 输入流
   private static PDDocument document = null;   
//获取pdf文件中的编号

    public static String getAllInfoFromPDF(String pdfFilePath){  

        String result = null;  

        FileInputStream is = null;  

        PDDocument document = null;  

        try {  

            is = new FileInputStream(pdfFilePath);  

            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();  

                }  

            }  

        }  

        return result;  

    }  
public static void main(String[] args) throws IOException {
/*  
* 通过递归得到某一路径下所有的目录及其PDF文件
*/
// 通过传入文件路径获取文件
File file = new File("F:\\pdf文件解析");
// 把获取到的文件名保存在数组中
   File[] files = file.listFiles();
   for(File f:files){
    //获取文件类型,即文件后缀名
    int start = f.getAbsolutePath().length()-3;
    int end  = f.getAbsolutePath().length();
    //得到文件的后缀名
    String pdf = f.getAbsolutePath().substring(start, end);
    //判断是否是pdf格式的文件
    if(pdf.equals("pdf") || pdf.equals("PDF")){
    // 是pdf格式的文件
    //得到全部pdf文件中的信息
    String str = getInfoFromPDF.getAllInfoFromPDF(f.getAbsolutePath());
    //截取pdf文件中的编号
    String code = str.substring(str.indexOf(":")+1,str.indexOf(":")+27);
    System.out.println("解析pdf文件后编号为:"+code); 
    }
   }
}

注:记得添加jar哦!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  pdf 解析pdf pdf转化
相关文章推荐