Contact us Blog

Generating Word and PDF documents

View Video This page is specifically about generating Word (.docx) and .pdf documents from .docx templates. We assume here that you are familiar with how to use Apsona's merge tool.

The video at right illustrates how to use the tool for generating Word documents. If you like, you can download the template used in the video.

What is a template?

A template is just a .docx file created with either Microsoft Word, Google Docs or LibreOffice Writer. It contains all the boilerplate text, images and formatting needed for the finished document, along with place-holder merge fields that will be replaced with actual data values when the template is processed into a finished document.

Naming your merge fields

In a Word (.docx) template, Apsona recognizes merge fields created using Word's standard tools. For example, with Word 2010, you would use the Insert - Quick Parts - Merge field tool, just as you would for creating any merge document. Apsona recognizes all merge fields in your Word document, so you don't need to adhere to any specific naming constraints with your field names. By the way, creating merge fields in Word can be a bit tedious, and there is an easier way.

Using Google Docs, OpenOffice or LibreOffice Writer documents

Google Docs, OpenOffice or LibreOffice can all be used to create documents in .docx format, but these tools do not support merge fields in the manner supported by Microsoft Word. Therefore, when using templates created with these tools, Apsona's document merge tool recognizes "simple" merge fields — plain text strings typed in the format <<TotalProjectCost>>, i.e., names surrounded by double angle brackets. Merge field names set up in this syntax must contain only alphabets, numerals or the underscore, e.g., <<Total Cost>> would not be a recognized merge field because of the embedded space.

We also recommend some extra measures when creating these angle-bracket-based merge fields. If you create part of such a field and then edit the field's name, the internal document structure can change sufficiently that Apsona is unable to recognize the field as a merge field, so that field would no longer appear among the mappable choices. To avoid this situation, we recommend creating the entire field, including angle brackets, in a plain text editor such as Notepad, and copy-pasting it into the document. Subsequently, if you need to change its name, remove it entirely and re-create it. Below is an animation that illustrates this process.

Using this angle-bracket-based syntax is not very reliable in Microsoft Word, because Microsoft Word is quite finicky about spelling checks for such pieces of text, and that can render these merge fields unrecognizable. You can tell Word to ignore the spell check. When you notice a red squiggly line indicating a spelling error under your merge field name, you can right-click on the text and choose "Ignore All" . Even with the ignored spelling, however, we have found that Word renders the field unusable in some situations, so the most reliable way to create merge fields in Word is using the standard Insert - Quick Parts - Field mechanism described above.

Please keep in mind that if you have created a template using this angle-bracket-based syntax, you should not open or save it in Microsoft Word, because as noted above, Word can change the internal representation of the merge field so that Apsona cannot recognize it. If using Google Docs, simply download the document in .docx format (via the File - Download as - Microsoft Word .docx menu) and upload the downloaded file into your Salesforce Document object.

Specifying field format

You can set up the formats for date and currency fields in the last step of the merge action, as in the screen shot below. The date format you specify in this popup applies to all date fields produced by the merge. Similarly, the currency format applies to all its currency fields.

You can also specify the format of the field data as part of the merge field, by including it after an @ sign. This formatting feature is currently limited to date, datetime and time-of-day values only.

Below is a screen shot that illustrates how to set up a format string for a date field. (This screen shot shows a field from Microsoft Word, but the same syntax can be used for Google Docs and LibreOffice merge fields.) The merge field is named ReportDate, immediately followed by an @ sign and a format specifier. In this example, it requires the date value to be rendered in the format MMM d, yyyy, e.g., August 9, 2018. So the format specifier is a piece of text that contains format codes arranged as needed, with spaces or commas between them.

