I'm trying to automate modification of a few docx files with various layouts that I did not create myself with Apache POI (5.2.3). After I've made the edits (i.e. remove headers/footers and remove a few paragraphs whose text matches some expected content) I then want to trim any leading whitespace/newlines that might have been leftover after the removal of content.
This works fine for some of the docs I'm working with, but for one of them, there's a piece of content that's being removed even though it has text. The green shape below, which contains the bordered box with "Some Title and Some Sub-Title" is being removed by my code, but I don't understand how. The first paragraph that's encountered that is considered non-empty of text is "Some Header Here".
I'm tracking down all paragraphs starting from the beginning of the doc and trying to scoop up all text from any function that would return any. Is there some other way to access the text that I'm not trying?
private static void trimContent(XWPFDocument doc) {
List<XWPFParagraph> pgToRemove = new ArrayList<>();
List<XWPFParagraph> allParagraphs = doc.getParagraphs();
addLeadingEmptyParagraphs(allParagraphs, pgToRemove);
for (XWPFParagraph pg : pgToRemove) {
doc.removeBodyElement( doc.getPosOfParagraph(pg) );
}
}
private static void addLeadingEmptyParagraphs(
List<XWPFParagraph> allParagraphs, List<XWPFParagraph> pgToRemove) {
//
for (int pgIdx = 0; pgIdx < allParagraphs.size(); pgIdx++) {
XWPFParagraph pg = allParagraphs.get(pgIdx);
StringBuilder pgTextBuilder = new StringBuilder();
StringBuilder runTextBuilder = new StringBuilder();
String pgText = pg.getText().trim();
String pgParaText = pg.getParagraphText().trim();
String pgPicText = pg.getPictureText().trim();
String pgFootText = pg.getFootnoteText().trim();
if (pgText != null) pgTextBuilder.append(pgText.trim());
if (pgParaText != null) pgTextBuilder.append(pgParaText.trim());
if (pgPicText != null) pgTextBuilder.append(pgPicText.trim());
if (pgFootText != null) pgTextBuilder.append(pgFootText.trim());
for ( XWPFRun run : pg.getRuns() ){
String runTxt = run.text();
String runPic = run.getPictureText();
if (runTxt != null) runTextBuilder.append(runTxt.trim());
if (runPic != null) runTextBuilder.append(runPic.trim());
}
if ( runTextBuilder.toString().isEmpty() && pgTextBuilder.toString().isEmpty() ){
pgToRemove.add(pg);
System.out.println( String.format("Empty [%d]", pgIdx));
}
else {
System.out.println( String.format("Text [%d] => [%s]", pgIdx, pgText));
break;
}
}
}
