Articles in this section
Category / Section

How to Convert HTML to PDF in AWS Lambda with Custom Font in NET 6 Container Image

6 mins read

The Syncfusion HTML to PDF converter is a .NET Core PDF library for converting webpages, SVG, MHTML, and HTML to PDF using C#. It is reliable and accurate. Using this library, you can convert HTML to PDF in AWS Lambda with docker image using Blink.

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 HTML to PDF in AWS Lambda with docker image:

  1. Create an AWS Lambda function to convert HTML to PDF and publish it to AWS.
  2. Invoke the AWS Lambda function in your main application using AWS SDKs.
Steps to convert HTML to PDF in AWS Lambda with docker image:
  1. Create a new AWS Lambda project with Tests as follows:

    ejdotnetcore-4283_img1.png

  2. Create a project name and select location.

    ejdotnetcore-4283_img2.png

  3. Select Blueprint as .NET 6 (Container Image) Function and click

    ejdotnetcore-4283_img3.png
    .

  4. Install the Syncfusion.HtmlToPdfConverter.Net.Aws and AWSSDK.Lambda NuGet package as a reference to your AWS lambda project from the NuGet.org.

    ejdotnetcore-4283_img4.png

    ejdotnetcore-4283_img5.png

  5. Using the following namespaces in the Function.cs file.

    using Syncfusion.HtmlConverter;
    using Syncfusion.Pdf;
    using System.IO;
    
  6. Add the following code sample in Function.cs to create a PDF document.

    public string FunctionHandler(string input, ILambdaContext context)
    {
      //Initialize HTML to PDF converter with the Blink rendering engine.
      HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);
          
      BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();
      blinkConverterSettings.CommandLineArguments.Add("--no-sandbox");
      blinkConverterSettings.CommandLineArguments.Add("--disable-setuid-sandbox");
      blinkConverterSettings.AdditionalDelay = 3000;
    htmlConverter.ConverterSettings = blinkConverterSettings;
    
      //Convert the HTML string to PDF.
      PdfDocument document = htmlConverter.Convert(input, PathToFile());        
    
      //Save the document into a stream.
      MemoryStream memoryStream = new MemoryStream();
    
      //Save and close the PDFDocument.
      document.Save(memoryStream);
      document.Close(true);
    
      string base64 = Convert.ToBase64String(memoryStream.ToArray());
      memoryStream.Close();
      memoryStream.Dispose();
    
    return base64;
    }
    
    public static string PathToFile()
    {
      string? path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
      if (string.IsNullOrEmpty(path))
      {
         path = Environment.OSVersion.Platform == PlatformID.Unix ? @"/" : @"\";
      }
      return Environment.OSVersion.Platform == PlatformID.Unix ? string.Concat(path.Substring(5), @"/") : string.Concat(path.Substring(6), @"\");
    }
    
  7. Add the following steps to add custom font into a PDF.

    1. Create a font folder in your project and place all the needed font files.
    2. Create a config file for font configuration by using the below commands and place inside that fonts folder.
    3. Refer to the following docker command to copy the required to system folder.
    <?xml version="1.0"?>
    
    <!DOCTYPE fontconfig SYSTEM "fonts.dtd">
    
    <fontconfig>
    
      <dir>/var/task/fonts/</dir>
    
      <cachedir>/tmp/fonts-cache/</cachedir>
    
      <config></config>
    
    </fontconfig>
    
    RUN yum -y install fontconfig
    
    COPY fonts /usr/share/fonts/truetype/
    
    
    
    RUN fc-cache -f -v
    

    download (4) (1).png

  8. And include the below environment variable in your AWS lambda function, the following namespaces and code samples in the AWSHelper class to invoke the published AWS Lambda function using the function name and access keys.

    download (3).png

  9. Create a new folder as Helper and add a class file as AWSHelper.cs. Add the following namespaces and code samples in the AWSHelper class to invoke the published AWS Lambda function using the function name and access keys.
    Using Amazon.Lambda;

    Using Amazon.Lambda;n;
    using Amazon.Lambda.Model;
    using Newtonsoft.Json;
    
    public class AWSHelper
    ```js
    public class AWSHelper Task<byte[]> RunLambdaFunction(string html)
    {  {
      public static async Task<byte[]> RunLambdaFunction(string html)
      {  {
         tryvar AwsAccessKeyId = "awsaccessKeyID";
         {  var AwsSecretAccessKey = "awsSecretAccessKey";
            var AwsAccessKeyId = "awsaccessKeyID";
            var AwsSecretAccessKey = "awsSecretAccessKey";ient(AwsAccessKeyId, AwsSecretAccessKey, Amazon.RegionEndpoint.USEast1);
            InvokeRequest invoke = new InvokeRequest
            AmazonLambdaClient client = new AmazonLambdaClient(AwsAccessKeyId, AwsSecretAccessKey, Amazon.RegionEndpoint.USEast1);
            InvokeRequest invoke = new InvokeRequestner",
            {  InvocationType = InvocationType.RequestResponse,
               FunctionName = "AWSLambdaDockerContainer",alizeObject(html)
               InvocationType = InvocationType.RequestResponse,
               Payload = Newtonsoft.Json.JsonConvert.SerializeObject(html)
            };vokeResponse response = await client.InvokeAsync(invoke);
            //Get the InvokeResponse from the client InvokeRequest.
            InvokeResponse response = await client.InvokeAsync(invoke);
            Console.WriteLine($"Response: {response.LogResult}");
            //Read the response stream.e: {response.StatusCode}");
            Console.WriteLine($"Response: {response.LogResult}");}");
            Console.WriteLine($"Response: {response.StatusCode}");
            Console.WriteLine($"Response: {response.FunctionError}");
            var stream = new StreamReader(response.Payload);
            JsonReader reader = new JsonTextReader(stream););
            var serilizer = new JsonSerializer();
            var responseText = serilizer.Deserialize(reader);
            return Convert.FromBase64String(responseText.ToString());
            //Convert Base64String into a PDF document.
            return Convert.FromBase64String(responseText.ToString());
         }
         catch (Exception ex)e($"Exception Occured HTMLToPDFHelper: {ex}");
         {
             Console.WriteLine($"Exception Occured HTMLToPDFHelper: {ex}");
         }
      return Convert.FromBase64String("");
      }
    }ight-click the project and select **Publish to AWS Lambda.**
    ```etcore-4283_img6.png](https://{yourdomain}/kb/attachment/article/13520/inline/10230)
    
  10. Right click the project and select Publish to AWS Lambda.. After creating the profile, add a name for the Lambda function to publish. Then, click **Next. **

    ejdotnetcore-4283_img6.png

  11. 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. **oy your application.

    ejdotnetcore-4283_img7.png

  12. 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.NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEwMjMzIiwib3JnaWQiOiIzIiwiaXNzIjoic3VwcG9ydC5zeW5jZnVzaW9uLmNvbSJ9.jtifDt1CcDJ4Xl4ZlaxaC-jdqQF3seKsfPe7_RJXY50)

    ejdotnetcore-4283_img8.png

    ejdotnetcore-4283_img9.png
    )

  13. After deploying the application, sign in to your AWS account and you can see the published Lambda function in AWS console.
    Refer to the following steps to invoke the AWS Lambda function from the Test application:

  14. Add the following code example to invoke the AWS lambda function with HTML string from the Function Test.

    public class FunctionTest
    {
       [Fact]
       public void HtmlToPDFFunction()
       {
           string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
           string filePath = Environment.OSVersion.Platform == PlatformID.Unix ? string.Concat(path.Substring(5), @"/") : string.Concat(path.Substring(6), @"\");
    
           var html = File.ReadAllText($"{filePath}/HtmlSample.html");
           byte[] base64 = null;
           base64 = AWSHelper.RunLambdaFunction(html).Result;
    
           FileStream file = new FileStream($"{filePath}/file{DateTime.Now.Ticks}.pdf", FileMode.Create, FileAccess.Write);
           var ms = new MemoryStream(base64);
           ms.WriteTo(file);
           file.Close();
           ms.Close();
       }
    }
    
  15. Right click the test application and select Run Tests.

    ejdotnetcore-4283_img11.png

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

    Screenshot (928).png

You can download a complete working sample from HTML-to-PDF-AWS-with-custom-font.zip.

Click here to explore the rich set of Syncfusion Essential PDF features.

Take a moment to peruse the documentation for Converting HTML to PDF, where you will find various options for URL to PDF, HTML string to PDF, and Hyperlinks.

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

See Also:

Convert HTML to PDF in AWS Lambda

Convert HTML to PDF in Azure Function

Convert HTML to PDF in Azure App Service

Convert HTML to PDF in Azure Function Linux

Convert HTML to PDF in Azure App Service Linux

Convert HTML to PDF in docker

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