Generating Word and PDF documents

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. The screenshot below illustrates the template used in the videos above.

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.

The merge action builder recognizes all merge fields in your Word document, so you don’t need to adhere to any specific naming constraints with your field names. You do not, for example, have to look up any sort of “allowed names” list from which to pick your names – you can just make up any names you want. By the way, creating merge fields in Word can be a bit tedious, and there is an easier way.

Note: Best practice: In general, avoid using special characters in your field names. Use only alphabets, numerals and the underscore symbol.

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 <>, 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., <> 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” .

Please keep in mind that if you have created a template using this angle-bracket-based syntax, you should not edit such fields in Microsoft Word, because as noted above, Word can change the internal representation of the merge field so that Apsona cannot recognize it. Make sure to copy/paste from a plain text editor instead. 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, time-of-day and number values.

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.

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.

You can use the same format with the angle-bracket-based fields with Google Docs and LibreOffice merge fields, e.g., your merge field might look like <>

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 #

yyyy Four 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
MMMM Full 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

Examples #

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

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

Format codes for number fields #

The format codes for numeric fields let you specify how many digits should appear after the decimal point in the displayed number. The displayed number will automatically include commas to separate thousandths places. Below are the available codes, with the Example column showing how the number 25304.323 will be displayed.

Code Interpretation Example
0.000 Three decimal places 25,304.323
0.00 Two decimal places 25,304.32
0.0 One decimal place 25,304.3
0 No decimal part 25,304

“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.

Support for rich-text fields #

Rich-text fields can contain any valid HTML, and can therefore be quite complex. Apsona’s Document Generator offers limited support for rich-text fields, incliding paragraphs, bullet lists, numbered lists and images.

The content produced from a rich-text field in the Word document inherits any fonts and colors set up around the merge field. For example, If you have set up a region of your Word template to use, say, the Calibri font with a red text color, and you include a rich-text merge field in that region, then all the content produced by the rich-text field will be produced in the Calibri font with red text.

Inhibiting rich-text formatting #

In some situations, you might need to use a rich text field in your template but omit all the formatting in the field. For this purpose, you can create a merge field that contains the no_format formatting tag after an @ sign, like this:

«my_richtext_field@no_format»

When you specify this formatting tag, the merge tool removes all HTML formatting from the content of the field and renders just the text part of the content. This formatting tag is available with both MS-Word-style and angle-bracket-style merge fields.

Arithmetic calculations #

You can perform simple arithmetic calculations in merge fields. For example, assuming that you have two merge fields DueAmt and PaymentAmt, you can create a merge field <> whose value will be the result of subtracting PaymentAmt from DueAmt. Similarly, the calculation «(GPA1 + GPA2)/2» calculates the average of the two merge fields GPA1 and GPA2.

The screenshot below shows a template with a few more examples of calculated values.

Some things to bear in mind about such calculations:

  • The calculation can use the Word merge field form (Insert – Quick Parts – Field in Word), as shown in the fourth example of the above screenshot, or the angle-bracket form, as in the other examples of the above screenshot. But if you are using the angle-bracket form, make sure to create the field using the copy-from-notepad technique described above; otherwise it is much more likely that Apsona will not recognize the calculation correctly, but instead will treat the entire calculation formula as a separate field.
  • You can perform calculations on sublist aggregate values, as in the third example of the above screenshot. Keep in mind, though, that Word can get confused and produce incorrect merge fields when there are multiple sublist aggregate values in the calculation. In such situations, we recommend using the angle-bracket form for the calculation field.
  • Field names used in a calculation can contain only alphabets, numerics and underscores. They cannot contain spaces. For example, a field such as «My Field - Other field» will not be recognized as a calculation because its field names contain spaces in them. For the same reason, any record group names that need to be used in such calculations must also contain only alphabets, numerics or underscores.
  • Calculations are available only for top-level fields and sublist aggregation fields. They are not supported within sublists: the merge tool will not recognize any calculations placed between TableStart and TableEnd tags.
  • Only the four standard arithmetic operators for addition (+), subtraction (-), multiplication (*) and division (/) are supported, and parenthesized expressions are supported. No other expressions are supported.
  • If a calculation result produces a number with a fractional value, the fraction part is shown rounded to two decimal places.

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. Some common discrepancies:

  • Extra pages in PDF files, usually because the content in the page is too tight, and overflows to new pages in the PDF rendering (albeit not in Word).
  • Text boxes being placed at incorrect positions in the page.

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.
Note: 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.

