Apache Poi - как удалить все ссылки из документов Word
Я хочу удалить все гиперссылки в документе 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 ответ
Мое решение, по крайней мере для категории.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();
}
}
Единственное предостережение при таком подходе состоит в том, что если есть материал с этими угловыми скобками, который не является связующим звеном, его тоже можно удалить. Если у вас есть более четкое представление о том, какие ссылки могут появляться, вы можете использовать более конкретное регулярное выражение вместо того, которое я предоставил.