How to Generate PDF using Asp.Net Core and Azure Chintan Prajapati October 9, 2018 8 min read 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 ? Which is best open source library or component to generate pdf using .net core, c# and Azure App Service ? How does azure app service plan being on linux or windows makes a difference? What plan to choose for pdf generation ? 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 Wkhtmltopdf DinkToPDF RotavitaHere is a comparison of their popularity on github.https://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 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 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. 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. 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 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) ” 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. Once you applied, just restart the web app. And now run the web appAnd 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. 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. private byte[] GeneratePdf(string htmlContent) { try { _logger.LogInformation("GeneratePdf started."); // Configure global settings for the PDF document var globalSettings = new GlobalSettings { ColorMode = ColorMode.Color, Orientation = Orientation.Portrait, PaperSize = PaperKind.A4, Margins = new MarginSettings { Top = 18, Bottom = 18 }, }; // Configure object settings for the HTML content 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 } }; // Create the PDF document var htmlToPdfDocument = new HtmlToPdfDocument { GlobalSettings = globalSettings, Objects = { objectSettings }, }; // Convert HTML to PDF return _converter.Convert(htmlToPdfDocument); } catch (Exception ex) { _logger.LogError("Error in GeneratePdf: {Message}", ex.Message); 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. 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. 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. Apply the plan, Restart the app and run, you will get the desired output. And when i see in the blob storage. 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. 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 With the free plan it is showing timeout errorProblem 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 readonly ILogger<HomeController> _logger; private readonly IFileProvider _fileProvider; private readonly IConfiguration _config; // Ensure you have a configuration instance injected public HomeController(IGeneratePdf generatePdf, ILogger<HomeController> logger, IFileProvider fileProvider, IConfiguration config) { _generatePdf = generatePdf; _logger = logger; _fileProvider = fileProvider; _config = config; // Initialize the configuration instance } [Obsolete] public async Task<IActionResult> Index() { try { // Generate PDF var bytes = _generatePdf.GetPDF("<h1 style='color:red'>Hello World</h1>"); // Retrieve storage configuration values var connString = _config.GetValue<string>("StorageKey") ?? string.Empty; var blobContainer = _config.GetValue<string>("blobContainer") ?? string.Empty; var blobName = _config.GetValue<string>("blobName") ?? string.Empty; // Create the blob client var storageAccount = CloudStorageAccount.Parse(connString); var blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve reference to the container and blob var container = blobClient.GetContainerReference(blobContainer); var blockBlob = container.GetBlockBlobReference(blobName); // Upload the byte array to the blob asynchronously await blockBlob.UploadFromByteArrayAsync(bytes, 0, bytes.Length); return Ok(new { Message = "File has been uploaded successfully." }); } catch (Exception ex) { // Log the error _logger.LogError("Error: {Message}", ex); // Create a message for the response var msg = ex.InnerException?.Message ?? ex.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 ServerDev/TestPlanLinuxWindowsF1 Shared Infrastructure (Windows Only) 1 GB memory 60 min/day compute FreeFreeD1 Shared Infrastructure (Windows Only) 1 GB memory 240 min/day computeNot 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)ProductionPlanLinuxWindowsP1V2 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.