Below is a list of the format codes that Apsona recognizes. Note that format codes are case-sensitive. (These are the same format codes recognized by the formatString function in Apsona's JavaScript function library.)

Format codes for date and datetime fields

yyyyFour digit year, e.g., 2017
M One- or two-digit month, e.g., 1 for January and 10 for October
MM Two-digit month with a leading zero if necessary, e.g., 01 for January and 10 for October
MMM Three-letter month name, e.g., Feb for February
MMMMFull month name, e.g., October
d One- or two-digit date
dd Two-digit date with a leading zero if necessary
EE Full weekday name, e.g., Monday
E Three-letter weekday name, e.g., Mon
HH Two-digit hour of day, in 24-hour format
hh Two-digit hour of day, in 12-hour format, with leading zero if needed
h Hour of day in 12-hour format
mm Two-digit minute of hour, with leading zero if needed
ss Two-digit seconds, with leading zero if needed
a AM/PM indicator

Format codes for time-of-day fields

These are essentially the same as for datetime fields, except that only format codes for the time part are recognized; date format codes are not.
HH Two-digit hour of day, in 24-hour format
hh Two-digit hour of day, in 12-hour format, with leading zero if needed
h Hour of day in 12-hour format
mm Two-digit minute of hour, with leading zero if needed
ss Two-digit seconds, with leading zero if needed
a AM/PM indicator


Here are a few more examples showing a specific date and time:

MMM d, yyyy HH:mmProduces Aug 9, 2017 18:03
MM/dd/yyyy h:mm aProduces 08/09/2017 6:03 pm
M/d/yyyyProduces 8/9/2017

"Text before" and "Text after" choices in Word templates

You can also use the "text before" and "text after" options for merge fields in Word templates - see screen shot below. This enables you to include additional text either before or after a merge field's value, but only if the field contains a non-empty value. In other words, if the field does not produce a value in the document (e.g., for the screen shot below, the Last name field is empty), then the text specified as "text before" is not produced, either. This lets you provide bits of text that separate the content from merge fields.

Sub-lists in Word templates

In many situations, we would want to produce Word documents in which each output document contains a sub-list. Apsona's merge tool includes extensive support for sublists.

Support for PDF files

When generating documents from Word .docx templates, or sending email with attachments, you can optionally specify that the output should be generated in .pdf format, by selecting the corresponding option in step 2.

If you select this option, you can perform any of the functions available with .docx documents:
  • generate one PDF file for each merge record, and download the PDF files as part of the generated .zip file;
  • attach that PDF file to a Salesforce record, or attach it to the outgoing email generated by the merge tool;
  • generate a single PDF file containing the results of all the generated documents, separated by page breaks or paragraph breaks, just as you can with .docx files.
You can also set up a button in a Salesforce record detail page to generate the PDF document. See this article for information about creating buttons.

The PDF generation process

When generating .docx files, Apsona uses a technique that produces all the needed .docx files entirely within the browser, without involving any third party servers. Thus all data traffic occurs between your browser and the Salesforce servers. But when generating PDF files, no such technique is available. So Apsona first generates the .docx versions and then converts them to PDF format. This conversion is performed by Apsona servers dedicated specifically for PDF conversion. Therefore, when you request PDF format, there is a noticeable impact on application speed and performance, because of the network traffic between your browser and the Apsona servers.

Data security

It is worth pointing out here that the only data that is exchanged between your browser and the Apsona servers is the .docx and .pdf files. When converting a particular .docx file to PDF format, Apsona hands the .docx file to one of the Apsona PDF conversion servers, waits for the converted result, and then delivers the result to you in the browser. For its part, the PDF conversion server performs the conversion using internal tools. The server retains the converted PDF file on its local file storage for no more than two hours, after which the files are automatically removed.

PDF file size limits

Owing to the performance and network latency consequences of the PDF conversion process, Apsona limits the size .docx files to be converted. Any given .docx file to be converted cannot exceed 1 MB in size. This limit applies only when converting to PDF files; it does not apply if you are generating .docx files. Ordinarily, this is quite sufficient. If, however, you need to produce a large document (say, a few thousand envelopes or invoices all in one file), you can either (a) produce separate PDF files, one for each data record, or (b) produce the file in .docx format (which will not incur the size limit), download the .docx file, and convert it to PDF locally on your desktop or laptop using standard word processing tools (e.g., Microsoft Word, LibreOffice Writer or Google Docs).

Microsoft Word templates and PDF output

When converting the results of Microsoft Word templates to PDF files, you might find discrepancies in layout or formatting between the Word structure and the PDF structure. This is because Word includes many proprietary techniques in its rendering, and they often cannot be accurately reproduced by the non-Microsoft tools we use for PDF conversion. When you see such discrepancies, we suggest either
  • iterating the template design a few times, trying the PDF conversion, and getting the results as close as possible to your satisfaction, or
  • opening your template in either Google Docs or LibreOffice Writer (both of which produce more accurate PDF files) to determine how close it gets to the layout you need.
It is important to point out, for the above reasons, that we cannot guarantee conformance of Apsona's PDF output layout with the PDF layout produced by Microsoft Word.

Appending the contents of PDF attachments

In some situations, you might store attachments in your Salesforce org that you wish to be appended to each generated document. For example, suppose that you have a Travel Record object from which you need to generate invoices for travel expenses. Suppose further that each Travel Record has PDF attachments containing the bills incurred for the travel, and the contents of these attachments need to be appended to the end of the generated invoice. In such a situation, you can use the "Append attachment contents" option in the last step of the merge action builder - see the screen shot below.

With this feature, each generated document will have appended to it the contents of the PDF attachments to the records. Each page of each PDF document will appear as a separate page in the generated document. This feature is only available when generating .docx or .pdf documents.

To use this feature:
  1. In step 4 of the merge builder popup, check the box to append the contents.
  2. Specify the object whose attachments must be used to append content to the output file. The available objects are the ones for which record IDs are available in the data source (object or report) from which you are running the merge action.
  3. Provide comma-separated text strings that will be used to match attachment names. With the above screen shot, any pdf attachment whose name contains bill or voucher will have its content included in the output document.


  • The Document Generator looks for attachments in the Salesforce Classic Attachment object, as well as in the Lightning Files objects.
  • In the Attachment object, PDF attachments are identified by checking that the Content Type field of the Attachment record contains the value application/pdf. Therefore, please ensure that this field is correctly set to application/pdf for any attachment records you want to include.
  • In the Lightning objects, the Content Document object's File Type and File Extension fields are checked, and if one of them equals pdf, then the file is assumed to be a PDF file.

Troubleshooting Word template files

Sometimes you might find that your template produces spurious data, or that Apsona complains about the existence of a field that you don't immediately see in the template, suggesting that there are fields in the template that aren't visible. One way to examine your entire template for merge field errors is to use Microsoft Word's "Toggle field codes" feature. To do this, open the template file in Word, type Ctrl-A to select the entire document, and they type Alt-F9. This will show all the field codes in the entire document. You can then, for example, use Ctrl-F to find particular fields that are not otherwise visible.

For example, below is a screen shot of a template as it is normally presented by Microsoft Word.

After typing Ctrl-A followed by Alt-F9, you would see something like the screen shot below. To bring back the original view, simply type Ctrl-A followed by Alt-F9 again.

Notes and special cases

Displaying check boxes in Word

You can display a boolean value (a yes/no checkbox field in Salesforce, or an Apsona calculation that produces a boolean value) as a checkbox in Word. To do this, add the string @checkbox to the merge field name, and map the merge field to a boolean value in the data source. For example, the screen shots below show the template structure (on the left) and the generated result (on the right).

Conditional merge fields

Microsoft Word mail-merge templates can use fields containing conditional and formatting information in them, e.g., to produce dates and currencies in specific formats, or to produce different pieces of text depending on conditions, via an IF construct. A simple example is an IF condition in a letter template that generates a salutation of Mr. if the gender (a value known at the point of merging) is "male", and Ms. if the gender is "female".

Apsona's merge tool does not recognize such conditional fields, but you can achieve the same effect in other ways. One is by using as data source a report that produces the necessary conditional values. If you need a conditional value in a merge document, simply produce a report containing all the fields it needs, and add a calculated value with the appropriate condition. In this example, assuming that the report has a column named Gender that tells the gender of the record, you can add a calculated value whose calculation formula is {!Gender} == "Male" ? "Mr." : "Mrs.". You then add a Salutation merge field to your document template, and map that field to the calculated value column of the report. More information is available about calculated values in single-step reports as well as in multi-step reports.

A second, much more powerful way to create conditional logic in your templates is to use Apsona's conditional directives, documented in another article.

Handling multi-line fields

Some data fields (such as address fields) contain multiple lines of data. Organizations might create custom formula fields that string together several other fields, separated by the BR() function to make the result appear on multiple lines in Salesforce. In the raw data field within Salesforce, the lines are separated using the HTML <BR> symbol. If you try to use such a field to merge directly into a Word document, there will be no line breaks in the output document, but instead, you will find the <BR> symbol.

To remedy this situation and provide the correct line breaks between lines, you will need to do two things:
  • Create an Apsona report or multi-step report containing the fields you wish to use to generate the document;
  • Create an Apsona calculated field in the report, whose purpose is to replace the <BR> symbol with the newline character.

To carry out the replacement, you can use the JavaScript replace function. For example, if your multi-line data field in the report is named Contacts.Contact.Multi line Address, you can use the formula {!Contacts.Contact.Multi-line Address}.replace (/<br>/g, "\n") in the calculated field, as illustrated in the screen shot below. Note that whilst this screen shot shows a calculated field in a multi-step report, calculated fields are supported in simple (single-step) reports as well as in multi-step reports.

You can then map the calculated field into the generated document, instead of the original field containing the <BR> symbols. The document generator will then recognize the newline symbols and produce the correct output document.

First-page-only header and footer

Microsoft Word offers the option to have a separate header and footer for just the first page of a document. The screen shot below shows how you would set this option in Word 2010. If you create a template that uses this feature, be sure to use the "separate files, one for each record" value for the Output structure option in step 2 of the document generator wizard, as in the screen shot below. Using any of the other options ("single file with page breaks" or "single file with paragraph breaks") is not supported with such a template, and will cause Apsona to produce output files that Word cannot open.

Font support

When you create text with a particular font in your Word template, Apsona carries the font specification into the generated document. So if the font is available on the system where the generated document is opened, then the text the corresponding text will render correctly.

When generating PDF documents, however, the supported fonts are limited to the ones available to the PDF generator. Below is a list of the fonts currently available. If a font is not available to the PDF generator, the text will be rendered in a default font.
Agency FB
Angsana New
Anonymous Pro
Arabic Typesetting
Archer,Archer Medium
Arial,Arial Black
Arial,Arial Narrow
Arial Rounded MT Bold
Arial Unicode MS
Baskerville Old Face
Bauhaus 93
Bell MT
Berlin Sans FB
Berlin Sans FB Demi
Bernard MT Condensed
Bitstream Vera Sans
Bitstream Vera Sans Mono
Bitstream Vera Serif
Blackadder ITC
Bodoni MT
Bodoni MT,Bodoni MT Black
Bodoni MT,Bodoni MT Condensed
Bodoni MT,Bodoni MT Poster Compressed
Book Antiqua
Bookman Old Style
Bookshelf Symbol 7
Bradley Hand ITC
Britannic Bold
Browallia New
Brush Script MT
Californian FB
Calisto MT
Cambria Math
Century Gothic
Century Schoolbook
Colonna MT
Comic Sans MS
Cooper Black
Copperplate Gothic Bold
Copperplate Gothic Light
Cordia New
Courier New
Curlz MT
DejaVu Sans
DejaVu Sans,DejaVu Sans Condensed
DejaVu Sans,DejaVu Sans Light
DejaVu Sans Mono
DejaVu Serif
DejaVu Serif,DejaVu Serif Condensed
Edwardian Script ITC
Engravers MT
Eras Bold ITC
Eras Demi ITC
Eras Light ITC
Eras Medium ITC
Estrangelo Edessa
Felix Titling
Footlight MT Light
Franklin Gothic Book
Franklin Gothic Demi
Franklin Gothic Demi Cond
Franklin Gothic Heavy
Franklin Gothic Medium
Franklin Gothic Medium Cond
Freestyle Script
French Script MT
Gentium Basic
Gentium Book Basic
Gill Sans MT
Gill Sans MT Condensed
Gill Sans MT Ext Condensed Bold
Gill Sans Ultra Bold
Gill Sans Ultra Bold Condensed
Gloucester MT Extra Condensed
Goudy Old Style
Goudy Stout
Harlow Solid Italic
High Tower Text
Imprint MT Shadow
Informal Roman
Iskoola Pota
Juice ITC
Khmer UI
Kristen ITC
Kunstler Script
Lao UI
Levenim MT
Liberation Mono
Liberation Sans
Liberation Sans Narrow
Liberation Serif
Linux Biolinum G
Linux Libertine G
Lucida Bright
Lucida Calligraphy
Lucida Console
Lucida Fax
Lucida Handwriting
Lucida Sans
Lucida Sans Typewriter
Lucida Sans Unicode
Maiandra GD
Malgun Gothic,맑은 고딕
Matura MT Script Capitals
Microsoft Himalaya
Microsoft JhengHei,微軟正黑體
Microsoft New Tai Lue
Microsoft PhagsPa
Microsoft Sans Serif
Microsoft Tai Le
Microsoft Uighur
Microsoft YaHei,微软雅黑
Microsoft Yi Baiti
Miriam Fixed
Modern No. 20
Mongolian Baiti
Monotype Corsiva
MS Mincho,MS 明朝
MS Outlook
MS Reference Sans Serif
MS Reference Specialty
MV Boli
Niagara Engraved
Niagara Solid
OCR A Extended
Old English Text MT
Palace Script MT
Palatino Linotype
Perpetua Titling MT
Plantagenet Cherokee
Poor Richard
Rage Italic
Rockwell Condensed
Rockwell Extra Bold
Sakkal Majalla
Script MT Bold
Segoe Print
Segoe Script
Segoe UI
Segoe UI,Segoe UI Light
Segoe UI,Segoe UI Semibold
Segoe UI Symbol
Shonar Bangla
Showcard Gothic
Simplified Arabic
Simplified Arabic Fixed
Snap ITC
Tempus Sans ITC
Times New Roman
Traditional Arabic
Trebuchet MS
Tw Cen MT
Tw Cen MT Condensed
Tw Cen MT Condensed Extra Bold
Ubuntu Condensed
Ubuntu Mono
Ubuntu,Ubuntu Light
Viner Hand ITC
Vladimir Script
Wide Latin
Wingdings 2
Wingdings 3