Apache Poi - как удалить все ссылки из документов Word - PullRequest
1 голос
/ 30 января 2012

Я хочу удалить все гиперссылки в документе Word и сохранить текст.У меня есть эти два метода для чтения текстовых документов с расширениями doc и docx.

private void readDocXExtensionDocument(){
    File inputFile = new File(inputFolderDir, "test.docx");
    try {
        XWPFDocument document = new XWPFDocument(OPCPackage.open(new   FileInputStream(inputFile)));
        XWPFWordExtractor extractor = new XWPFWordExtractor(document);
        extractor.setFetchHyperlinks(true);
        String context =  extractor.getText();
        System.out.println(context);
    } catch (InvalidFormatException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private void readDocExtensionDocument(){
    File inputFile = new File(inputFolderDir, "test.doc");
    POIFSFileSystem fs;
    try {
        fs = new POIFSFileSystem(new FileInputStream(inputFile));
        HWPFDocument document = new HWPFDocument(fs);
        WordExtractor wordExtractor = new WordExtractor(document);
        String[] paragraphs = wordExtractor.getParagraphText();
        System.out.println("Word document has " + paragraphs.length + " paragraphs");
        for(int i=0; i<paragraphs.length; i++){
            paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");
            System.out.println(paragraphs[i]);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Можно ли удалить все ссылки в текстовом документе с помощью библиотеки apache poi?Если это не так, есть ли другие библиотеки, которые могут обеспечить это?

1 Ответ

2 голосов
/ 12 октября 2012

Мое решение, по крайней мере для категории .docx, заключается в использовании регулярных выражений. Зацени это

private void readDocXExtensionDocument(){
   Pattern p = Pattern.compile("\\<(.+?)\\>");
   File inputFile = new File(inputFolderDir, "test.docx");
   try {
      XWPFDocument document = new XWPFDocument(OPCPackage.open(new   FileInputStream(inputFile)));
      XWPFWordExtractor extractor = new XWPFWordExtractor(document);
      extractor.setFetchHyperlinks(true);
      String context =  extractor.getText();
      Matcher m = p.matcher(context);
      while (m.find()) {
         String link = m.group(0); // the bracketed part
         String textString = m.group(1); // the text of the link without the brackets
         context = context.replaceAll(link, ""); // ordering important.  Link then textString
         context = context.replaceAll(textString, "");
      }
      System.out.println(context);
   } catch (InvalidFormatException e) {
    e.printStackTrace();
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

Единственное предостережение при таком подходе состоит в том, что если есть материал с этими угловыми скобками, который не является связующим звеном, его тоже можно удалить. Если у вас есть лучшее представление о том, какие ссылки могут отображаться, вы можете использовать более конкретное регулярное выражение вместо того, которое я предоставил.

...