Reputation: 3270
i need to add a simple text (From another .txt or .doc file) to a .doc file the code is very simple :
public static void main(String[] args) throws IOException {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("/home/amira/work/APPS-579/word/test1.doc"));
HWPFDocument doc = new HWPFDocument(fs);
Range range = doc.getRange();
CharacterRun run = range.insertAfter("Hello World!!! It works well!!!");
run.setBold(true);
run.setItalic(true);
run.setCapitalized(true);
OutputStream out = new FileOutputStream("/home/amira/work/APPS-579/word/sampleAfter.doc");
doc.write(out);
out.flush();
out.close();
}
The new sampleAfter.doc is created but only contains the content of test1.doc : the "Hello World!!! It works well!!!" string has not been added .
I tried so to use the
range.insertBefore(String text)
method so it works and the string is added before the content of test1.doc.
I really don't get it. Is there an explanation for this issue.
Here's the content of test1.doc :
Voilà mon premier test le 24/03/24
Here's the result of : System.out.println(range.text());
With an insertBefore :
- Hello World!!! It works well!!!Voilà mon premier test le 24/03/24
With an insertAfter :
Voilà mon premier test le 24/03/24
Hello World!!! It works well!!!
Upvotes: 0
Views: 191
Reputation: 1757
Well, the above code seems to work for me. I guess it would be better to follow the following approach
Range r1 = doc.getRange();
Section sec = r1.getSection(r1.numSections()-1);
Paragraph para = sec.getParagraph(sec.numParagraphs()-1);
CharacterRun run = para.getCharacterRun(para.numCharacterRuns()-1);
run.insertAfter("Hello World!!! It works well!!!");
run.setBold(true);
run.setItalic(true);
run.setCapitalized(true);
Upvotes: 1