2012-01-30 3 views
1

Word 문서의 모든 하이퍼 링크를 제거하고 텍스트를 유지하려고합니다. doc 및 docx 확장자를 가진 워드 문서를 읽는이 두 가지 방법이 있습니다.Apache Poi - Word 문서에서 모든 링크를 제거하는 방법

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 library를 사용하여 워드 문서의 모든 링크를 제거 할 수 있습니까? 그렇지 않은 경우, 이것을 제공 할 수있는 다른 라이브러리가 있습니까?

답변

2

내 솔루션은 적어도 .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(); 
    } 
    } 

이 방법에주의해야 할 점은 그 재료도 제거 할 수 있다는 것을, 링크되지 않습니다 이러한 각도 브래킷이있는 경우. 어떤 종류의 링크가 나타날지 더 잘 알고 있다면 필자가 제공 한 것보다 더 구체적인 정규식을 시도해 볼 수 있습니다.