HTML to PDF API for .NET

This is the documentation of the .NET client library for the Pdfcrowd HTML to PDF API. Here are some sample PDFs generated by the API:

Status report JavaScript vector chart Wikipedia page Invoice Newsletter

Installation

Integration with your application is a matter of a few minutes:

  1. Sign up and obtain your username and API key.
  2. Download the client library: pdfcrowd-2.7-dotnet.zip
  3. Unpack the downloaded .zip file and add a reference to bin/pdfcrowd.dll to your project.

Getting Started

In the following examples, do not forget to replace "username" and "apikey" with your username and API key.

HTML to PDF C# Example Application

The following code shows how to convert a web page, raw HTML code, and a local HTML file:

using System;
using System.IO;

public class PdfcrowdTest
{
  static void Main() {
    try 
    {
      FileStream fileStream;  

      // create an API client instance
      pdfcrowd.Client client = new pdfcrowd.Client("username", "apikey");

      // convert a web page and save the PDF to a file
      fileStream = new FileStream("google_com.pdf", FileMode.CreateNew);
      client.convertURI("http://www.google.com", fileStream);
      fileStream.Close();

      // convert an HTML string and store the PDF into a memory stream
      MemoryStream memStream = new MemoryStream();
      string html = "<head></head><body>My HTML Layout</body>";
      client.convertHtml(html, memStream);

      // convert an HTML file
      fileStream = new FileStream("file.pdf", FileMode.CreateNew);
      client.convertFile("c:/local/file.html", fileStream);
      fileStream.Close();

      // retrieve the number of tokens in your account
      int ntokens = client.numTokens();
    }
    catch(pdfcrowd.Error why) {
      System.Console.WriteLine(why.ToString());
    }
  }
}

HTML to PDF in ASP.NET - C#

The following code converts a web page using C# ASP.NET and sends the generated PDF as an HTTP response:

<%-- file: PdfGenerator.aspx --%>
<%@ Page Language="C#" CodeFile="PdfGenerator.aspx.cs" Inherits="Website.PdfGenerator"
         AutoEventWireup="true" %>
// file: PdfGenerator.aspx.cs
using System;
using System.IO;

namespace Website
{
  public partial class PdfGenerator : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
      try
      {
          // create an API client instance
          pdfcrowd.Client client = new pdfcrowd.Client("username", "apikey");

          // convert a web page and write the generated PDF to a memory stream
          MemoryStream Stream = new MemoryStream();
          client.convertURI("http://www.google.com", Stream);

          // set HTTP response headers
          Response.Clear();
          Response.AddHeader("Content-Type", "application/pdf");
          Response.AddHeader("Cache-Control", "max-age=0");
          Response.AddHeader("Accept-Ranges", "none");
          Response.AddHeader("Content-Disposition", "attachment; filename=google_com.pdf");

          // send the generated PDF
          Stream.WriteTo(Response.OutputStream);
          Stream.Close();
          Response.Flush();
          Response.End();
      }
      catch(pdfcrowd.Error why)
      {
          Response.Write(why.ToString());
      }
    }
  }
}

You can also convert raw HTML code, just use the convertHtml() method instead of convertURI():

    client.convertHtml("<head></head><body>My HTML Layout</body>", Stream);

The API lets you also convert a local HTML file:

    client.convertFile("c:/MyLayout.html", Stream);

HTML to PDF in ASP.NET - Visual Basic

The following code converts a web page using Visual Basic ASP.NET and sends the generated PDF as an HTTP response:

<%-- file: PdfGenerator.aspx --%>
<%@ Page Language="VB" CodeFile="PdfGenerator.aspx.vb" Inherits="Website.PdfGenerator"
         AutoEventWireup="true" %>
' file: PdfGenerator.aspx.vb
Imports System
Imports System.IO

Namespace Website
  Public Partial Class PdfGenerator
      Inherits System.Web.UI.Page
      Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        Dim Response As System.Web.HttpResponse = System.Web.HttpContext.Current.Response
        Try
            ' create an API client instance
            Dim client As New pdfcrowd.Client("username", "apikey")

            ' convert a web page and write the generated PDF to a memory stream
            Dim Stream As New MemoryStream
            client.convertURI("http://www.google.com", Stream)

            ' set HTTP response headers
            Response.Clear() 
            Response.AddHeader("Content-Type", "application/pdf")
            Response.AddHeader("Cache-Control", "max-age=0")
            Response.AddHeader("Accept-Ranges", "none")
            Response.AddHeader("Content-Disposition", "attachment; filename=google_com.pdf") 

            ' send the generated PDF
            Stream.WriteTo(Response.OutputStream)
            Stream.Close()
            Response.Flush() 
            Response.End()
        Catch why As pdfcrowd.Error
            Response.Write(why.ToString())
        End Try
      End Sub
  End Class
End Namespace

You can also convert raw HTML code, just use the convertHtml() method instead of convertURI():

    client.convertHtml("<head></head><body>My HTML Layout</body>", Stream)

The API lets you also convert a local HTML file:

    client.convertFile("c:/MyLayout.html", Stream)

Error Handling

C#

try {
    // ..
    // call the API
} catch(pdfcrowd.Error why) {
    // why.ToString() returns an error message
}

Visual Basic

Try
    ' ...
    ' call the API
Catch why As pdfcrowd.Error
    ' why.ToString() returns an error message
End Try

API Reference

class pdfcrowd.Client (view source)

Provides access to the Pdfcrowd API from your .NET applications.

Constructor

public Client(string username, string apikey)
Arguments are your username at Pdfcrowd and apikey which can be found in your account.

Conversion

