How to Convert HTML to PDF in C# .NET Core Framework
Using just a few lines of code, we can easily convert HTML strings to PDF documents with a free API.
Instead of writing a bunch of complicated code to handle our conversion, we can call a free API using complementary C# .NET Core code examples instead. This service will render an image of our HTML file and save that image in PDF format.
First, let’s install the client SDK. We can run the below command in our Package Manager console to install via NuGet:
Install-Package Cloudmersive.APIClient.NETCore.DocumentAndDataConvert -Version 2.2.1
Next, let’s take care of API call authorization. We can use a free Cloudmersive API key to make up to 800 API calls per month (once we reach that total, it’ll simply reset the following month).
Finally, let’s use the below code examples to call the function.
using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NETCore.DocumentAndDataConvert.Api;
using Cloudmersive.APIClient.NETCore.DocumentAndDataConvert.Client;
using Cloudmersive.APIClient.NETCore.DocumentAndDataConvert.Model;
namespace Example
{
public class ConvertWebHtmlToPdfExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");
var apiInstance = new ConvertWebApi();
var input = new HtmlToPdfRequest(); // HtmlToPdfRequest | HTML to PDF request parameters
try
{
// Convert HTML string to PDF
byte[] result = apiInstance.ConvertWebHtmlToPdf(input);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling ConvertWebApi.ConvertWebHtmlToPdf: " + e.Message );
}
}
}
}
When we pass our HTML string in our input request, we can also specify any extra loading wait time our HTML string might need (e.g., for loading media). We can also determine the scale factor & if we want to include background graphics in our final document.
{
"Html": "string",
"ExtraLoadingWait": 0,
"IncludeBackgroundGraphics": true,
"ScaleFactor": 0
}
That’s all there is to it — now we can easily convert HTML strings to PDF documents with a few lines of code.