Home Caching of basic XWPFDocument templates and reusing them for document generation
Reply: 0

Caching of basic XWPFDocument templates and reusing them for document generation

user2732 Published in March 18, 2018, 1:51 am

We are implementing a portal handling requests for modifying and generating Microsoft Office 2007 documents (docx).The back-end is implemented in Java using Apache POI as the API of manipulating the contents of the docx files. The back-end is accessed through RestAPI calls coming from a front-end written in JavaScript.

The back-end acts like a Document Server that handles about 15 different docx documents which act as templates and contain tokens that need to be replaced with actual values. The requests coming from the front-end are actually a token value map that the back-end needs to replace in the templates and generate a new document, for each request. The workflow is as follows:

  • receive request from front-end: token-value map
  • read template document as XWPFDocument object
  • parse and replace text in all XWPFParagraph/XWPFTable elements of the XWPFDocument
  • write the modified XWPFDocument to a different file path

I am trying to implement a caching mechanisms at the moment, it is a real performance issue going to the disk and reading the files for each request. I would need to treat each template document as a Prototype and return a clone for each request that the back-end receives, something similar to this:

XWPFDocument theDocument = documentCache.clone(documentConfiguration.getInputType());

The clone method is currently implemented as follows:

public XWPFDocument clone(DocumentDictionary.DocumentType type){


    XWPFDocument document = null;
    try {
        document = new XWPFDocument(PACKAGE_MAP.get(type));
    }catch(IOException exception){
        logger.error("Unable to clone document for input type {}", type);

    return document;

This implementation does not yield the desired results, the first request processing works as expected, but the second request fails when writting the document with the error:

Caused by: org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.

The exception above does not replicate in the case of reading the document fresh at each request. Looking at the Apache POI API, the clone() methods for XWPFDocument and ZipPackage, used in the reading/writting process are protected, so I cannot use the basic functionality offered by the programming language and the issues seems to come from the fact that the ZipPackage is shared and used in both the reading/writting of the document.

Has anyone been able to implement such a mechanism using Java and Apache POI?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.299129 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO