How to create a new word from a template with docx4j

I have the following script and you need some advice:

The user enters a text document as a template and provides some parameters at runtime, so I can query my database and get the data to fill out the document. So there are two main things I need to do:

  • Replace each key in the document with the corresponding result of the current query string.
  • To "merge" (copy? Duplicate?) An existing document without changing it to itself (add) depending on how many lines I received from the request, and replace the keys from this new copy with the following line values.

What is the best aprroach for? At the moment, I have managed to complete the replacement using the unmarshallfromtemplate template, providing it with a hash map. But this method is a bit complicated because I need to add "$ {variable_name}" in the document, and sometimes the word separates the "$ {" and "}" in different tags, causing problems.

I read about xml custom binding, but didn't understand it completely. Do I need to create custom XML, paste it into the document (all this is not runtime) and call applybindings? If so, how would I link the fields in the document with xml? By the name?

+4
source share
1 answer

docx4j includes VariablePrepare, which can tidy up your input docx so that your keys are not split into separate runs.

But you still better switch to linking content management data, especially if you have duplicate data (for example, items on an invoice). Disclosure: I advocate this approach in docx4j.

To apply the content management data binding approach:

  • Create an XML format that makes sense for your data, and write code to convert the database query results into this format.

  • Modify your template so that the content controls snap to the elements of your XML document. usually you use an authoring add-in for Word to help with this. (Microsoft technology uses XPath to bind, so how you bind depends on your XML structure, but, yes, you usually bind to an element name or ID).

  • Now that you have your XML file and the appropriate intput docx, ContentControlsMergeXML contains the code needed to create the instance document at runtime. There's also a version of this for the servlet environment at https://github.com/plutext/OpenDoPE-WAR

As an alternative to 1 and 2, there is also org.docx4j.model.datastorage.migration.FromVariableReplacement during the current night hours that can convert your existing $ {document. Only for standardized target XML format.

If you have additional questions, the forum is dedicated to this topic at http://www.docx4java.org/forums/data-binding-java-f16/

+6
source

All Articles