How to convert Word document to PDF in AWS Lambda?
Using Syncfusion .Net Core Word and PDF library, you can convert a Word document to PDF in AWS Lambda.
Setting up the AWS Toolkit for Visual Studio:
- You can create an AWS account by referring to this link.
- Download and install the AWS Toolkit for Visual Studio, you can download the AWS toolkit from this link. The Toolkit can be installed from Tools/Extension and updates options in Visual Studio.
Refer to the following steps to convert Word document to PDF in AWS:
- Create an AWS Lambda function to convert Word document to PDF and publish it to AWS.
- Invoke the AWS Lambda function in your main application using AWS SDKs.
Steps to convert Word document to PDF in AWS Lambda function:
- Create a new AWS Lambda project as follows.
- Select Blueprint as Empty Function and click Finish.
- Install the Syncfusion.DocIORenderer.Net.Core NuGet package as a reference to your AWS lambda project from NuGet.org.
- Install the SkiaSharp.NativeAssets.Linux NuGet package as a reference to your AWS lambda project from NuGet.org.
- Create a folder and copy the required data files and include the files to the project.
- Set the copy to output directory to Copy if newer to all the data files.
- Include the following namespaces in Function.cs file.
using System.IO; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.DocIORenderer; using Syncfusion.Pdf; using Syncfusion.Drawing;
- Add the following code snippet in Function.cs to create a PDF document.
/// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public string FunctionHandler(string input, ILambdaContext context) { string filePath = Path.GetFullPath(@"Data/Adventure.docx"); //Load the file from the disk FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); WordDocument document = new WordDocument(fileStream, FormatType.Docx); //Hooks the font substitution event document.FontSettings.SubstituteFont += FontSettings_SubstituteFont; DocIORenderer render = new DocIORenderer(); PdfDocument pdf = render.ConvertToPDF(document); //Unhooks the font substitution event after converting to PDF document.FontSettings.SubstituteFont -= FontSettings_SubstituteFont; //Save the document into stream MemoryStream stream = new MemoryStream(); //Save the PDF document pdf.Save(stream); document.Close(); render.Dispose(); return Convert.ToBase64String(stream.ToArray()); } /// <summary> /// Sets the alternate font when a specified font is not installed in the production environment /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void FontSettings_SubstituteFont(object sender, SubstituteFontEventArgs args) { string filePath = string.Empty; //Load the file from the disk FileStream fileStream = null; if (args.OriginalFontName == "Calibri") { filePath = Path.GetFullPath(@"Data/calibri.ttf"); fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); args.AlternateFontStream = fileStream; } else if (args.OriginalFontName == "Arial") { filePath = Path.GetFullPath(@"Data/arial.ttf"); fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); args.AlternateFontStream = fileStream; } else { filePath = Path.GetFullPath(@"Data/times.ttf"); fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); args.AlternateFontStream = fileStream; } }
- Right-click the project and select Publish to AWS Lambda.
- Create a new AWS profile in the Upload Lambda Function Window. After creating the profile, add a name for the Lambda function to publish. Then, click Next.
- In the Advanced Function Details window, specify the Role Name as based on AWS Managed policy. After selecting the role, click the Upload button to deploy your application.
- After deploying the application, you can see the published Lambda function in AWS console.
- Edit Memory size and Timeout as maximum in Basic settings of the AWS Lambda function.
Refer to the following steps to invoke the AWS Lambda function from console application:
- Create a new console project.
- Install the AWSSDK.Core, AWSSDK.Lambda and Newtonsoft.Json package as a reference to your main application from the NuGet.org.
- Include the following namespaces in Program.cs file.
using Amazon; using Amazon.Lambda; using Amazon.Lambda.Model; using Newtonsoft.Json;
- Add the following code snippet in Program class to invoke the published AWS Lambda function using the function name and access keys.
//Create a new AmazonLambdaClient AmazonLambdaClient client = new AmazonLambdaClient("awsaccessKeyID", "awsSecreteAccessKey", RegionEndpoint.USEast2); //Create new InvokeRequest with published function name. InvokeRequest invoke = new InvokeRequest { FunctionName = "MyNewFunction", InvocationType = InvocationType.RequestResponse, Payload = "\"Test\"" }; //Get the InvokeResponse from client InvokeRequest. InvokeResponse response = client.Invoke(invoke); //Read the response stream var stream = new StreamReader(response.Payload); JsonReader reader = new JsonTextReader(stream); var serilizer = new JsonSerializer(); var responseText = serilizer.Deserialize(reader); //Convert Base64String into PDF document byte[] bytes = Convert.FromBase64String(responseText.ToString()); FileStream fileStream = new FileStream("Sample.pdf", FileMode.Create); BinaryWriter writer = new BinaryWriter(fileStream); writer.Write(bytes, 0, bytes.Length); writer.Close(); System.Diagnostics.Process.Start("Sample.pdf");
- By executing the program, you will get the PDF document as follows.
The samples of AWS Lambda and console applications are attached in this article for your reference. Find the samples from the following location.
AWS Lambda: MyLambdaFunction
Console sample: Console-App-.NET-Core
Take a moment to peruse the documentation, where you can find 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 and Image conversions with code examples.
Explore more about the rich set of Syncfusion Word Framework features.
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.