How to convert HTML to PDF in C# .NET Framework

By the end of this tutorial, you will have the ability to fully render a website from its HTML string and create a PDF version of the rendered site. Before you start cracking your knuckles in preparation for all that coding, let me first tell you that there is a much easier way. Through the simple use of an API, we can start having this functionality almost instantly. Let me show you how.

The first step is to install our client. By running the following command from package manager, NuGet will handle it for you.

Install-Package Cloudmersive.APIClient.NET.DocumentAndDataConvert -Version 2.2.0

From there, run ConvertWebHtmlToPdf, as shown here.

using System;using System.Diagnostics;using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Api;using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Client;using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Model;namespace Example{public class ConvertWebHtmlToPdfExample{public void main(){// Configure API key authorization: ApikeyConfiguration.Default.AddApiKey("Apikey", "YOUR_API_KEY");// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed// Configuration.Default.AddApiKeyPrefix("Apikey", "Bearer");var apiInstance = new ConvertWebApi();var input = new HtmlToPdfRequest(); // HtmlToPdfRequest | HTML to PDF request parameterstry{// Convert HTML string to PDFbyte[] result = apiInstance.ConvertWebHtmlToPdf(input);Debug.WriteLine(result);}catch (Exception e){Debug.Print("Exception when calling ConvertWebApi.ConvertWebHtmlToPdf: " + e.Message );}}}}

And that about does it. Now we just need to drop in our HTML and the API will respond with our finished PDF file. Awesome!

Image for post
Image for post

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store