Class VariableReplace

java.lang.Object
org.docx4j.samples.VariableReplace

public class VariableReplace extends Object
There are at least 3 approaches for replacing variables in a docx. 1. as shows in this example (but consider VariableReplaceStAX instead!) 2. using Merge Fields (see org.docx4j.model.fields.merge.MailMerger) 3. binding content controls to an XML Part (via XPath) Approach 3 is the recommended one when using docx4j. See the ContentControl* examples, Getting Started, and the subforum. Approach 1, as shown in this example, works in simple cases only. It won't work if your KEY is split across separate runs in your docx (which often happens), or if you want to insert images, or multiple rows in a table. You're encouraged to investigate binding content controls to an XML part. There is org.docx4j.model.datastorage.migration.FromVariableReplacement to automatically convert your templates to this better approach. OK, enough preaching. If you want to use VariableReplace, your variables should be appear like so: ${key1}, ${key2} And if you are having problems with your runs being split, VariablePrepare can clean them up.
  • Constructor Details

    • VariableReplace

      public VariableReplace()
  • Method Details

    • main

      public static void main(String[] args) throws Exception
      Throws:
      Exception
    • newlineToBreakHack

      private static String newlineToBreakHack(String r)
      Hack to convert a new line character into w:br. If you need this sort of thing, consider using OpenDoPE content control data binding instead.
      Parameters:
      r -
      Returns: