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. (Last updated on: June 24, 2019).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to convert HTML to PDF in Azure using .NET Core

Platform: ASP.NET Core |
Control: PDF |
Published Date: November 15, 2018 |
Last Revised Date: April 26, 2019

Syncfusion HTML to PDF for .NET used to convert webpages, SVG, MHTML, and HTML to PDF. Using this library, you can convert HTML to PDF in Azure using .NET Core.

Steps to convert HTML to PDF in Azure programmatically:

  1. Create a new ASP.NET Core MVC application. Create new ASP.NET Core application in visual studio
  2. Install the Syncfusion.HtmlToPdfConverter.QtWebKit.Net.Core NuGet package as reference to your .NET Core application from NuGet.org Install required nuget packages
  3. Copy the QtBinariesWindows folder from the installed HtmltoPdfConverter package and paste it into the folder which contains the HTMLtoPDF_Azure.csproj file. QtBinariesWindows location  Pate location for QtBinariesWindows
  4. Then, set Copy to output directory to copy all the QtBinariesWindows (All files including inner folders and files) assemblies. Copy to output directory property
  5. Add an Export To PDF button in index.cshtml. Add Button in html page
  6. Include the following namespaces and code snippet for converting HTML to PDF in Azure.

C#

using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
using System.IO;
using Microsoft.AspNetCore.Hosting;

 

//To get content root path of the project
private readonly IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment)
{
   _hostingEnvironment = hostingEnvironment;
}
 
public IActionResult ExportToPDF()
{
 //Initialize HTML to PDF converter 
 HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
 WebKitConverterSettings settings = new WebKitConverterSettings();
  //Set WebKit path
  settings.WebKitPath = Path.Combine(_hostingEnvironment.ContentRootPath, "QtBinariesWindows");
  //Assign WebKit settings to HTML converter
  htmlConverter.ConverterSettings = settings;
  //Convert URL to PDF
  PdfDocument document = htmlConverter.Convert("https://www.google.com");
  MemoryStream stream = new MemoryStream();
  document.Save(stream);
  return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf, "Sample.pdf");
}
  1. The HTML converter requires OPENSSL libraries to convert HTTPS sites to PDF. The OPENSSL assemblies can be copied to the QtBinariesWindows folder parallel to the Syncfusion.WebKitWrapper assembly and published along with the binaries. Make sure to set copy always for all the QtBinariesWindows assemblies with OPENSSL assemblies. Copy the assemblies
  2. Right click the project and select Publish. Publish the project
  3. Create new profile in the Publish window. Pick publish target
  4. Create App service using Azure subscription and select a hosting plan. Create new App service
  5. HTML to PDF conversion will works from basic hosting plan (B1). So, select the hosting plan as needed. HTML to PDF conversion will not work if the hosting plan is Free/Shared. Configure azure hosting plan
  6. After creating a profile, click the Publish button. Publish azure
  7. Now, the published website will open in the browser, then you can export HTML to PDF. Published website
  8. By exporting HTML to PDF, you will get the PDF document as follows. Screenshot of output PDF document

A complete working sample can be downloaded from HTMLtoPDF_Azure.zip

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.

2X faster development

The ultimate ASP.NET Core UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment
Comments
ajit goel
Jun 24, 2019

"HTML to PDF conversion will not work if the hosting plan is Free/Shared."=> why will the html to pdf conversion not work if the hosting plan is free\shared? Can you please advise?

Reply
Gowthamraj Kumar [Syncfusion]
Jun 25, 2019

Hi Ajit,

Our HTML to PDF converter internally using QtWebKit rendering engine and we will internally launch the browser process for converting HTML to PDF. Due to the access restrictions and limitation of Consumption/Free/Shared hosting plan, it prevents the loading of the browser process. So, the conversion will be failed in the Consumption/Free/Shared hosting plans on Azure environment. Other hosting plans does not have the restriction for loading the browser process.

Regards,

Gowthamraj K

ajit goel
Jun 24, 2019

Hello,

I am getting the following error, after I deploy my application to Azure App Service. The application works correctly on my local machine. I have a S1 hosting plan on Azure. Can you please advise what the possible issue could be? :