public void convertHtml(string html, System.IO.Stream outstream)
Converts the html string to PDF and writes the result to outstream.
public void convertFile(string fpath, System.IO.Stream outstream)
Converts a local file fpath to PDF and writes the result to outstream. The file can be either an HTML document or a .zip, .tar.gz., or .tar.bz2 archive which can contain external resources such as images, stylesheets, etc.
public void convertURI(string url, System.IO.Stream outstream)
Converts a web page at url to PDF and writes the result to outstream.

Page Setup

public void setPageWidth(double/string value)
Sets PDF page width in units.
public void setPageHeight(double/string value)
Sets PDF page height in units. Use -1 for a single page PDF.
public void setPageMargins(string top, string right, string bottom, string left)
Sets PDF page margins in units.
public void setHorizontalMargin(double/string value)
Deprecated. Use setPageMargins instead.
public void setVerticalMargin(double/string value)
Deprecated. Use setPageMargins instead.

Header and Footer

public void setFooterHtml(string html)
Places the specified html code inside the page footer. The following variables are expanded:
  • %u - URL to convert.
  • %p - The current page number.
  • %n - Total number of pages.
public void setFooterUrl(string url)
Loads HTML code from the specified url and places it inside the page footer. See setFooterHtml for the list of variables that are expanded.
public void setHeaderHtml(string html)
Places the specified html code inside the page header. See setFooterHtml for the list of variables that are expanded.
public void setHeaderUrl(string url)
Loads HTML code from the specified url and places it inside the page header. See setFooterHtml for the list of variables that are expanded.
public void setHeaderFooterPageExcludeList(string exclist)
exclist is a comma seperated list of physical page numbers on which the header a footer are not printed. Negative numbers count backwards from the last page: -1 is the last page, -2 is the last but one page, and so on.
Example: "1,-1" will not print the header and footer on the first and the last page.
public void setPageNumberingOffset(int offset)
An offset between physical and logical page numbers. The default value is 0.
Example: if set to "1" then the page numbering will start with 1 on the second page.

HTML options

public void enableImages(bool value)
Set value to false to disable printing images to the PDF. The default is true
public void enableBackgrounds(bool value)
Set value to false to disable printing backgrounds to the PDF. The default is true
public void setHtmlZoom(float value)
Set HTML zoom in percents. It determines the precision used for rendering of the HTML content. Despite its name, it does not zoom the HTML content. Higher values can improve glyph positioning and can lead to overall better visual appearance of generated PDF .The default value is 200. See also setPdfScalingFactor().
public void enableJavaScript(bool value)
Set value to false to disable JavaScript in web pages. The default is true.
public void enableHyperlinks(bool value)
Set value to false to disable hyperlinks in the PDF. The default is true.
public void setDefaultTextEncoding(string value)
value is the text encoding used when none is specified in a web page. The default is utf-8.
public void usePrintMedia(bool value)
If value is true then the print CSS media type is used (if available).

PDF options

public void setEncrypted(bool value)
If value is set to true then the PDF is encrypted. This prevents search engines from indexing the document. The default is false.
public void setUserPassword(string pwd)
Protects the PDF with a user password. When a PDF has a user password, it must be supplied in order to view the document and to perform operations allowed by the access permissions. At most 32 characters.
public void setOwnerPassword(string pwd)
Protects the PDF with an owner password. Supplying an owner password grants unlimited access to the PDF including changing the passwords and access permissions. At most 32 characters.
public void setNoPrint(bool value)
Set value to true disables printing the generated PDF. The default is false.
public void setNoModify(bool value)
Set value to true to disable modifying the PDF. The default is false.
public void setNoCopy(bool value)
Set value to true to disable extracting text and graphics from the PDF. The default is false.
public void setPageLayout(int value)
Specifies the initial page layout when the PDF is opened in a viewer.
  • SINGLE_PAGE
  • CONTINUOUS
  • CONTINUOUS_FACING
public void setPageMode(int value)
Specifies the appearance of the PDF when opened.
  • FULLSCREEN - Full-screen mode.
public void setInitialPdfZoomType(int value)
value specifies the appearance of the PDF when opened.
  • FIT_WIDTH
  • FIT_HEIGHT
  • FIT_PAGE
public void setInitialPdfExactZoom(float value)
value specifies the initial page zoom of the PDF when opened.
public void setPdfScalingFactor(float value)
The scaling factor used to convert between HTML and PDF. The default value is 1.0.
public void setPageBackgroundColor(string value)
The page background color in RRGGBB hexadecimal format.
public void setTransparentBackground(bool value)
Does not print the body background. Requires the following CSS rule to be declared:
body {background-color:rgba(255,255,255,0.0);}
public void setAuthor(string author)
Sets the author field in the created PDF.

Watermark

public void setWatermark(string url, string offset_x, string offset_y)
url is a public absolute URL of the watermark image (must start either with http:// or https://). The supported formats are PNG and JPEG. offset_x and offset_y is the watermark offset in units. The default offset is (0,0).
public void setWatermarkRotation(double angle)
Rotates the watermark by angle degrees.
public void setWatermarkInBackground(bool value)
When value is set to true then the watermark is be placed in the background. By default, the watermark is placed in the foreground.

Miscellaneous

public void useSSL(bool use_ssl)
Set to true to call the API over a secure connection. The default is false.
public int numTokens()
Returns the number of available conversion tokens in your account.
public void setMaxPages(int npages)
Prints at most npages pages.
public void setFailOnNon200(bool value)
If value is true then the conversion will fail when the source URI returns 4xx or 5xx HTTP status code. The default is false.

class pdfcrowd.Error

Derived from System.Exception. It is thrown when an error occurs. Use ToString() method to get the error message.

Units

Page dimensions and margins can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt). If no units are specified, points are assumed. Examples: "210mm", "8.5in".