Generate PDF Using String Template Rajani Jilla December 20, 2017

Generate PDF Using String Template

Generate PDF Using String Template
This blog details about using a StringTemplate library to generate PDF documents dynamically. Before we look into the implementation, let’s first understand what is all about StringTemplate’s.

What Is StringTemplate?

  • StringTemplate is a template engine library used for generating source code, web pages, emails, or any other formatted text output.
  • It supports generating the templates like emails, documents, newsletters, web pages, code generator.
  • It depends on ANTLR (Another Tool For Language Recognition) to parse the string template language.
  • One of the important characteristics is that it clearly separates the model (business logic) from view.


  • Using this, we can ensure the business logic, the computation required to generate the structured text does not have a dependency on how it is represented on the user interface.
  • Application admin can have full control and flexibility on the entity attributes of a template to modify and change the representation at any point in time.
  • Templates can be reused across similar kind of applications.
  • A library is capable of supporting if else conditions to render the content required based on the conditions. 


Since the library internally uses Reflexion pattern, feature well suits for the application where file count is less to generate from a template.


To use this, we need to download the StringTemplate library. For example, Let’s assume a use case where an application has a form which will be filled by users to register and export the same as PDF file and print it for future use.

Following are the details that user will be filling in:

  • First Name
  • Last Name
  • Mobile Number
  • Email ID
  • Pin Code
  • City

And all these attributes belong to an entity naming “User”. Now let’s say we have a template file ( with below HTML:


And to export user data to PDF, we will have to pass the key name and user object as value to the template. Template engine will parse the template content and replaces the attributes with user object data dynamically at runtime using the delimiter mentioned as “$”. Output content with actual data can be used for generating the PDF.


We can also add multiple keys to the template engine as below:


If you’d like to learn more about this topic, please feel free to get in touch with one of our experts for a personalized consultation.