While MS Word support in Apache POI is not very good. Downloading and then saving any file other than the main formatting will most likely distort the layout. You should try, although perhaps this works for you.
There are also a number of commercial libraries, but I do not know if there are any of them.
The crappy "solution" that I had to deal with when working with a similar requirement recently was to use the DOCX format, which opens a ZIP container, read an XML document, and then replace my markers with the necessary texts. This works to replace simple bits of text without paragraphs, etc.
private static final String WORD_TEMPLATE_PATH = "word/word_template.docx"; private static final String DOCUMENT_XML = "word/document.xml"; final Resource templateFile = new ClassPathResource(WORD_TEMPLATE_PATH); final ZipInputStream zipIn = new ZipInputStream(templateFile.getInputStream()); final ZipOutputStream zipOut = new ZipOutputStream(output); ZipEntry inEntry; while ((inEntry = zipIn.getNextEntry()) != null) { final ZipEntry outEntry = new ZipEntry(inEntry.getName()); zipOut.putNextEntry(outEntry); if (inEntry.getName().equals(DOCUMENT_XML)) { final String contentIn = IOUtils.toString(zipIn, UTF_8); final String outContent = this.processContent(new StringReader(contentIn)); IOUtils.write(outContent, zipOut, UTF_8); } else { IOUtils.copy(zipIn, zipOut); } zipOut.closeEntry(); } zipIn.close(); zipOut.finish();
I'm not proud of it, but it works.
Henning
source share