I need to replace certain text in a WinWord document. The problem is, any text replacement I do on a Range with the replaceText function creates a broken WinWord file unless the replacement and replaced strings are both the exact same length. We will be dealing with dynamic content, so this will not do.
Range object specs: http://poi.apache.org/apidocs/org/apache/poi/hwpf/usermodel/Range.html#replaceText(java.lang.String, java.lang.String)
The replaceText function has an optional third parameter, an int, to specify some sort of offset. I thought maybe this could be the solution, but the param can't even handle a negative value, which makes it hard or impossible to do a replacement unless the offset (replacement.length() - replaced.length()) is positive. However, I may need it to be negative. Anyhow, nothing in the docs would seem to imply that this offset param is needed if the two other params aren't equal length.
Here's my code: (let's say a.doc just contains "caaaaaaake")
String inputFilename = "C:\\\a.doc";
String outputFilename = "C:\\b.doc";
POIFSFileSystem fs = null;
FileInputStream fis = new FileInputStream(inputFilename);
fs = new POIFSFileSystem(fis);
HWPFDocument doc = new HWPFDocument(fs);
Range range = doc.getRange();
range.replaceText("caaaaaaake", "piiiie");
FileOutputStream fos = new FileOutputStream(outputFilename);
doc.write(fos);
fis.close();
fos.close();
The code executes no problem, but it creates a broken word file. What can I do?