Articles in this section
Category / Section

How to Convert HTML to PDF Using Blink in Azure Functions Linux

4 mins read

The Syncfusion HTML to PDF converter is a .NET Core library for converting web pages, and HTML to PDF. Using this library, you can convert any HTML strings, URLs, or web pages to PDF in the Azure Functions Linux.

In this tutorial, we will illustrate the conversion of HTML to PDF using C# with the Blink rendering engine in the Azure Function Application Linux. In addition, our HTML to PDF converter will work seamlessly on various platforms like Azure cloud or web apps, Amazon Web Service (AWS), Docker, WinForms, WPF, ASP.NET MVC, ASP.NET Core with Windows, Linux, and MacOS.

Note:This article demonstrates how to use Azure Function 3.0. For Azure Function 4.0, kindly refer to the below KB.
How to convert HTML to PDF in Azure Functions 4.0?

Steps to convert HTML to PDF in the Azure Functions using the Blink rendering engine

  1. Create the Azure function project.
    CreateAzureFunction.png
  2. Select the Azure Functions type and the .NET Core version.
    Trigger.png
  3. Install the Syncfusion.HtmlToPdfConverter.Net.Linux NuGet package as a reference to your .NET Core Azure function application from NuGet.org.
    NuGetPackage.png

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

  1. Include the following namespaces in the Function1.cs file.
using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
using System.Runtime.InteropServices;
  1. Add the following code sample in the Function1 class to convert HTML to PDF using the Blink HTML converter in the Azure Functions Linux.
[FunctionName("Function1")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext executionContext)
{
     string blinkBinariesPath = string.Empty;
     try
     {
         blinkBinariesPath = SetupBlinkBinaries(executionContext);
     }
     catch
     {
         throw new Exception("BlinkBinaries initialization failed");
     }
 
     string url = req.Query["url"];
 
     //Initialize the HTML to PDF converter with the Blink rendering engine.
     HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);
     BlinkConverterSettings settings = new BlinkConverterSettings();
 
     //Set command line arguments to run without sandbox.
     settings.CommandLineArguments.Add("--no-sandbox");
     settings.CommandLineArguments.Add("--disable-setuid-sandbox");
 
     settings.BlinkPath = blinkBinariesPath;
 
     //Assign Blink Converter settings to the HTML converter. 
     htmlConverter.ConverterSettings = settings;
 
     //Convert URL to PDF.
     PdfDocument document = htmlConverter.Convert(url);
 
     MemoryStream ms = new MemoryStream();
     
     //Save and close the PDF document. 
     document.Save(ms);
     document.Close();
 
     ms.Position = 0;
 
     return new FileStreamResult(ms, "application/pdf");
  }

  1. Add the following helper methods to copy and set permission to the BlinkBinariesLinux folder.
private static string SetupBlinkBinaries(ExecutionContext executionContext)
{
string blinkAppDir = Path.Combine(executionContext.FunctionAppDirectory, "BlinkBinariesLinux");
string tempBlinkDir = Path.GetTempPath();
string chromePath = Path.Combine(tempBlinkDir, "chrome");
 
if (!File.Exists(chromePath))
{
 
     CopyFilesRecursively(blinkAppDir, tempBlinkDir);
 
     SetExecutablePermission(tempBlinkDir);
}
return tempBlinkDir;
}
 
 
private static void CopyFilesRecursively(string sourcePath, string targetPath)
{
//Create all the directories from the source to the destination path.
foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
{
    Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
}
 
//Copy all the files from the source path to the destination path.
foreach (string newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))
{
    File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);
}
}
 
[DllImport("libc", SetLastError = true, EntryPoint = "chmod")]
internal static extern int Chmod(string path, FileAccessPermissions mode);
 
private static void SetExecutablePermission(string tempBlinkDir)
{
FileAccessPermissions ExecutableFilePermissions = FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite | FileAccessPermissions.UserExecute |
FileAccessPermissions.GroupRead | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherRead | FileAccessPermissions.OtherExecute;
 
string[] executableFiles = new string[] { "chrome", "chrome_sandbox" };
 
foreach (string executable in executableFiles)
{
    var execPath = Path.Combine(tempBlinkDir, executable);
 
    if (File.Exists(execPath))
    {
        var code = Function1.Chmod(execPath, ExecutableFilePermissions);
        if (code != 0)
        {
            throw new Exception("Chmod operation failed");
        }
    }
    }
}

  1. Include the below enum in the Function1.cs file.
[Flags]
internal enum FileAccessPermissions : uint
{
OtherExecute = 1,
OtherWrite = 2,
OtherRead = 4,
 
GroupExecute = 8,
GroupWrite = 16,
GroupRead = 32,
 
UserExecute = 64,
UserWrite = 128,
UserRead = 256
}

Publish to Azure Functions Linux

  1. Right-click the project and select Publish. Then, create a new profile in the Publish Window. The Blink rendering engine will work in consumption plan. So, you can create the Azure Function App service with a consumption plan.
    SelectPublish.png
  2. After creating the profile, click the Publish button.
    Publish.png
  3. Now, go to the Azure portal and select App Services. After running the service, click Get function URL > Copy. Include the URL as a query string in the URL. Then, paste it into the new browser tab. You will get the PDF document as follows.
    Output.png

A complete working sample can be downloaded from HtmlToPdfBlinkAzureFunction.zip.

Take a moment to peruse the documentation where you can find converting HTML pages to PDF document along with respective customization options and features

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

An online sample link to convert HTML to PDF.

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