PdfException: No such file or directory Syncfusion.HtmlConverter.HtmlConverter.ConvertHtmlToPdf(string url, int width, int height) Syncfusion.HtmlConverter.HtmlToPdfConverter.Convert(string url) HTMLtoPDF_Azure.Controllers.HomeController.ExportToPDF() in C:\Users\AjitGoel\Downloads\Convert HTML to PDF in Azure using .NET Core-Syncfusion\HTMLtoPDF_Azure\HTMLtoPDF_Azure\Controllers\HomeController.cs lambda_method(Closure , object , Object[] ) Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d12.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d10.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context) Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d14.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d22.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d17.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d15.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.AspNetCore.Builder.RouterMiddleware+d4.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d7.MoveNext()

Reply
Gowthamraj Kumar [Syncfusion]
Jul 05, 2019

Hi Ajit,

After publishing the application to Azure App service Linux, the converter throws "No such file or directory exception". Please refer below steps to overcome this exception and get the conversion succeeded in Azure App service Linux.

  • Create a new ASP.NET Core Web application and integrate the HTML to PDF conversion changes.
  • Copy the QtBinaries for Linux folder to the project folder and set Copy local as always. So, that the QtBinaries will be published to Azure environment.
  • After published the Application to Azure App Service Linux, the converter throws "No such file or directory exception".

Refer below steps to overcome the no such file or directory exception:

  • WebKit HTML converter for Linux has some dependency packages for converting HTML to PDF. By default the Azure server does not have these packages. So, we need to install the packages on the server. Please refer below link for dependency packages for converting HTML to PDF in Linux.

UG: Prerequisites for Linux

  • There is two ways to install the dependency packages to Azure server. i). Using SSH from Azure portal. ii). By running the commands from C#.

Using SSH from Azure portal:

  1. After the published the Web application, login to the Azure portal in a web interface and open the published app service.
  2. Under Development Tools Menu, Open the SSH and Click the go link.
  3. From the terminal window you can install the dependency packages. Please use below single command to install the all dependencies packages.
apt-get update && apt-get -y install xvfb && apt-get -y install fontconfig && apt-get -y install libssl1.0-dev && apt-get -y install libx11-dev libx11-xcb-dev libxcb-icccm4-dev libxcb-image0-dev libxcb-keysyms1-dev libxcb-randr0-dev libxcb-render-util0-dev libxcb-render0-dev libxcb-shm0-dev libxcb-util0-dev libxcb-xfixes0-dev libxcb-xkb-dev libxcb1-dev libxfixes-dev libxrandr-dev libxrender-dev

Running the commands from C#:

  1. Create shell file (dependenciesInstall.sh) with the above commands.
  2. Copy the file to project folder and set copy local as always.
  3. Get the path of the .sh file and run the file using below method.
  4. Call this method only once in the startup class.
private void InstallDependencies(string shellFilePath)
{
     Process process = new Process
     {
          StartInfo = new ProcessStartInfo
          {
               FileName = "/bin/bash",
               Arguments = "-c " + shellFilePath,
               CreateNoWindow = true,
               UseShellExecute = false,
          }
     };
     process.Start();
     process.WaitForExit();
}

Notes : Please make sure that the QtBinariesLinux folder is placed in the project folder.

Regards,

Gowthamraj K

Subrata Das
Jul 23, 2019

Hi Gowthamraj, I am using HTML to PDF converter in my Asp.net Core 2.2 Api project. I have followed all the steps mentioned in this article and it's working perfectly fine in local machine. But I get 500 internal server error when I publish it to Azure and invoke the particular method.

Kindly help me in solving this issue.

Thanks, Subrata

Reply
Gowthamraj Kumar [Syncfusion]
Jul 24, 2019

Hi Subrata,

We are tried to reproduce the reported issue with provided details. We have created a simple Web API sample with provided details in Net core 2.2 and checked the conversion in Azure App service. When we host the Web API to Azure App service, we also get the HTTP Error 500 server in our side. This error may occurs due to missing of configuration settings in startup. We can overcome this issue by adding the appsettings.json to startup configuration. We have modified the configuration settings in below sample, now the conversion works properly without any issue. Please find the code snippet for startup.

public Startup(IHostingEnvironment env)
{
   var builder = new ConfigurationBuilder().
                 SetBasePath(env.ContentRootPath).
                 AddJsonFile("appsettings.json", false, true).
                 AddEnvironmentVariables();
   configuration = builder.Build();
}

While hosting the Web API application in Azure app service, we have to manually make the request to the API in the web browser to get the required result. Kindly please try the below sample in your end and let me know the result.

Sample: DotNetCoreApiSample

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

Regards,

Gowthamraj K

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
Live Chat Icon