Blog Post

How to Generate PDF Certificates from HTML in C#

Illustration: How to Generate PDF Certificates from HTML in C#

In this post, you’ll learn how to generate PDF certificates from HTML using our C# PDF Generator API. With our API, you can generate 100 PDF certificates per month for free. To access your API key, sign up for a free account.

Certificates are most commonly generated by educational institutions, online course platforms, and corporate training programs. PDF certificates can automatically be generated when a student or employee successfully completes their program. To further streamline the process, a student’s name, program, and completion date can be pulled from a database and dynamically inserted into the certificate.

To help you get started, we’ve provided a free certificate template in HTML and CSS that can be customized to meet your specific requirements. You can easily style your certificate by updating the CSS file with your own custom images and fonts.

Requirements

To get started, you’ll need:

To access your PSPDFKit API key, sign up for a free account. Your account lets you generate 100 documents for free every month. Once you’ve signed up, you can find your API key in the Dashboard > API Keys section.

Information

You can find a similar example made for a receipt template on GitHub.

Creating a New .NET Project

Create a new .NET project via the .NET command-line interface (CLI) with the following command:

dotnet new console --name PspdfkitApiDemo

Change your directory to the newly created project directory:

cd PspdfkitApiDemo

To make an HTTP request, install RestSharp as a dependency:

dotnet add package RestSharp -v 106.15.0

Downloading the Certificate Template

Download the certificate template and extract the contents of the ZIP file into a folder. You’ll get an HTML file, Inter fonts, a Space Mono font, SVG logos, and a README file.

Creating a CSS File

If you open the index.html file, you’ll see the styles between the opening and closing <style> tag. Copy the styles to a new file called style.css, and save it in the same folder:

@font-face {
	font-family: 'Inter';
	src: url('Inter-Regular.ttf') format('truetype');
	font-weight: 400;
	font-style: normal;
}

@font-face {
	font-family: 'Inter';
	src: url('Inter-Medium.ttf') format('truetype');
	font-weight: 500;
	font-style: normal;
}

@font-face {
	font-family: 'Inter';
	src: url('Inter-Bold.ttf') format('truetype');
	font-weight: 700;
	font-style: normal;
}

@font-face {
	font-family: 'Space Mono';
	src: url('SpaceMono-Regular.ttf') format('truetype');
	font-weight: 400;
	font-style: normal;
}

body {
	font-size: 0.875rem;
	font-family: 'Inter', sans-serif;
	font-weight: 400;
	color: #000000;
	text-align: center;
	margin: 0 auto;
	position: relative;
}

#pspdfkit-header {
	font-size: 0.625rem;
	text-transform: uppercase;
	letter-spacing: 2px;
	font-weight: 700;
	color: #717885;
	margin-top: 2.5rem;
	margin-bottom: 2.5rem;
}

.logo {
	margin-top: 2.5rem;
	height: 1.5rem;
	width: auto;
}

h1 {
	font-family: 'Space Mono', monospace;
	font-size: 2.25rem;
	font-weight: 400;
	margin-top: 0;
}

h4 {
	font-family: 'Space Mono', monospace;
	font-size: 1rem;
	font-weight: 400;
}

.page {
	margin-left: 5rem;
	margin-right: 5rem;
}

.form {
	display: flex;
	flex-direction: column;
	margin-top: 6rem;
}

.border-bottom {
	border: 1px solid #000000;
	border-top: none;
	border-left: none;
	border-right: none;
}

.signer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin: 2rem 0 2rem 0;
}

.signer-item {
	flex-grow: 1;
}

input {
	color: #4537de;
	font-family: 'Space Mono', monospace;
	font-size: 1rem;
	text-align: center;
	margin-top: 4rem;
	height: 4rem;
	width: 100%;
	box-sizing: border-box;
}

input#name {
	font-size: 1.5rem;
}

#pspdfkit-footer {
	font-size: 0.5rem;
	text-transform: uppercase;
	letter-spacing: 1px;
	font-weight: 500;
	color: #717885;
	margin-top: 2.5rem;
	bottom: 2.5rem;
	position: absolute;
	width: 100%;
}

.footer-columns {
	display: flex;
	justify-content: space-between;
	padding-left: 2.5rem;
	padding-right: 2.5rem;
}

To access the styles from index.html, use the <link> tag. While referring to the stylesheet file, just use the name of the file and don’t create nested paths:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta
			name="viewport"
			content="width=device-width, initial-scale=1.0"
		/>
		<title>Certificate</title>
		<link rel="stylesheet" href="style.css" />
	</head>
</html>

Interacting with the API

Now, open the Program.cs file. It should have the Program class with the Main method:

using System;
using System.IO;
using System.Net;
using RestSharp;

namespace PspdfkitApiDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      // Implement your call to PSPDFKit API here.
    }
  }
}

Preparing the Request

Next, you can start making your request. Use the RestClient class to make requests to the PSPDFKit API /build endpoint.

Then, create a RestRequest with the required authorization header, the files you want to send, and the instructions as a parameter:

using System;
using System.IO;
using System.Net;
using RestSharp;

