在Java中,利用poi处理pdf、doc、docx文档

一:处理PDF文档

  处理PDF文档需要引用pdfbox-app-1.8.7.jar的jar包(ps:版本应该没有具体要求)。

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

private static String getPDFText(File file){
        PDDocument document;
        String text = "";
        try {
            document = PDDocument.load(file);
            PDFTextStripper stripper = new PDFTextStripper();
            text = stripper.getText(document);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return text;
    }

二:处理doc文档

  处理doc文档需要引入poi-3.10.1-20140818.jar和poi-scratchpad-3.10.1-20140818.jar

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
 
public String getDocContent(File docFile){     
        FileInputStream docFis;
        String text = null;
        try {
            docFis = new FileInputStream(docFile);
            HWPFDocument doc = new HWPFDocument(docFis);
            Range rang = doc.getRange();
            text = rang.text();
            docFis.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return text;     
    } 

三:处理docx文档

  处理docx文档需要引入poi-ooxml-3.10.1-20140818.jar和poi-ooxml-schemas-3.10.1-20140818.jar以及xmlbeans-2.3.0.jar(ps:使用的XWPFWordExtractor()中用到了xmlbeans-2.3.0.jar中的类。)

import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public String getDocxContent(File docxFile){     
        FileInputStream docxFis;
        String text = null;
        try {
            docxFis = new FileInputStream(docxFile);
            XWPFDocument docx = new XWPFDocument(docxFis);
            XWPFWordExtractor docxExtractor = new XWPFWordExtractor(docx);
            text = docxExtractor.getText();
            docxFis.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return text;     
    }

 

转载于:https://www.cnblogs.com/tangxiaolang/p/4110029.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值