What is Aspose?
Aspose, a file formats API provider, provides .NET, Java, Android, SharePoint, Reporting Services, and cloud-based APIs for document generation, conversion, and automation. Unlike any 3rd party DLL, you can use Aspose and play with your office documents along with PDF in a much simpler way.
The very best part of this I found is mail merge. To generate any PDF, you have to continue either item by item or you can create your HTML and then convert it into a PDF. Here, in Aspose, we have a method named Merge() through which we can use a Word template and from there, we can generate the PDF with our desired values. And twe can do this by writing only 3-4 lines. It’s that easy.
After using this, the only disappointing thing I found is, Aspose is not free :(
For more Aspose-related information, you can visit here.
So, let’s see how to integrate Aspose in our .NET application and use it to generate PDF from a template.
Integrate Aspose in your .NET application
Aspose is available in NuGet Package Manager library. So, you can install it either from the Package Manager console.
There is one DLL named Aspose.Total, which includes all packages but you can also get the license of individual items like (Aspose.Words, Aspose.PDF, Aspose.HTML etc.). Here, we will use Aspose.Words.
Go to your Package Manager window or search for “Aspose.Words”.
Or, if you want to install it from NuGet Package Manager console, then open the console and copy paste the below command.
PM> Install-Package Aspose.Words -Version 19.5.0
After successful integration, you will find a reference in your application.
Create Word Template
Now, coming to the template part, you have to create a Word document which will contain the mail merge fields. Please go through the provided link to create a Word document using mail merge. Mail Merge in Microsoft Word.
Using Code
Create a solution of any type in Visual Studio. I am taking VS 2017 and creating a console application. Make sure you have already installed the Aspose.Words in your application.
Now, create a Util namespace and add a new class named AsposeHelper and paste the below code snippet.
- using System;
- using System.IO;
- using WORDS = Aspose.Words;
- using ASPOSE_Demo.Util.Handlers;
-
- namespace ASPOSE_Demo.Util
- {
- public class ASPOSEHelper
- {
- public static MemoryStream GenerateMemoryStreamFromWordTemplate(string templateLink,
- string[] placeholders,
- object[] values)
- {
- try
- {
- MemoryStream dstStream = null;
-
- var doc = new Aspose.Words.Document(templateLink);
- try
- {
-
- doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();
-
- doc.MailMerge.Execute(placeholders, values);
-
- dstStream = new MemoryStream();
-
- doc.Save(dstStream, GetSaveFormat("Pdf"));
- }
- catch
- {
-
- throw;
- }
- finally
- {
- doc = null;
- }
- return dstStream;
- }
- catch
- {
- throw;
- }
- }
-
- private static WORDS.SaveFormat GetSaveFormat(string outputType)
- {
- return (WORDS.SaveFormat)Enum.Parse(typeof(WORDS.SaveFormat), outputType.ToString());
- }
- }
- }
This is our Aspose class which will create the PDF as a memory stream and will pass it to the calling method.
Now, you have to create a new Handler method to handle the HTML because if you put any HTML as a value in the mail merge, it will take that as a value only.
For that, create a new class named HandleMergeFieldInsertHtml and paste the below code snippet.
- using Aspose.Words;
- using Aspose.Words.MailMerging;
-
- namespace ASPOSE_Demo.Util.Handlers
- {
- public class HandleMergeFieldInsertHtml : IFieldMergingCallback
- {
-
-
-
- void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
- {
-
- if (e.DocumentFieldName.EndsWith("HTML") || e.DocumentFieldName.StartsWith("HTML"))
- {
-
- DocumentBuilder builder = new DocumentBuilder(e.Document);
- builder.MoveToMergeField(e.DocumentFieldName);
- builder.InsertHtml((string)e.FieldValue);
-
-
- e.Text = "";
- }
- }
-
- void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
- {
-
- }
- }
- }
Now, please note, if you have to put any HTML data in PDF, then you have to name the Merge fields either starting with “HTML” or ending with “HTML”.
Now, it’s time to consume the Aspose helper class. In your mail method, create two arrays of type string/object. In one array, there will be a series of placeholders (merge fields name). Make sure it is a string array. In another array, there will be the desired values. This can be any type of array. If you have all values in one single type, you can create an array of that type, or you can create an array of type Object.
The count and place should be in same order for both the arrays, otherwise, you will get a runtime exception.
-
-
-
- var placeHolders = new string[] { "Title", "First_Name", "Company_Name", "Address_Line_1", "City", "ZIP_Code", "Email_Address" };
-
-
- var actualValues = new string[] { "Mr.", "Arkadeep", "PwC", "Dum Dum", "Kolkata", "700 050", "[email protected]"};
-
-
-
- var templateLocation = @"C:\Users\arkadeepde\source\repos\ASPOSE_Demo\ASPOSE_Demo\Template\Template.docx";
-
-
- var memoryStream = ASPOSEHelper.GenerateMemoryStreamFromWordTemplate(templateLocation, placeHolders, actualValues);
-
- memoryStream.Position = 0;
Now, you have your memory stream. Save it as PDF and enjoy.
-
- using (FileStream file = new FileStream(@"C:\D\arka.pdf", FileMode.Create, System.IO.FileAccess.Write))
- {
- byte[] bytes = new byte[memoryStream.Length];
- memoryStream.Read(bytes, 0, (int)memoryStream.Length);
- file.Write(bytes, 0, bytes.Length);
- memoryStream.Close();
- }