Articles in this section
Category / Section

How to convert HTML to PDF in Azure Functions 4.0 with ASP.NET Core PDF?

7 mins read

Syncfusion® HTML to PDF converter for our ASP.NET Core PDF Library's feature tour page  used to convert web pages, and HTML to PDF. Using this library, you can convert any HTML strings or URL or web pages to PDF in Azure Functions 4.0(NET 6).

In this tutorial, we will illustrate the conversion of HTML to PDF using C# with advanced Blink rendering engine. In addition, our HTML to PDF converter will work seamlessly in 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.

Steps to convert HTML to PDF in Azure Functions 4.0

  1. Create an Azure Functions projects. Create Azure Function project in ASP.NET Core PDF

 

  1. Select framework to Azure Functions V4 (.NET 6) and select HTTP triggers as follows. Choose NET 6 framework in ASP.NET Core PDF

 

  1. Install the Syncfusion.HtmlToPdfConverter.Net.Linux NuGet package as a reference to the project.
    Install latest Linux NuGet package in ASP.NET Core PDF
  2. Include the following namespace in Functions1.cs file to convert the HTML to PDF using C#.
    using Syncfusion.HtmlConverter;
    using Syncfusion.Pdf;
    using System.Runtime.InteropServices;
    

C#

 

  1. Add the following code snippet in Function1 class to convert HTML to PDF in Azure Functions V4.
    [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, "bin/runtimes/linux/native");
    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
    }
    

 

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

Choose publish target in ASP.NET Core PDF

  1. After creating the profile, click the Publish button.

Create publish profile in ASP.NET Core PDF

  1. Now, go to the Azure portal and select the 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.

Example: https://htmltopdfazurefunctionblink.azurewebsites.net/api/Function1?code=aYCeymbJeHMGIwEEIuCIcNe….&url=https://www.syncfusion.com

Output document in ASP.NET Core PDF

A complete working sample can be downloaded from HtmlToPdf_AzureFunctions4.0.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 Syncfusion Essential® PDF features.


An online sample link to convert HTML to PDF.


Conclusion

I hope you enjoyed learning about how to convert html to pdf in Azure portal.

You can refer to our ASP.NET Core PDF Library's feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core PDF Library example to understand how to create and manipulate data.

For current customers, you can check out our Document processing libraries from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

 



Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (4)
Please  to leave a comment
MG
Miguel Goicochea

Hello I tried following this example and while it works well locally (the report takes 3 minutes to generate). However, when I publish to Azure I get a timeout after the function has been running for less than 4 minutes (3min 50s). The azure function is using a dedicated app plan and I have had no issues when running other products I have been evaluating for a longer period, so I am not sure if I am missing any settings on the converter.

GK
Gowthamraj Kumar

Hi Miguel,

The converter may throws the exception under Consumption/Free/Shared hosting plans on Azure. Please make sure you are not using the mentioned hosting plans to publish on Azure environment. Due to the access restrictions and limitation of these hosting plan, it prevents the loading of the browser process. So, the conversion will be failed or timeout in the Consumption/Free/Shared hosting plans on Azure environment. Other hosting plans does not have the restriction for loading the browser process.

If still you are facing the same error, kindly contact us through our Direct Trac

Regards,

Gowthamraj K

US
Underwood Studio

The OPENSSL assemblies link above doesn't work. It just tosses you to an "Access Denied" error page on S3. Can that link be updated?

GK
Gowthamraj Kumar

Hi Underwood,

Sorry for the inconvenience caused.

We have updated the proper OPENSSL assemblies link in this KB article. Now you can download the assemblies from below link,

OPENSSL: https://www.syncfusion.com/downloads/support/directtrac/general/ze/OPENSSL-1821714558

Please refer the below link for more details about OPENSSL,

UG: https://help.syncfusion.com/file-formats/pdf/convert-html-to-pdf/webkit#openssl

Please let us know if you need any further assistance with this.

Regards,

Gowthamraj K

JP
jay patadia

On my local machine, it is working fine. But, when deploying to Azure It throws an error, HTML conversion failed.

I am hosting it on the b1 plan, I have also unchecked the run from the package file option.

Can you help me to find out what is the issue here?

Thank you,

GK
Gowthamraj Kumar

Hi Jay,

Thank you for contacting Syncfusion support.

We already faced the similar issue in Azure functions 3.1. The reported issue may occurs due to QtBinaries assemblies are not copied properly with Azure SDK 3.0.11. Please follow the below steps to copy the files properly to resolve the reported issue.

  1. Open the Azure portal in browser.

  2. Navigate to the deployed Azure function in Azure portal.

  3. Open the console of Azure function.

    1.png

  4. As we said earlier, QtBinaries assemblies are not copied properly while publish to Azure functions.

  5. So, we need to manually copy all the assemblies from azure portal.

  6. QtBinariesWindows from location “c:\home\site\wwwroot\QtBinariesWindows” does not have all the assemblies, so we need to copy all the assemblies and inner folder from bin folder.

  7. Using cd command, navigate to the location “c:\home\site\wwwroot\bin\QtBinariesWindows” and run the below command.

cp . c:\home\site\wwwroot\QtBinariesWindows\

2.png

  1. Then we need to copy the files from “platform” and “imageformats” folders using the same approach.

  2. Using cd command, navigate to the location “c:\home\site\wwwroot\bin\QtBinariesWindows\platforms” and run the below command.

cp . c:\home\site\wwwroot\QtBinariesWindows\platforms

  1. Using cd command, navigate to the location “c:\home\site\wwwroot\bin\QtBinariesWindows\imageformats” and run the below command.

cp . c:\home\site\wwwroot\QtBinariesWindows\imageformats

  1. Ensure the all the files are copied to “c:\home\site\wwwroot\QtBinariesWindows” location using dir command. Also, ensure the inner folders (imageformats, platforms) has all the files.

    3.png

  2. Now try the conversion from Azure function URL.

  3. We need to copy this assemblies for the first time only.

Regards,

Gowthamraj K

NC
Netflg Consulting LLC

Hi, do you guys has any sample where the converter will work with an Azure function in Windows or do we have to necessarily go with Linux?

Thank you in advance

Access denied
Access denied