RTF Template

Overview

RTFTemplate is RTF engine RTF to RTF, which is able to generate RTF by merging template RTF (model RTF source) with JAVA object (context). RTFTemplate use Velocity for merging template with JAVA object. Use case with RTF template is :

  • design your RTF template with MS Word by using MERGEFIELD, HYPERLINK and BOOKMARK (cf. RTF specification).
  • put context with JAVA Object.
  • merge your RTF template with JAVA object by using RTFTemplate.
  • after merging, MERGEFIELD/HYPERLINK are replaced by JAVA objects value putted into context and BOOKMARK are used for loop on list of JAVA object (eg : to generate RTF Table (several RTF Row) by iterating on objects of the list).

It exist too version of RTFTemplate for C#. Go to NRTFTemplate page for more information.

Steps for generate RTF

Two steps are necessary for RTF generation if RTF model (source) is designed by MS Word :

  • Step 1: new RTF template must be created by adding velocity macro to the RTF source model. On other words, MERGEFIELD/HYPERLINK must be replaced by value (velocity syntax $object.value) and BOOKMARK must be replaced by velocity macro #foreach.
  • Step 2 : merge template velocity (created into step 1) with JAVA objects by using Velocity Engine. Result of merge give the RTF target with values.

RTF model Example

Here an example of RTF model source designed by MS Word:

After merging RTF model source with context, RTF target generated is :

How use RTFTemplate

Here example code for generate RTF (Step 1 and 2) :

  /*
   * Create a new instance of the VelocityEngine
   * Using stock configuration in this example, but this could instead be the VelocityEngine in general 
   * use by your servlet(s) for example
   */
  VelocityEngine ve = new VelocityEngine();
  ve.init();

  /*
   * Create a new RTFTemplateEngine
   */
  RTFTemplateEngine engine = new RTFTemplateEngine( ve );
  
  /*
   * Set any common formatting objects on the engine - these will be passed through to each template it creates
   */
  engine.setDefaultFormat(Date.class, DateFormat.getDateInstance());
  
  /*
   * Create a common inner context
   */
  Context ctx = new VelocityContext();
  ctx.put("date", new Date());  
  
  /*
   * Create and merge template for the model of Project Velocity
   */
  RTFTemplate template = engine.createTemplate( new File("source_project.rtf") );
  template.setInnerContext( ctx );
  template.put("project", new Project("Jakarta Velocity project"));
  template.merge("project_velocity.rtf.out.rtf");
  
  /*
   * Create and merge template for the model of Project RTFTemplate
   */
  template.put("project", new Project("RTFTemplate Project"));
  template.merge("project_rtftemplate.rtf.out.rtf");