How to create HWPF document with apache poi

3.2k Views Asked by At

Please somebody help me with putting text into paragraphs. I have this code :

private void createDOCDocument(String from, File file) throws Exception {

    POIFSFileSystem fs = new POIFSFileSystem(DOCGenerator.class.getClass().getResourceAsStream("/poi/template.doc"));
    HWPFDocument doc = new HWPFDocument(fs);
    Range range = doc.getRange();
    Paragraph par1 = range.insertAfter(new ParagraphProperties(), 0);    
    CharacterRun run1 = par1.insertAfter(from);
    run1.setFontSize(11);
    DocumentSummaryInformation dsi = doc.getDocumentSummaryInformation();
    CustomProperties cp = dsi.getCustomProperties();
    if (cp == null)
        cp = new CustomProperties();
    cp.put("myProperty", "foo bar baz");
    dsi.setCustomProperties(cp);
    doc.write(new FileOutputStream(file));

}

But the problem is that if I put the "from" string directly into the range, it will be in the resulting document, but if I create a paragraph and put it in there instead, the document is empty. Even if I process it with apache tika and its WordExtractor, it gets nothing.

btw /poi/template.doc is empty document.

If I do it like this :

Paragraph par1 = range.getParagraph(0);
CharacterRun run1 = par1.insertAfter(from);

and from is "whatever" then in the document there is "w" (the initial) character at the beginning ... What the hell is this ?

1

There are 1 best solutions below

0
On

Try with a recent nightly build / svn checkout of POI. The HWPF codebase is currently being heavily worked on by Sergey, and bugs like the one you've described have recently been fixed.