We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to convert Word document to PDF in AWS Lambda

Platform: WinForms |
Control: DocIO |
Published Date: August 25, 2020 |
Last Revised Date: August 27, 2021

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:

  1. You can create an AWS account by referring to this link.
  2. 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:

  1. Create an AWS Lambda function to convert Word document to PDF and publish it to AWS.
  2. Invoke the AWS Lambda function in your main application using AWS SDKs.

Steps to convert Word document to PDF in AWS Lambda function:

  1. Create a new AWS Lambda project as follows.

A screenshot of a cell phone

Description automatically generated

  1. Select Blueprint as Empty Function and click Finish.

A screenshot of a social media post

Description automatically generated

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

A screenshot of a social media post

Description automatically generated

  1. Install the SkiaSharp.NativeAssets.Linux NuGet package as a reference to your AWS lambda project from NuGet.org.

A screenshot of a social media post

Description automatically generated

  1. Create a folder and copy the required data files and include the files to the project.

A screenshot of a cell phone

Description automatically generated

  1. Set the copy to output directory to Copy if newer to all the data files.

A screenshot of a social media post

Description automatically generated

  1. 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;
    

 

  1. 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;
         }
     }
    
  1. Right-click the project and select Publish to AWS Lambda.

A screenshot of a social media post

Description automatically generated

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

A screenshot of a social media post

Description automatically generated

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

A screenshot of a social media post

Description automatically generated

  1. After deploying the application, you can see the published Lambda function in AWS console.

A screenshot of a social media post

Description automatically generated

  1. Edit Memory size and Timeout as maximum in Basic settings of the AWS Lambda function.

A screenshot of a cell phone

Description automatically generated

Refer to the following steps to invoke the AWS Lambda function from console application:

  1. Create a new console project.

Create a Console Application

  1. Install the AWSSDK.Core, AWSSDK.Lambda and Newtonsoft.Json package as a reference to your main application from the NuGet.org.

Install AWSSDK packages

Install AWSSDK lambda packages

Install Newtonsoft packages

  1. Include the following namespaces in Program.cs file.
    using Amazon;
    using Amazon.Lambda;
    using Amazon.Lambda.Model;
    using Newtonsoft.Json;
    
  1. 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");
    

 

  1. By executing the program, you will get the PDF document as follows.

A screenshot of a cell phone

Description automatically generated

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.

Note:

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.

 

2X faster development

The ultimate WinForms UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile