Skip to main content

Convert HTML to PDF


Convert HTML to PDF documents using the `pdf` endpoint.

Converting HTML into a PDF requires using the pdf endpoint. The pdf endpoint uses an instructions JSON document you send to the endpoint. The endpoint then processes the instructions to create the resultant PDF. You must create an instructions document when you call the pdf endpoint directly. When you use one of the DynamicPDF client libraries, then the client library hides the complexities of creating the instructions document from you.

In this tutorial, we create a PDF document using the pdf endpoint with the html input type, using a string containing HTML, an HTML string that includes a relative base path, and an HTML document. First, we call the pdf endpoint directly using cURL. We then use the C#, Java, Node.js, PHP, Go, and Python client libraries.

Required Resources

  • Before beginning, add the Convert HTML to PDF sample to your DynamicPdf API samples folder.

Figure 1. Adding the Convert HTML to PDF sample project to samples.

  • Create a local directory c:/temp/html-to-pdf and download the resources.

You should have two files:

  • instructions.json, and
  • products.html.

Obtaining API Key

Obtain an API key from Apps and API Keys in the Portal.

tip

If you are not familiar with the File Manager or Apps and API Keys, refer to the following tutorial and relevant Users Guide pages.

Calling API Directly Using cURL

Let's call the endpoint directly using an instructions document and cURL. We start by creating an instructions document.

Instructions Document

Create the following instructions document using a text-editor of your choice.

{
"inputs": [
{
"type": "html",
"htmlString": "<html>An example HTML fragment.</html>"
},
{
"type": "html",
"basePath": "https://www.dynamicpdf.com",
"htmlString": "<html>,<p>HTML with basePath.</p><img src='./images/logo.png'></img></html>"
},
{
"type": "html",
"resourceName":"products.html"
}
]
}

The instructions.json document specifies the first input as an HTML string. The second input, also a string, prepends a basePath to any relative paths (in this example, the relative image's path). The final input takes a file on our local filesystem. But only the resource's file name is specified, as the POST command loads the actual resource.

cURL Command

After creating the instructions document, we can use cURL to call the pdf endpoint directly.

info

The pdf endpoint is an HTML form POST submission. Although we use file paths to load the instructions document and the HTML resource, realize that you could load the resources from anywhere, provided they are translated into binary for the form submission. For example: the following C# code snippet illustrates. Note that the "file" is paramFileBytes, a byte array. Of course, one of DynamicPdf API client libraries simplify sending binary data using the pdf endpoint.

private async Task<System.IO.Stream> Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
HttpContent stringContent = new StringContent(paramString);
HttpContent fileStreamContent = new StreamContent(paramFileStream);
HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(stringContent, "param1", "param1");
formData.Add(fileStreamContent, "file1", "file1");
formData.Add(bytesContent, "file2", "file2");
var response = await client.PostAsync(actionUrl, formData);
if (!response.IsSuccessStatusCode)
{
return null;
}
return await response.Content.ReadAsStreamAsync();
}
}
  • Replace the API key below with your own key, ensuring the line is -H "Authorization:Bearer <your-key>".
  • Specify the location of the instructions.json document on your local filesystem.
  • Specify the location of the products.html document on your local filesystem.
  • Finally, specify the output document returned from the pdf endpoint.
curl https://api.dynamicpdf.com/v1.0/pdf 
-H "Authorization:Bearer DP.xxx-api-key-xxx"
-F "Instructions=@C:/temp/dynamicpdf-api-samples/converting-html-pdf-endpoint/instructions.json"
-F "Resource=@C:/temp/dynamicpdf-api-samples/converting-html-pdf-endpoint/products.html"
-o html-output.pdf
  • Execute the command and the following document is returned to the command-line as a JSON document.
info

If you attempt to open the PDF and you receive an error, then open the PDF in a text editor to view the JSON error.

::::

Figure 2. Downloading PDF using cURL from command-line.

  • Open to review the created PDF.

Figure 3. The created PDF from the instructions.json.

See Sample Resources for instructions on adding sample resources.

:::

Calling Endpoint Using Client Library

To simplify development, you can also use one of the DynamicPDF API client libraries. Use the client library of your choice to complete this tutorial section.

Complete Source

You can access the complete source for this project at one of the following GitHub projects.

LanguageFile NameLocation (package/namespace/etc.)GitHub Project
JavaPdfHtmlExample.javacom.dynamicpdf.api.exampleshttps://github.com/dynamicpdf-api/java-client-examples
C#Program.csPdfHtmlExamplehttps://github.com/dynamicpdf-api/dotnet-client-examples
NodejsPdfHtmlExample.jsnodejs-client-exampleshttps://github.com/dynamicpdf-api/nodejs-client-examples
Gopdf-html-example.gogo-client-exampleshttps://github.com/dynamicpdf-api/go-client-examples
PHPPdfHtmlExample.phpphp-client-exampleshttps://github.com/dynamicpdf-api/php-client-examples
PythonPdfHtmlExample.pypython-client-exampleshttps://github.com/dynamicpdf-api/python-client-examples
tip

Click on the language tab of choice to view the tutorial steps for the particular language.

Available on NuGet:

Install-Package DynamicPDF.API
  • Create a new Console App (.NET Core) project named PdfHtmlExample.
  • Add the DynamicPDF.API NuGet package.
  • Create a new Pdf instance and assign the api key.
  • Create a new static method named Run.
  • Add the following code to the Run method.
  • Run the application and the PDF is created.
using System;
using DynamicPDF.Api;

namespace PdfHtmlExample
{
class Program
{
static void Main(string[] args)
{
string key = "DP.xxx-api-key-xxx";
string savePath = "c:/temp/html-to-pdf/html-output.pdf";
string resourcePath = "c:/temp/html-to-pdf/products.html";
Program.Run(key, savePath, resourcePath);
}

public static void Run(string apiKey, string savePath, string resourcePath)
{
Pdf pdf = new Pdf();
pdf.ApiKey = apiKey;

// add simple HTML string

pdf.AddHtml("<html>An example HTML fragment.</html>");

// use basepath in an HTML string

pdf.AddHtml("<html><p>HTML with basePath.</p><img src='./images/logo.png'></img></html>", "https://www.dynamicpdf.com");

// add html from a path on local drive

HtmlResource resource = new HtmlResource(System.IO.File.ReadAllText(@"c:/temp/html-to-pdf/products.html"));
pdf.AddHtml(resource);
PdfResponse pdfResponse = pdf.Process();
System.IO.File.WriteAllBytes(savePath, pdfResponse.Content);
}
}
}
   Follow us on social media for latest news!