Articles in this section
Category / Section

How to mail merge Word documents and convert to PDF in Azure Functions v2

3 mins read

Syncfusion .NET Word Library generates personalized reports through mail merge on Word documents and convert them to PDF documents in Azure Functions using the Word to PDF converter.

Steps to mail merge Word documents and convert to PDF in Azure Functions v2 (.NET Standard):

  1. Create a new Azure functions project.

Azure Functions project

  1. Select the framework Azure Functions v2 (.NET Standard) and select HTTP trigger as follows.

Selecting Framework Azure Functions v2

  1. Install the Syncfusion.DocIORenderer.Net.Core NuGet package as a reference to your project from the NuGet.org.

Installing NuGet from nuget.org

  1. Include the following namespaces in the Function1.cs file.

 

C#

using Syncfusion.Pdf;
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIORenderer;
using Syncfusion.DocIO;
  1. Add the following code snippet in the Run method of the Function1 class to mail merge Word documents and convert them to PDF in Azure Functions and return the resultant PDF document to the client end.

 

C#

// JSON string
string jsonDataString = "{\"Reports\":[{\"SiteName\":\"Test Site Name\",\"SiteAddress\":\"Test Site Address\",\"ClientName\":\"Compliance 365\",\"Locations\":[{\"id\":\"1\",\"Name\":\"Location 1\",\"Description\":\"Test Description\"}]}]}";
// Gets JSON object from JSON string
JObject jsonObject = JObject.Parse(jsonDataString);
// Converts to IDictionary data from JSON object
IDictionary<string, object> data = GetData(jsonObject);
 
Stream stream = req.Content.ReadAsStreamAsync().Result;
// Opens the template document
WordDocument wordDocument = new WordDocument(stream, FormatType.Docx);
// Creates the mail merge data table in order to perform mail merge
MailMergeDataTable dataTable = new MailMergeDataTable("Reports", (List<object>)data["Reports"]);
// Performs the mail merge operation with the dynamic collection
wordDocument.MailMerge.ExecuteNestedGroup(dataTable);
// Create an instance for DocIORenderer for Word to PDF conversion
DocIORenderer render = new DocIORenderer();
// Converts Word document to PDF.
PdfDocument pdfDocument = render.ConvertToPDF(wordDocument);
// Releases the resources used by the Word document and DocIO Renderer objects
render.Dispose();
wordDocument.Dispose();
 
MemoryStream memoryStream = new MemoryStream();
// Saves the PDF file
pdfDocument.Save(memoryStream);
memoryStream.Position = 0;
// Creates the response to return
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
// Sets the PDF document content response
response.Content = new ByteArrayContent(memoryStream.ToArray());
// Sets the content disposition as attachment
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{    
FileName = "Result.pdf" }; // Sets the content type as PDF format mime type response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");   // Returns the response with the output PDF stream return response;

 

  1. Right-click the project and select Publish. Then, create a new profile in the Publish Window.

Publish the Azure functions

  1. Create an App Service using an Azure subscription and select a hosting plan.

Create an plan to publish your Azure functions

  1. The Syncfusion® DocIO library works from the basic hosting plan (B1). So, select the required hosting plan.

Configure hosting plan

  1. After creating the profile, click the Publish button.

Publish screenshot

  1. Now, go to the Azure portal and select the Function Apps. After running the service, click Get function URL and then click Copy.
  2. Paste the function URL into the client sample (which will request the Azure Function to mail merge Word documents and convert them to PDF using the template Word document). You will get the output PDF document as follows.

Generated PDF

A complete sample to mail merge Word documents and convert them to PDF in Azure Functions v2 can be downloaded from Mail merge and Word to PDF conversion in Azure Functions v2.

Steps to post the request to Azure Functions with a template Word document:

  1. Create a console application to request the Azure Functions API.
  2. Add the following code snippet into the Main method to post the request to Azure Functions with a template Word document to mail merge and get the resultant PDF document.

C#

// Reads the template Word document
FileStream fs = new FileStream(@"../../Data/Adventure.docx", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
fs.Position = 0;
// Saves the Word document in a memory stream
MemoryStream inputStream = new MemoryStream();
fs.CopyTo(inputStream);
inputStream.Position = 0;
 
try
{
    Console.WriteLine("Please enter your Azure Functions URL:");
    string functionURL = Console.ReadLine();

    // Creates HttpWebRequest with hosted Azure Function URL
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(functionURL);
    // Sets request method as POST
    req.Method = "POST";
    // Gets the request stream to save the Word document stream
    Stream stream = req.GetRequestStream();
    // Writes the Word document stream into the request stream
    stream.Write(inputStream.ToArray(), 0, inputStream.ToArray().Length);

    // Gets the response from the Azure Function
    HttpWebResponse res = (HttpWebResponse)req.GetResponse();

    // Saves the Word document stream
    FileStream fileStream = File.Create("Result.pdf");
    res.GetResponseStream().CopyTo(fileStream);
    // Disposes the streams
    inputStream.Dispose();
    fileStream.Dispose();
}
catch (Exception ex)
{
    throw;
}

A console application to post the request to Azure Functions can be downloaded from WordToPDF.zip.

Take a moment to peruse the documentation, where you will find the basic Word document processing options along with features like mail merge, merge and split documents, find and replace text in the Word document, protect the Word documents, and most importantly PDF conversion with code examples.

Explore more about the rich set of Syncfusion® Word Framework features.

Note:

Starting with v16.2.0.x, if you reference Syncfusion® assemblies from a trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering a Syncfusion® license key in your application to use the components without a trial message.

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied