How to convert HMTL to PDF in C# (ASP.NET, Azure Websites etc)

It is quite easy to utilize HTML to PDF API in your .NET applications.

Prerequisites

Obtain your access token

Please visit tokens page and copy your access token. We will refer to the token as TOKEN in this guide.

Usage

Convert a URL to PDF and save to disk

This snippet uses HTML to PDF API to generate a PDF and stream back the resulting file. After receiving the response, we write the file to out.pdf in this sample but it’s up to you to use it as you wish.

public void Capture()
{
  using (var client = new WebClient())
  {
    NameValueCollection qs = new NameValueCollection();
    qs.Add("access_token", "TOKEN");
    qs.Add("url", "http://google.com");

    client.QueryString = qs;

    // Create the PDF and stream it to out.pdf
    client.DownloadFile("https://restpack.io/api/html2pdf/v4/convert", "out.pdf")
  }
}

Convert an HTML string to PDF

Here, instead of sending a url querystring parameter, we are POSTing a json document with html_data string. It can contain complex html, css, inline JS etc.

public void Capture()
{
  using (var client = new WebClient())
  {
    NameValueCollection qs = new NameValueCollection();
    qs.Add("access_token", "TOKEN");
    client.QueryString = qs;

    NameValueCollection body = new NameValueCollection();
    body.Add("html_data", "<strong>Bold text here</strong> and regular here..");

    // Create the PDF and stream it to a buffer
    MemoryStream ms = new MemoryStream(client.UploadValues("https://restpack.io/api/html2pdf/v4/convert", body))

    // Use ms
  }
}

For detailed usage instructions, please check the Documentation page.