Notes #

  • 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 
 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 
 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 
     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 (/
/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 
 symbols. The document generator will then recognize the newline symbols and produce the correct output document.

Headers and footers #

When generating a single output document file with either page breaks or paragraph breaks, you cannot vary the header or footer depending on the document content; the headers and footers on all the generated pages will be the same. For example, if you add record fields or conditional logic in the footer, wanting to show a different piece of text in the footer depending on the record used for the document content, the footer will not change. The only way to have different content in the header or footer for each generated document is to generate separate files, one for each record.

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
Aharoni
Algerian
Andalus
Angsana New
AngsanaUPC
Anonymous
Anonymous Pro
Aparajita
Arabic Typesetting
Archer,Archer Medium
Arial
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
Broadway
Browallia New
BrowalliaUPC
Brush Script MT
Calibri
Californian FB
Calisto MT
Cambria
Cambria Math
Candara
Castellar
Centaur
Century
Century Gothic
Century Schoolbook
Chiller
Colonna MT
Comic Sans MS
Consolas
Constantia
Cooper Black
Copperplate Gothic Bold
Copperplate Gothic Light
Corbel
Cordia New
CordiaUPC
Courier New
Curlz MT
DaunPenh
David
DejaVu Sans
DejaVu Sans,DejaVu Sans Condensed
DejaVu Sans,DejaVu Sans Light
DejaVu Sans Mono
DejaVu Serif
DejaVu Serif,DejaVu Serif Condensed
DFKai\-SB,標楷體
DilleniaUPC
Dingbats
DokChampa
Ebrima
Edwardian Script ITC
Elephant
Engravers MT
Eras Bold ITC
Eras Demi ITC
Eras Light ITC
Eras Medium ITC
Estrangelo Edessa
EucrosiaUPC
Euphemia
FangSong,仿宋
Felix Titling
Footlight MT Light
Forte
Franklin Gothic Book
Franklin Gothic Demi
Franklin Gothic Demi Cond
Franklin Gothic Heavy
Franklin Gothic Medium
Franklin Gothic Medium Cond
FrankRuehl
FreesiaUPC
Freestyle Script
French Script MT
Gabriola
Garamond
Gautami
Gentium
GentiumAlt
Gentium Basic
Gentium Book Basic
Georgia
Gigi
Gill Sans MT
Gill Sans MT Condensed
Gill Sans MT Ext Condensed Bold
Gill Sans Ultra Bold
Gill Sans Ultra Bold Condensed
Gisha
Gloucester MT Extra Condensed
Goudy Old Style
Goudy Stout
Haettenschweiler
Harlow Solid Italic
Harrington
High Tower Text
Impact
Imprint MT Shadow
Informal Roman
IrisUPC
Iskoola Pota
JasmineUPC
Jokerman
Juice ITC
KaiTi,楷体
Kalinga
Kartika
Khmer UI
KNW\-TTNandi
KodchiangUPC
Kokila
Kristen ITC
Kunstler Script
Lao UI
Latha
Leelawadee
Levenim MT
Liberation Mono
Liberation Sans
Liberation Sans Narrow
Liberation Serif
LilyUPC
Linux Biolinum G
Linux Libertine G
Lucida Bright
Lucida Calligraphy
Lucida Console
Lucida Fax
Lucida Handwriting
Lucida Sans
Lucida Sans Typewriter
Lucida Sans Unicode
Magneto
Maiandra GD
Malgun Gothic,맑은 고딕
Mangal
Marlett
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
Miriam Fixed
Mistral
Modern No. 20
Monaco
Mongolian Baiti
Monotype Corsiva
MoolBoran
MS Mincho,MS 明朝
MS Outlook
MS Reference Sans Serif
MS Reference Specialty
MV Boli
Narkisim
Niagara Engraved
Niagara Solid
Nyala
OCR A Extended
Old English Text MT
Onyx
OpenSymbol
Palace Script MT
Palatino Linotype
Papyrus
Parchment
Perpetua
Perpetua Titling MT
Plantagenet Cherokee
Playbill
Poor Richard
Pristina
Raavi
Rage Italic
Ravie
Rockwell
Rockwell Condensed
Rockwell Extra Bold
Rod
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
Shruti
SimHei,黑体
Simplified Arabic
Simplified Arabic Fixed
SimSun\-ExtB
Snap ITC
Stencil
Sylfaen
Symbol
Tahoma
Tempus Sans ITC
Times New Roman
Traditional Arabic
Trebuchet MS
Tunga
Tw Cen MT
Tw Cen MT Condensed
Tw Cen MT Condensed Extra Bold
Ubuntu
Ubuntu Condensed
Ubuntu Mono
Ubuntu,Ubuntu Light
Utsaah
Vani
Verdana
Vijaya
Viner Hand ITC
Vivaldi
Vladimir Script
Vrinda
Webdings
Wide Latin
Wingdings
Wingdings 2
Wingdings 3

Powered by BetterDocs