I have developed a Java code which replaces some string patterns in a template and then generates a output docx file, using Apache POI. It was easy to replace the patterns in the headers and paragraphs, but I got an issue while trying to replace inside textboxes. I am using the code provided by Axel Ritcher in Replace text in text box of docx by using Apache POI, but the problem is that it is trimming some white spaces on each run.
For example:
cp -r basedir destination
Becomes:
cp-r basedir destination
The part of the code responsible for doing this substitution is this (The parameters of the function are: doc_buffer is a XWPFDocument, pattern and replacement are both Strings):
for (XWPFParagraph paragraph : doc_buffer.getParagraphs()) {
XmlCursor cursor = paragraph.getCTP().newCursor();
cursor.selectPath(
"declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//*/w:txbxContent/w:p/w:r");
List<XmlObject> ctrsintxtbx = new ArrayList<XmlObject>();
while (cursor.hasNextSelection()) {
cursor.toNextSelection();
XmlObject obj = cursor.getObject();
ctrsintxtbx.add(obj);
}
for (XmlObject obj : ctrsintxtbx) {
CTR ctr = CTR.Factory.parse(obj.toString());
XWPFRun bufferrun = new XWPFRun(ctr, (IRunBody) paragraph);
String text = bufferrun.getText(0);
if ((text != null) && (text.contains(pattern))) {
text = text.replaceAll(pattern, replacement);
bufferrun.setText(text, 0);
}
obj.set(bufferrun.getCTR());
}
}
If you need any additional information, please let me know.
Thanks in advance!
Somehow I have managed to find the issue that was causing this. I'll post it here so if anyone have the same problem, they can see how I have solved.
The method CTR.Factory.parse used on the example required a String type, but if you check the XmlObject.Factory docs, there are many parse function which require different types of parameters to use. So I have changed this line:
CTR ctr = CTR.Factory.parse(obj.toString());
To the method that accepts XMLInputStream as argument, and then created a new InputStream for the XmlObject:
CTR ctr = CTR.Factory.parse(obj.newInputStream());