namespace PspdfkitApiDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      var client = new RestClient("https://api.pspdfkit.com/build");

      var request = new RestRequest(Method.POST)
        .AddHeader("Authorization", "Bearer {YOUR_API_KEY}") // Replace {YOUR_API_KEY} with your API key.
        .AddFile("index.html", "index.html")
        .AddFile("style.css", "style.css")
        .AddFile("Inter-Regular.ttf", "Inter-Regular.ttf")
        .AddFile("Inter-Medium.ttf", "Inter-Medium.ttf")
        .AddFile("Inter-Bold.ttf", "Inter-Bold.ttf")
        .AddFile("SpaceMono-Regular.ttf", "SpaceMono-Regular.ttf")
        .AddFile("logo.svg", "logo.svg")
				.AddFile("ribbon.svg", "ribbon.svg")
        .AddParameter("instructions", new JsonObject
        {
          ["parts"] = new JsonArray
          {
            new JsonObject
            {
              ["html"] = "index.html",
              ["assets"] = new JsonArray
              {
                "style.css",
                "Inter-Regular.ttf",
                "Inter-Medium.ttf",
                "Inter-Bold.ttf",
                "SpaceMono-Regular.ttf",
                "logo.svg",
					 "ribbon.svg"
              }
            }
          }
        }
		.ToString());
	 }
  }
}

After making a successful request, save the response to a file. Then, stream the response to a file using AdvancedResponseWriter on your request:

request.AdvancedResponseWriter = (responseStream, response) =>
{
	if (response.StatusCode == HttpStatusCode.OK)
   {
      using (responseStream)
      {
         using var outputFileWriter = File.OpenWrite("result.pdf");
         responseStream.CopyTo(outputFileWriter);
      }
   }
   else
   {
      var responseStreamReader = new StreamReader(responseStream);
      Console.Write(responseStreamReader.ReadToEnd());
   }
};

Executing the Request

All that’s left is to execute your request:

var response = client.Execute(request);

This will save the resulting PDF in the root directory of the project as result.pdf.

To generate the PDF, go to your terminal and run:

dotnet run

You can see the full code below:

// Program.cs

using System;
using System.IO;
using System.Net;
using RestSharp;

namespace PspdfkitApiDemo
{
	class Program
	{
		static void Main(string[] args)
		{
			var client = new RestClient("https://api.pspdfkit.com/build");

			var request = new RestRequest(Method.POST)
			  .AddHeader("Authorization", "Bearer {YOUR_API_KEY}") // Replace {YOUR_API_KEY} with your API key.
			  .AddFile("index.html", "index.html")
			  .AddFile("style.css", "style.css")
			  .AddFile("Inter-Regular.ttf", "Inter-Regular.ttf")
			  .AddFile("Inter-Medium.ttf", "Inter-Medium.ttf")
			  .AddFile("Inter-Bold.ttf", "Inter-Bold.ttf")
			  .AddFile("SpaceMono-Regular.ttf", "SpaceMono-Regular.ttf")
			  .AddFile("logo.svg", "logo.svg")
				.AddFile("ribbon.svg", "ribbon.svg")
			  .AddParameter("instructions", new JsonObject
			  {
				  ["parts"] = new JsonArray
				{
			new JsonObject
			{
			  ["html"] = "index.html",
			  ["assets"] = new JsonArray
			  {
				"style.css",
				"Inter-Regular.ttf",
				"Inter-Medium.ttf",
				"Inter-Bold.ttf",
				"SpaceMono-Regular.ttf",
				"logo.svg",
				"ribbon.svg"
			  }
			}
				}
			  }.ToString());

			request.AdvancedResponseWriter = (responseStream, response) =>
			{
				if (response.StatusCode == HttpStatusCode.OK)
				{
					using (responseStream)
					{
						using var outputFileWriter = File.OpenWrite("result.pdf");
						responseStream.CopyTo(outputFileWriter);
					}
				}
				else
				{
					var responseStreamReader = new StreamReader(responseStream);
					Console.Write(responseStreamReader.ReadToEnd());
				}
			};

			client.Execute(request);
		}
	}
}

Conclusion

In this post, you generated a PDF certificate from an HTML template using our C# PDF generation API. We created similar PDF certificate generation blog posts using sample code from other programming languages:

In addition to templates for generating certificates, we created free templates for other commonly used documents, like receipts, invoices, and reports. If you’re interested in generating other types of documents in C#, check out the following posts:

All our templates are available for you to download on our PDF Generator API page. Feel free to customize or add any CSS to the template to fit your use case or help reflect your company’s brand.

Related Products
Share Post
Free 60-Day Trial Try PSPDFKit in your app today.
Free Trial

Related Articles

Explore more
TUTORIALS  |  API • Python • How To • Tesseract • OCR

How to Use Tesseract OCR in Python

TUTORIALS  |  API • Tips

How to Convert Scanned PDF to Text with PSPDFKit's OCR API

PRODUCTS  |  API • Releases • Components

PSPDFKit API OCR and Office Conversion Improvements