How to Generate PDF using Asp.Net Core and Azure

Hello MS Azure enthusiastic!!

Earlier when there was no cloud era, we were hosting all sites on mostly dedicated or virtual private servers.

Nowadays Azure based cloud hosting is the only alternative left for all Microsoft technology lovers to build their scalable applications in the cloud with least effort. . There are many ways to generate pdf using .net core using paid and free both types of components. But a problem comes into picture for a typical developer’s life on the day of release i.e deployment. He . he.

I know you have been on such an adventure when all code works perfectly in your Windows PC and it doesn’t work in Staging or Live server. This used to happen to me too!!

Then you realize that the open source component which you used is not compatible or has other dependencies which needs to be made available on the server. And then you do not control or manage the hosting for clients. Now you are in a trap. !!

You may decide to rewrite code with another library, or suggest an option to buy a paid component for pdf generation.

Which means time wasted, production deadlines crossed, and additional component cost to client. :( huh ..

Too bad!!

This happened to me again when my old open source pdf library was working nice on windows pc and windows server, and all of sudden i assumed that in azure also it would work without any problem.

But I was wrong !!

There were many limitations or details which I needed to be aware of before making my decision on choosing the right PDF generation library for azure and .net core.

So to save your precious time, I have written a detailed article.

Do you also have questions, which I had before doing this research ?

  1. Which is best open source library or component to generate pdf using .net core, c# and Azure App Service ?
  2. How does azure app service plan being on linux or windows makes a difference? What plan to choose for pdf generation ?
  3. What kind of price you or your company or your client may have to pay to azure for Best in class PDF generation facility ?

If your answer is yes then i want to take your attention for the next 5 minutes.

When I was searching in google for “generate pdf using .net core and azure ”. To achieve this I was searching to find the best open source library to work with. I found many libraries but here I am listing some of them in which I worked.

The list of libraries

  1. Wkhtmltopdf
  2. DinkToPDF
  3. Rotavita

Here is a comparison of their popularity on github.

comparison-of-their popularityhttps://www.githubcompare.com/wkhtmltopdf/wkhtmltopdf+rdvojmoc/dinktopdf+webgio/rotativa.aspnetcore

Wkhtmltopdf

  • It is an open source library which is able to put several objects into the output file, an object is either a single webpage, a cover webpage or a table of contents.
  • This library will work but with some conditions and limitations. Further I will describe this. Let’s see how we can use this.
  • Create .Net Core empty web application.
  • Install Wkhtmltopdf.NetCore NuGet Package.

PM > Install-Package Wkhtmltopdf.NetCore -Version 3.0.2

A screenshot of a Visual Studio project named "PDFLibraryWebApp" built with Asp.Net Core, displaying the project structure including folders like Dependencies, Properties, PDFs, and files such as appsettings.json, HomeController.cs, Program.cs, and Startup.cs. The project is ready for deployment to Azure.

  • Add One Controller. Here I have added a HomeController. And add this code in that controller.


public class HomeController : Controller
{
private readonly IGeneratePdf _generatePdf;
private static ILogger _logger;
private readonly IFileProvider _fileProvider;
public HomeController(IGeneratePdf generatePdf, ILogger<HomeController> logger, IFileProvider fileProvider)
{
_generatePdf = generatePdf;
_logger = logger;
_fileProvider = fileProvider;
}[Obsolete]
public IActionResult Index()
{
try
{
var bytes = _generatePdf.GetPDF(“<h1 style=’color:red’>Hello World<h1>”);
System.IO.File.WriteAllBytes(Environment.ContentRootPath + @”PDfswkhtmltopdf.pdf”, bytes);
return PhysicalFile(Environment.ContentRootPath + @”PDfswkhtmltopdf.pdf”, “application/pdf”);
}
catch (Exception ex)
{
_logger.LogInformation(“Error : ” + ex);
var msg = ex.Message;
if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
msg = ex.InnerException.Message;
System.IO.File.WriteAllText(Environment.ContentRootPath + @”PDfswkhtmltopdfError.txt”, msg);
return PhysicalFile(Environment.ContentRootPath + @”PDfswkhtmltopdfError.txt”, “application/txt”);
}
}
}
  • Here the Library is providing the Interface Service IGeneratePdf. This service has many methods.


Here the Library is providing the Interface Service IGeneratePdf. This service has many methods.

  • Here for the demo I am using GetPDF in which we can pass html strings.
  • And in the above code snippet you can see I have added the html.

“<h1 style=’color:red’>Hello World<h1>”
  • Use above code, save and run the application it will open the pdf file in the browser.


Use above code, save and run the application it will open the pdf file in the browser.

  • Now Our challenge is to make it work with Azure Cloud App service.
  • Create an App service and Publish the code into it.
  • Here i have published my project into free app service plan
  • If you are new with the app service and publishing code here is the reference :
    • https://docs.microsoft.com/en-au/azure/app-service/quickstart-dotnetcore?tabs=net60&pivots=development-environment-vs
  • Now here comes the limitation. And this limitation only comes into picture if Host is Azure. Here it is!

Problem Statement

  • Once your code has been published and run it will not work as it should.
  1. Rotativa folder with the wkhtmltopdf exe file as per system OS. you can get it from GitHub. Here is the link and paste this folder to the root folder with the help of Kudu Console
    https://github.com/fpanaccia/Wkhtmltopdf.NetCore/tree/master/Wkhtmltopdf.NetCore/Rotativa
  2. Once you run the application and it runs successfully then you will find the pdf with the incorrect fonts.

Once you run the application and it runs successfully then you will find the pdf with the incorrect fonts.

  • But no worries. We have a solution and yes that’s why this article is all about.

Solution

  • The ultimate solution is to use it with Azure so that you need to upgrade the plan. Here i have used Azure free plan, which has limited memory allocation and that’s why some features are not working
  • So The plan I used is a free plan. You can check your plan by going to your app service and clicking on “Scale Up (App Service Plan) ”

Screenshot of an Asp.Net Core web app service configuration page in Azure, showing options for resource group, location, subscription ID, and tools for diagnosing issues and managing application insights.
Solution

  • As shown in the above image the current plan is from Dev/Test and the pricing tier used is F1 free plan.
  • So it won’t work in Any plans from Dev/Test section it will only work in the Any plans in Production section.
  • Let’s try that…!

Solution Result

  • Change the plan from free to paid in the Production section. You can select any plan from production. Here I am using the minimum plan.

Screenshot of Azure App Service Pricing Tiers for "Production" featuring Asp.Net Core options. Explore S1, S2, and S3 tiers with details like ACU, memory, and disk space. The "Select" button is highlighted for the Azure S1 tier.

  • Once you applied, just restart the web app.

Screenshot of an Asp.Net Core web app management interface on Azure, featuring essential options for restarting, setting actions, and deployment. Highlights include the restart button and sections like Diagnose and solve problems for optimal performance management.

  • And now run the web app

Screenshot of a PDF document open in an Asp.Net Core browser, showcasing the text "Hello World" in vibrant red.

And it works…!

  • But now the big concern is price!! Why would you pay so much high ~5000 INR for Open source PDF facility
  • Rather I would buy a paid component. !
  • Anyways, I have figured out how to do this absolutely free in azure. Which i will share with you, i.e. how to leverage linux based free app service plan for PDF generation. And in which library it works seamlessly.
  • Anyways, as of now lets move toward a second open source .net core library for pdf generation in azure.

2. DinkToPDF

  • The source code for this library is in the GitHub CorePdfDemo repository.
  • This is another open source library which is using the wkhtmltopdf wrapper.
  • This library gives you more customization for generating PDFs in a convenient way. For ex,

var globalSettings = new GlobalSettings
{
ColorMode = ColorMode.Color,
Orientation = Orientation.Portrait,
PaperSize = PaperKind.A4,
Margins = new MarginSettings { Top = 18, Bottom = 18 },
};
  • It will give you options and methods to set the PDF size, margins, etc…
  • I have created one example and here is the main code to use. Please Click Here to get the whole example.

private byte[] GeneratePdf(string htmlContent)
{
try
{
_logger.LogInformation(“GeneratePdf start : “);
var globalSettings = new GlobalSettings
{
ColorMode = ColorMode.Color,
Orientation = Orientation.Portrait,
PaperSize = PaperKind.A4,
Margins = new MarginSettings { Top = 18, Bottom = 18 },
};

 

var objectSettings = new ObjectSettings { PagesCount = true, HtmlContent = htmlContent, WebSettings = { DefaultEncoding = “utf-8” }, HeaderSettings = { FontSize = 10, Right = “Page [page] of [toPage]”, Line = true }, FooterSettings = { FontSize = 8, Center = “PDF demo”, Line = true }, };

 

var htmlToPdfDocument = new HtmlToPdfDocument() { GlobalSettings = globalSettings, Objects = { objectSettings }, }; return _converter.Convert(htmlToPdfDocument); } catch (Exception ex) { _logger.LogInformation(“Error GeneratePdf : ” + ex); return null; } }

  • So once you download the code and run it it will work locally. Basically, the key thing which is required is DinkToPdf NugetPackage and the folder of v12.0.4. It is the wkhtmltopdf Wrapper.

Screenshot of a file directory showcasing highlighted packages: "DinkToPdf (1.0.8)" with two subfolders under "v0.12.4" for "32 bit" and "64 bit", seamlessly integrating with Asp.Net Core projects and optimized for deployment on Azure environments.

  • I have used the Invoice template for a demo. And you can find it in the Views folder.
  • Here I used to save the pdf file to Azure Blob Storage after pdf generation. For that please provide your storage key and the pdf file name in the appsettings.json.
  • Once all set the code Host the code into Azure app service. And run.
  • And run this url to get your output : https://{AppServiceName}.azurewebsites.net/documentgenerator
  • Problem Statement : Once you hit the above URL, It will take time and then it will give you the timeout error.

500-The-request-timed-out

  • Solution : The Solution for this is again you have to use the production plan (paid) of Azure App service.
  • Here, I am using the minimum plan for this.

Screenshot of an Asp.Net Core web interface on Azure showing pricing tiers for production-level workloads. The highlighted segment displays the S1 tier with 100 ACU, 1.75 GB memory, and $73.26/month estimated cost.

  • Apply the plan, Restart the app and run, you will get the desired output.

Text screenshot from an Asp.Net Core application on Azure displaying: "{'statusCode': 200, 'message': 'pdf file has been successfully uploaded'}.

  • And when i see in the blob storage.

Screenshot displaying a file directory with two PDF files: "GeneratedPdf.pdf" and "RazorTemplatePdf.pdf," both labeled under the "Hot (inferred)" access tier. These files were efficiently managed using Asp.Net Core within the Azure ecosystem.

  • So it’s all about choosing the right hosting plan and your code works well.

3. Rotavita

  • Another Library to generate pdf.
  • It’s working successfully locally and after hosting but yet another dependency.
  • Have to add the wkhtmltopdf.exe in Folder under wwwroot Folder and Rotavita.AspNetCore NugetPackage.
  • Click Here to download the whole example.

Screenshot of a C# class code in an ASP.NET Core namespace, integrating Azure functionalities. The code defines a class for rendering PDF views, with several methods and properties for handling different view formats.

  • It is the most easy to use library.
  • After hosting it to Azure it won’t work with free plan it will only work with the Production Plan
  • The result will be

A webpage titled "Index: RotativaDemo" in Asp.Net Core displays a users list with columns for ID, name, and address. Options to edit, view details, and delete are available for each user, seamlessly integrating with Azure for enhanced functionality.

  • With the free plan it is showing timeout error

500-The-request-timed-out

Problem Statement

  • As we saw, a solution to generate pdf using core and azure host is working but has to use the paid plans.

Solution (For App service Free plan)

  • So with my further research and guidance I finally found the solution is to host the website on Azure app service with Linux Operating system.
  • I got success with only wkhtmltopdf library and the more additional and important benefit is that it worked on App service free plan.
  • Create one Azure app service with Linux operating system with the free plan. Other configurations will be same except Operating system
  • Here i am using the same code of wkhtmltopdf demo in windows with little bit changes.
  • Use this code and publish it to the Azure App Service (Linux) with the free plan and it will work as expected.
  • For the whole example code (https://github.com/satva-git/satvaPdf/tree/main/WkHtmlToPDF).

public class HomeController : Controller
{
private readonly IGeneratePdf _generatePdf;

 

private static ILogger _logger; private readonly IFileProvider _fileProvider;

 

public HomeController(IGeneratePdf generatePdf, ILogger<HomeController> logger, IFileProvider fileProvider) { _generatePdf = generatePdf; _logger = logger; _fileProvider = fileProvider; }

[Obsolete] public IActionResult Index() { try { var bytes = _generatePdf.GetPDF(“<h1 style=’color:red’>Hello World<h1>”); var connString = _config.GetValue(“StorageKey”, “”); var blobContainer = _config.GetValue(“blobContainer”, “”); var blobName = _config.GetValue(“blobName”, “”); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connString); // Create the blob client. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve reference to a previously created container. CloudBlobContainer container = blobClient.GetContainerReference(blobContainer); // Retrieve reference to a blob named “myblob”. CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName); // upload from Stream object during file upload blockBlob.UploadFromByteArrayAsync(bytes, 0, bytes.Length); return Ok(new { Message = “File has been uploaded successfully.”}); } catch (Exception ex) { _logger.LogInformation(“Error : ” + ex); var msg = ex.Message; if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message)) msg = ex.InnerException.Message; return Ok(new { Message = “Error : ” + msg }); } } }

  • If you want to know more about the comparison of App service plans of windows and linux see the below table for your reference.

Prices Comparison for Linux & Windows Server

Dev/Test
PlanLinuxWindows
F1
Shared Infrastructure
(Windows Only)
1 GB memory
60 min/day compute
FreeFree
D1
Shared Infrastructure
(Windows Only)
1 GB memory
240 min/day compute
Not Applicable$9.49  /Month (Estimated)
B1
100 Total ACU
1.75 GB memory
A-Series compute equivalent
$13.14  /Month(Estimated)$54.75  /Month(Estimated)
B2
200 Total ACU
3.5 GB memory
A-Series compute equivalent
$26.28  /Month(Estimated)$109.50  /Month(Estimated)
B3
400 Total ACU
7 GB memory
A-Series compute equivalent
$51.83  Month(Estimated)$219.00  /Month(Estimated)
Production
PlanLinuxWindows
P1V2
210 Total ACU
3.5 GB memory
Dv2-Series compute equivalent
$83.95  /Month (Estimated)$146.00  /Month (Estimated)
P2V2
420 Total ACU
7 GB memory
Dv2-Series compute equivalent
$168.63  /Month(Estimated)$292.00  /Month(Estimated)
P3V2
840 Total ACU
14 GB memory
Dv2-Series compute equivalent
$337.26  /Month(Estimated)$584.00  /Month(Estimated)
P1V3
195 minimum ACU/vCPU
8 GB memory
2 vCPU
$127.75/Month(Estimated)$244.55  /Month(Estimated)
P2V3
195 minimum ACU/vCPU
16 GB memory
4 vCPU
$255.50  /Month(Estimated)$489.10  /Month(Estimated)
P3V3
195 minimum ACU/vCPU
32 GB memory
8 vCPU
$511.00  /Month(Estimated)$978.20  /Month(Estimated)
S1
100 Total ACU
1.75 GB memory
A-Series compute equivalent
$69.35  /Month (Estimated)$73.00  /Month (Estimated)
S2
200 Total ACU
3.5 GB memory
A-Series compute equivalent
$138.70  /Month(Estimated)$146.00  /Month(Estimated)
S3
400 Total ACU
7 GB memory
A-Series compute equivalent
$277.40  /Month(Estimated)$292.00  /Month(Estimated)

Conclusion

  • It is possible to generate pdf using dotnet core with Azure hosted apps with linux and windows operating system.
  • If you want to use paid plans then use the windows operating system, whereas to use with free app service plan use wkhtmltopdf library with linux operating system in Azure hosted app service.

    Want to Build PDF using Azure and Asp. Core? Connect With us as we are the Best Azure Consulting Companies in Global.

Article by

Chintan Prajapati

Chintan Prajapati, a seasoned computer engineer with over 20 years in the software industry, is the Founder and CEO of Satva Solutions. His expertise lies in Accounting & ERP Integrations, RPA, and developing technology solutions around leading ERP and accounting software, focusing on using Responsible AI and ML in fintech solutions. Chintan holds a BE in Computer Engineering and is a Microsoft Certified Professional, Microsoft Certified Technology Specialist, Certified Azure Solution Developer, Certified Intuit Developer, and Xero Developer.Throughout his career, Chintan has significantly impacted the accounting industry by consulting and delivering integrations and automation solutions that have saved thousands of man-hours. He aims to provide readers with insightful, practical advice on leveraging technology for business efficiency.Outside of his professional work, Chintan enjoys trekking and bird-watching. Guided by the philosophy, "Deliver the highest value to clients". Chintan continues to drive innovation and excellence in digital transformation strategies from his base in Ahmedabad, India.