【问题标题】:How to extract text from .doc document using apache poi?如何使用 apache poi 从 .doc 文档中提取文本?
【发布时间】:2013-03-23 17:57:40
【问题描述】:

我使用下面的一些代码 sn-ps 从 .doc 文件中提取文本

HWPFDocument document = new HWPFDocument(new FileInputStream(inputFile));
Range range = document.getRange();
        int len = range.numParagraphs();
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < len; i++) {
            builder.append(range.getParagraph(i).text());
        }

HWPFDocument document = new HWPFDocument(new FileInputStream(inputFile));
WordExtractor wordExtractor = new WordExtractor(document);
        String[] paragraphs = wordExtractor.getParagraphText();
        StringBuilder builder = new StringBuilder();
        for (String p : paragraphs) {
            builder.append(p);
        }

但是,它们都总是输出一些奇怪的字符。例如:PAGEREF_Toc351848910\h10HYPERLINK\l_Toc351848911CITATIONPla\l1033[HYPERLINK\l"Pla"13]。所以,我想知道从 .doc 文件中提取文本时它们来自哪里以及如何删除它们

提前致谢

【问题讨论】:

  • 您显示的 strange 文本是目录条目、TOC 参考和引文。抱歉,我不知道如何删除它们。
  • 您是否尝试过使用WordExtractor#stripFields(String) 删除它们?
  • 它有效。非常感谢

标签: java ms-word apache-poi doc


【解决方案1】:

我希望这能给你一些见解。

    private static void ConvertDoctoPdf(String src, String outputPdf) throws Exception {

        try {
            Document pdfdoc = new Document();

            HWPFDocument doc = new HWPFDocument(new FileInputStream(src));

            //create wordextractor object to wrap the extracted word from HWPFDocument object.
            WordExtractor we = new WordExtractor(doc);

            OutputStream outputFile = new FileOutputStream(new File(desc));

            //create a pdf writer object to write text to mypdf.pdf file
            PdfWriter.getInstance(pdfdoc, outputFile);

            pdfdoc.open();

            Paragraph para = new Paragraph();

            //Collecting all paragraphs
            String[] paragraphs = we.getParagraphText();

            for (int i = 0; i < paragraphs.length; i++) {
                //add the paragraph to the document
                para.add(paragraphs[i]);
                //para.add(new Chunk(Chunk.NEWLINE));
                }
            //print all paragraph together
            System.out.println(para);    
            //Add all paragraph together to pdfdoc document.
            pdfdoc.add(para);

            pdfdoc.close();
            we.close();
            }  catch (Exception e) {
            e.printStackTrace();

        }
    }

【讨论】:

  • 这似乎是在创建一个 PDF 文档 - 这如何以任何方式解决原始问题?
  • System.out.println(para); 它打印提取的段落。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-24
  • 2013-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-05
相关资源
最近更新 更多