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/dynamicpdf-api-samples/converting-html-pdf-endpoint
and download the resources.
You should have two files:
instructions.json
, andproducts.html
.
Obtaining API Key
Obtain an API key from Apps and API Keys in the Portal.
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.
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.dpdf.io/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.
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.
Language | File Name | Location (package/namespace/etc.) | GitHub Project |
---|---|---|---|
Java | PdfHtmlExample.java | com.dynamicpdf.api.examples | https://github.com/dynamicpdf-api/java-client-examples |
C# | Program.cs | PdfHtmlExample | https://github.com/dynamicpdf-api/dotnet-client-examples |
Nodejs | PdfHtmlExample.js | nodejs-client-examples | https://github.com/dynamicpdf-api/nodejs-client-examples |
Go | pdf-html-example.go | go-client-examples | https://github.com/dynamicpdf-api/go-client-examples |
PHP | PdfHtmlExample.php | php-client-examples | https://github.com/dynamicpdf-api/php-client-examples |
Python | PdfHtmlExample.py | python-client-examples | https://github.com/dynamicpdf-api/python-client-examples |
Click on the language tab of choice to view the tutorial steps for the particular language.
- C# (.NET)
- Java
- Node.js
- PHP
- Go
- Python
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--api-key--";
string savePath = "c:/temp/dynamicpdf-api-samples/converting-html-pdf-endpoint/html-output.pdf";
string resourcePath = "c:/temp/dynamicpdf-api-samples/converting-html-pdf-endpoint/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/dynamicpdf-api-samples/converting-html-pdf-endpoint/products.html"));
pdf.AddHtml(resource);
PdfResponse pdfResponse = pdf.Process();
System.IO.File.WriteAllBytes(savePath, pdfResponse.Content);
}
}
}
Available on NPM:
npm i @dynamicpdf/api
- Use npm to install the DynamicPDF API module.
- Create a new class named
PdfHtmlExample
. - Create a static
Run
method. - Add the following code to the
Run
method.
import fs from 'fs';
import {
Pdf,
PageSize,
Orientation,
HtmlResource
} from "@dynamicpdf/api"
export class PdfHtmlExample {
static async Run() {
var savePath = "c:/temp/dynamicpdf-api-samples/converting-html-pdf-endpoint/html-output.pdf";
var apiKey = "DP.xxx-api-key-xxx";
var pdf = new Pdf();
pdf.apiKey = apiKey;
//var resource = new HtmlResource("<html>hello</html>");
pdf.addHtml("<html>hello</html>", null,
PageSize.LETTER, Orientation.PORTRAIT, 1);
pdf.addHtml(new HtmlResource("<html><p>HTML with basePath.</p><img src='./images/logo.png'></img></html>"),
"https://www.dynamicpdf.com", PageSize.LETTER, Orientation.PORTRAIT, 1);
var resourcePath = "c:/temp/dynamicpdf-api-samples/converting-html-pdf-endpoint/products.html";
pdf.addHtml(new HtmlResource(resourcePath), null, PageSize.LETTER, Orientation.PORTRAIT, 1);
var res = await pdf.process();
if (res.isSuccessful) {
var outStream = fs.createWriteStream(savePath);
outStream.write(res.content);
outStream.close();
}
}
}
await PdfHtmlExample.Run();
- Run the application
node PdfHtmlExample.js
and the PDF is created.
Available on Maven:
https://search.maven.org/search?q=g:com.dynamicpdf.api
<dependency>
<groupId>com.dynamicpdf.api</groupId>
<artifactId>dynamicpdf-api</artifactId>
<version>1.1.1</version>
</dependency>
- Create a new Maven project and add the DynamicPDF API as a dependency.
- Create a new Maven project and add the DynamicPDF API as a dependency, also add the Apache Commons IO library.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
- Create a new class named
PdHtmlExample
with amain
method. - Create a new method named
Run
. - Add the following code to the
Run
method.
package com.dynamicpdf.api.examples;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
import com.dynamicpdf.api.HtmlResource;
import com.dynamicpdf.api.PageOrientation;
import com.dynamicpdf.api.PageSize;
import com.dynamicpdf.api.Pdf;
import com.dynamicpdf.api.PdfResponse;
public class PdfHtmlExample {
public static void Run(String apiKey, String savePath, String resourcePath) {
Pdf pdf = new Pdf();
try {
pdf.setApiKey(apiKey);
// add simple HTML string
pdf.AddHtml("<html>An example HTML fragment.</html>", null, PageSize.LETTER, PageOrientation.PORTRAIT, 1F);
// 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", PageSize.LETTER, PageOrientation.PORTRAIT, 1F);
// add html from a path on local drive
String temp = Files.readString(Paths.get(resourcePath));
HtmlResource resource = new HtmlResource(temp);
pdf.AddHtml(resource, null, PageSize.LETTER, PageOrientation.PORTRAIT, 1F);
PdfResponse pdfResponse = pdf.process();
FileUtils.writeByteArrayToFile(new File(savePath), pdfResponse.getContent());
} catch (IOException e) {
e.printStackTrace();
}
}
public 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/dynamicpdf-api-samples/converting-html-pdf-endpoint/products.html";
PdfHtmlExample.Run(key, savePath, resourcePath);
}
}
Available as a Composer package:
composer require dynamicpdf/api
- Use composer to ensure you have the required PHP libraries.
- Create a new class named
PdfHtmlExample
. - Add a
Run
method. - Add the following code to the
Run
method. - Run the application `php PdfHtmlExample.php'.
use DynamicPDF\Api\PdfResource;
use DynamicPDF\Api\Pdf;
use DynamicPDF\Api\HtmlResource;
include_once("constants.php");
require __DIR__ . '/vendor/autoload.php';
class PdfHtmlExample {
public static function Run(string $apikey, string $path, string $output_path) {
$pdf = new Pdf();
$pdf->ApiKey = $apikey;
$pdf->AddHtml("<html><p>This is a test.</p></html>");
$filePath = Utility::GetFileData($path . "HtmlWithAllTags.html");
$resource = new HtmlResource($filePath);
$pdf->AddHtml($resource);
$pdf->AddHtml("<html><img src='./images/logo.png'></img></html>", "https://www.dynamicpdf.com");
//call the pdf endpoint and return response
$response = $pdf->Process();
//if response is successful the save the PDF returned from endpoint
if($response->IsSuccessful)
{
file_put_contents($output_path . "html-php-output.pdf", $response->Content);
} else {
echo($response->ErrorJson);
}
}
}
PdfHtmlExample::Run(CLIENT_EXAMPLES_API_KEY, CLIENT_EXAMPLES_BASE_PATH . "users-guide/", CLIENT_EXAMPLES_OUTPUT_PATH);
Available as a GO package: https://pkg.go.dev/github.com/dynamicpdf-api/go-client
- Ensure you have the required GO libraries.
- Create a new file named
pdf-html-example.go
. - Add a
main
method. - Add the following code to the
main
method. - Run the application
go run pdf-html-example.go
.
package main
import (
"fmt"
"os"
"github.com/dynamicpdf-api/go-client/endpoint"
"github.com/dynamicpdf-api/go-client/input"
)
func main() {
pdfExample := endpoint.NewPdf()
pdfExample.Endpoint.BaseUrl = "https://api.dpdf.io/"
pdfExample.Endpoint.ApiKey = "DP.xxx-api-key-xxx"
inputOne := input.NewHtmlInputWithString("<html>An example HTML fragment.</html>")
inputTwo := input.NewHtmlInputWithString("<html><p>HTML with basePath.</p><img src='./images/logo.png'></html>")
inputTwo.SetBasePath("https://www.dynamicpdf.com")
pdfExample.Inputs = append(pdfExample.Inputs, inputOne)
pdfExample.Inputs = append(pdfExample.Inputs, inputTwo)
resp := pdfExample.Process()
res := <-resp
if res.IsSuccessful() == true {
os.WriteFile("C:/temp/dynamicpdf-api-samples/converting-html-pdf-endpoint/pdf-html-example-output.pdf",
res.Content().Bytes(), os.ModeType)
}else {
fmt.Print(res.ErrorJson())
}
}
Available at: pip install dynamicpdf-api
- Ensure you have the required Python libraries.
- Create a new file named
PdfHtmlExample.py
. - Add a
main
method. - Add the following code to the
main
method. - Run the application
python PdfHtmlExample.py
.
from dynamicpdf_api.pdf import Pdf
from dynamicpdf_api.html_resource import HtmlResource
def merge_pdfs(apiKey):
pdf=Pdf()
pdf.api_key=apiKey
pdf.add_html("<html><p>This is a test.</p></html>")
pdf.add_html(HtmlResource("html.html", "rb"))
pdf.add_html("<html><img src='./images/logo.png'></img></html>", "https://www.dynamicpdf.com")
response = pdf.process()
with open("Outputs/html-output-csharp.pdf", "wb") as output_file:
output_file.write(response.content)
# Call the function
api_key = 'DP.xxx-api-key-xxx'
merge_pdfs(api_key)
In all six examples, we added an HTML string, an HTML string where the image is located on the DynamicPDF website and so it specifies the basePath
, and then an HTML document from a file. The three HTML documents were converted into PDFs and merged into one combined PDF.