How to convert HTML to PDF in AWS Lambda with NET 6 Container Image?
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:
- 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 HTML to PDF in AWS Lambda with docker image:
- Create an AWS Lambda function to convert HTML to PDF and publish it to AWS.
- Invoke the AWS Lambda function in your main application using AWS SDKs.
Steps to convert HTML to PDF in AWS Lambda with docker image:
- Create a new AWS Lambda project with Tests as follows:
- Create a project name and select location.
- Select Blueprint as .NET 6 (Container Image) Function and click Finish.
- Install the Syncfusion.HtmlToPdfConverter.Net.Aws and AWSSDK.Lambda NuGet package as a reference to your AWS lambda project from NuGet.org.
- Using the following namespaces in the Function.cs file.
using Syncfusion.HtmlConverter; using Syncfusion.Pdf; using System.IO;
- 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.BlinkPath = Path.GetFullPath("BlinkBinariesAws"); 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), @"\"); }
- Create a new folder as Helper and add a class file as AWSHelper.cs. Add the following namespaces and code samples in AWSHelper class to invoke the published AWS Lambda function using the function name and access keys.
Using Amazon.Lambda; using Amazon.Lambda.Model; using Newtonsoft.Json;
public class AWSHelper { public static async Task<byte[]> RunLambdaFunction(string html) { try { var AwsAccessKeyId = "awsaccessKeyID"; var AwsSecretAccessKey = "awsSecretAccessKey"; AmazonLambdaClient client = new AmazonLambdaClient(AwsAccessKeyId, AwsSecretAccessKey, Amazon.RegionEndpoint.USEast1); InvokeRequest invoke = new InvokeRequest { FunctionName = "AWSLambdaDockerContainer", InvocationType = InvocationType.RequestResponse, Payload = Newtonsoft.Json.JsonConvert.SerializeObject(html) }; //Get the InvokeResponse from the client InvokeRequest. InvokeResponse response = await client.InvokeAsync(invoke); //Read the response stream. 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); //Convert Base64String into a PDF document. return Convert.FromBase64String(responseText.ToString()); } catch (Exception ex) { Console.WriteLine($"Exception Occured HTMLToPDFHelper: {ex}"); } return Convert.FromBase64String(""); } }
- 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, Sign in 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:
- Add the following code 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(); } }
- Right click the test application and select Run Tests.
- By executing the program, you will get the PDF document as follows.
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.
AWS Lambda: AWSLambdaDockerContainer.zip
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
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.
Conclusion
I hope you enjoyed learning about how to convert HTML to PDF in AWS Lambda with NET 6 Container Image.
You can refer to our ASP.NET Core PDF’s feature tour page to know about its other groundbreaking feature representations. You can also explore our ASP.NET Core PDF example to understand how to present and manipulate data.
For current customers, you can check out our ASP.NET Core components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our ASP.NET Core PDF and other ASP.NET Core components.
If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!