The Mail
╰ DocumentServer Namespace
╰ MailMerge Class
The MailMerge class is a .NET component that can be used to effortlessly merge template documents with database content in .NET projects, such as ASP.NET web applications, web services or Windows services. class can be used to merge form fields with data from JSON objects or IEnumerable objects. Form fields can be pre-populated to prepare forms for users to complete or they can be flattened.
We just published a new online demo that shows how to implement these options based on a typical form used in the healthcare industry.
Pre-Selecting Form Fields
On the first button click, the form fields are pre-selected with existing JSON data. To increase the user experience, to accelerate the process and to decrease errors, parts of a document can be pre-populated with known values.
The HttpGet controller method PDFPrepare is called with the boolean flatten parameter false.
[HttpGet] | |
public string PDFPrepare(bool flatten) { | |
byte[] bDocument; | |
// create temporary ServerTextControl | |
using (ServerTextControl tx = new ServerTextControl()) { | |
tx.Create(); | |
// loading the template | |
tx.Load(Server.MapPath("~/App_Data/Documents/patient_history.tx"), StreamType.InternalUnicodeFormat); | |
// fire up the MailMerge engine | |
using (MailMerge mailMerge = new MailMerge()) { | |
mailMerge.TextComponent = tx; // connect to ServerTextControl | |
// pre-selecting form fields | |
if (flatten == false) | |
mailMerge.FormFieldMergeType = FormFieldMergeType.Preselect; | |
else // flatten form fields | |
mailMerge.FormFieldMergeType = FormFieldMergeType.Replace; | |
string jsonData = System.IO.File.ReadAllText(Server.MapPath("~/App_Data/Documents/data.json")); | |
// merge JSON into fields | |
mailMerge.MergeJsonData(jsonData); | |
} | |
// export to PDF | |
tx.Save(out bDocument, BinaryStreamType.InternalUnicodeFormat); | |
} | |
// return as Base64 encoded string | |
return Convert.ToBase64String(bDocument); | |
} |
In this case, the Form
╰ DocumentServer Namespace
╰ MailMerge Class
╰ FormFieldMergeType Property
Specifies in which manner form fields are treated during the merge process. property is set to Preselect which basically tells the MailMerge engine to set the text of the form fields and to keep the form fields in the document.
Flattening Form Fields
On the second button, the controller method PDFPrepare is called with the boolean flatten parameter true. The Form
╰ DocumentServer Namespace
╰ MailMerge Class
╰ FormFieldMergeType Property
Specifies in which manner form fields are treated during the merge process. property is set to Replace. In this case, the MailMerge engine is removing known form fields and replaces them with the given text.
Live Demo
Test this demo live in our online demos.