POST /v1/pdf/convert/from/html
This API converts a RAW HTML code into a PDF document and process any JavaScript which the webpage triggers when it loads. For example if the the webpage triggers a JavaScript popup window then that will be included in the conversion process. There is no option to disable JavaScript on the supplied RAW HTML code.
Attributes
Attributes are case-sensitive and should be inside JSON for POST request. for example: { "url": "https://example.com/file1.pdf" }
Remember to ensure that request sizes are less than
4 mb in file size. For more information, see
Request Size Limits.
| Attribute | Type | Required | Default | Description |
html | string | Yes | - | Input HTML code to be converted. To convert the link to a PDF use the /pdf/convert/from/url endpoint instead. |
margins | string | No | - | Set custom margins, overriding CSS default margins. Specify the margins in the format {top} {right} {bottom} {left}. You can usepx,mm,cmorinunits. Also, you can set margins for all sides at once using a single value. |
paperSize | string | No | A4 | Specifies the paper size. Accepts standard sizes like ‘Letter’, ‘Legal’, ‘Tabloid’, ‘Ledger’, ‘A0’–‘A6’. You can also set a custom size by providing width and height separated by a space, with optional units: px (pixels), mm (millimeters), cm (centimeters), or in (inches). Examples: ‘200 300’, ‘200px 300px’, ‘200mm 300mm’, ‘20cm 30cm’, ‘6in 8in’. |
orientation | string | No | Portrait | Sets the document orientation. Options: Portrait for vertical layout, and Landscape for horizontal layout. |
printBackground | boolean | No | true | Set to false to disable background colors and images are included when generating PDFs from HTML/URL |
mediaType | string | No | print | Controls how content is rendered when converting to PDF. Options: print (uses print styles), screen (uses screen styles), none (no media type applied). |
DoNotWaitFullLoad | boolean | No | false | Controls how thoroughly the converter waits for a page to load before converting HTML to PDF --- false waits for full page load, while true speeds up conversion by waiting only for minimal loading. |
header | string | No | - | Set this to can add user definable HTML for the header to be applied on every page header. The format is html. |
footer | string | No | - | Set this to can add user definable HTML for the footer to be applied on every page bottom. The format is html. |
async | boolean | No | false | Set async to true for long processes to run in the background, API will then return a jobId which you can use with the Background Job Check endpoint. Also see Webhooks & Callbacks |
callback | string | No | - | The callback URL (or Webhook) used to receive the POST data. see Webhooks & Callbacks. This is only applicable when async is set to true. |
name | string | No | - | File name for the generated output, the input must be in string format. |
expiration | integer | No | 60 | Set the expiration time for the output link in minutes. After this specified duration, any generated output file(s) will be automatically deleted from PDF.co Temporary Files Storage. The maximum duration for link expiration varies based on your current subscription plan. To store permanent input files (e.g. re-usable images, pdf templates, documents) consider using PDF.co Built-In Files Storage. |
profiles | object | No | - | See Profiles for more information. |
outputDataFormat | string | No | - | If you require your output as base64 format, set this to base64 |
DataEncryptionAlgorithm | string | No | - | Controls the encryption algorithm used for data encryption. See User-Controlled Encryption for more information. The available algorithms are: AES128, AES192, AES256. |
DataEncryptionKey | string | No | - | Controls the encryption key used for data encryption. See User-Controlled Encryption for more information. |
DataEncryptionIV | string | No | - | Controls the encryption IV used for data encryption. See User-Controlled Encryption for more information. |
DataDecryptionAlgorithm | string | No | - | Controls the decryption algorithm used for data decryption. See User-Controlled Encryption for more information. The available algorithms are: AES128, AES192, AES256. |
DataDecryptionKey | string | No | - | Controls the decryption key used for data decryption. See User-Controlled Encryption for more information. |
DataDecryptionIV | string | No | - | Controls the decryption IV used for data decryption. See User-Controlled Encryption for more information. |
The header and footer parameters can contain valid HTML markup with the following classes used to inject printing values into them:
date: formatted print date
title: document title
url: document location
pageNumber: current page number
totalPages: total pages in the document
img: tag is supported in both the header and footer parameter, provided that the src attribute is specified as a base64-encoded string.
For example, the following markup will generate Page N of NN page numbering:
<span style='font-size:10px'>Page <span class='pageNumber'></span> of <span class='totalPages'></span>.</span>
An example with an advanced header and footer. Note that the top and bottom page margins are important because page content may overlap the footer or header.
{
"html": "<!DOCTYPE html><html><head><meta charSet=\"utf-8\"/><style type=\"text/css\">body { font-family: \"Arial\" }</style></head><body><h1>Hello</h1></body></html>",
"async": false,
"name": "result.pdf",
"margins": "40px 5px 40px 5px",
"paperSize": "Letter",
"orientation": "Portrait",
"printBackground": true,
"header": "<div style='width:100%'><span style='font-size:10px;margin-left:20px;width:50%;float:left'>LEFT SUBHEADER</span><span style='font-size:8px;width:30%;float:right'>RIGHT SUBHEADER</span></div>",
"footer": "<div style='width:100%;text-align:right'><span style='font-size:10px;margin-right:20px'>Page <span class='pageNumber'></span> of <span class='totalPages'></span>.</span></div>"
}
If you use JSON as input then make sure to escape it first (with JSON.stringify(dataObject) in JS). Escaping is when every " is replaced with \". Example with " be escaped as \" then: "templateData": "{ \"paid\": true, \"invoice_id\": \"0002\", \"total\": \"$999.99\" }".
Query parameters
No query parameters accepted.
Responses
| Parameter | Type | Description |
url | string | Direct URL to the final PDF file stored in S3. |
outputLinkValidTill | string | Timestamp indicating when the output link will expire |
pageCount | integer | Number of pages in the PDF document. |
error | boolean | Indicates whether an error occurred (false means success) |
status | string | Status code of the request (200, 404, 500, etc.). For more information, see Response Codes. |
name | string | Name of the output file |
credits | integer | Number of credits consumed by the request |
remainingCredits | integer | Number of credits remaining in the account |
duration | integer | Time taken for the operation in milliseconds |
Example Payload
{
"html": "<h1>Hello World!</h1><a href='https://pdf.co'>Go to PDF.co</a>",
"name": "result.pdf",
"margins": "5px 5px 5px 5px",
"paperSize": "Letter",
"orientation": "Portrait",
"printBackground": true,
"header": "",
"footer": "",
"mediaType": "print",
"async": false
}
Example Response
To see the main response codes, please refer to the
Response Codes page.
{
"url": "https://pdf-temp-files.s3.amazonaws.com/97dc323f32794eae8fa6602f5bd981c1/result.pdf",
"pageCount": 1,
"error": false,
"status": 200,
"name": "result.pdf",
"remainingCredits": 60646
}
Inconsistent URL Encoding in cURL Output: When using cURL to make API requests, the output JSON may show URL characters encoded as Unicode escape sequences. For example, the ampersand character (&) may appear as \u0026 in the cURL output. This is normal JSON encoding behavior and does not affect the validity of the URL. The URL will function correctly when used, as JSON parsers automatically decode these escape sequences. If you’re parsing the response programmatically, your JSON parser will handle this conversion automatically.
Code Samples
CURL
JavaScript/Node.js
Python
C#
Java
PHP
curl --location --request POST 'https://api.pdf.co/v1/pdf/convert/from/html' \
--header 'x-api-key: *******************' \
--header 'Content-Type: application/json' \
--data-raw '{
"html": "<h1>Hello World!</h1><a href=\"https://pdf.co\">Go to PDF.co</a>",
"name": "result.pdf",
"margins": "5px 5px 5px 5px",
"paperSize": "Letter",
"orientation": "Portrait",
"printBackground": true,
"header": "",
"footer": "",
"mediaType": "print",
"async": false
}'
var https = require("https");
var path = require("path");
var fs = require("fs");
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
const API_KEY = "***************************";
// HTML Input
const inputHtml = "./sample.html";
// Destination PDF file name
const DestinationFile = "./result.pdf";
// Prepare requests params as JSON
var parameters = {};
// Input HTML code to be converted. Required.
parameters["html"] = fs.readFileSync(inputHtml, "utf8");
// Name of resulting file
parameters["name"] = path.basename(DestinationFile);
// Set to css style margins like 10 px or 5px 5px 5px 5px.
parameters["margins"] = "5px 5px 5px 5px";
// Can be Letter, A4, A5, A6 or custom size like 200x200
parameters["paperSize"] = "Letter";
// Set to Portrait or Landscape. Portrait by default.
parameters["orientation"] = "Portrait";
// true by default. Set to false to disbale printing of background.
parameters["printBackground"] = true;
// If large input document, process in async mode by passing true
parameters["async"] = false;
// Set to HTML for header to be applied on every page at the header.
parameters["header"] = "";
// Set to HTML for footer to be applied on every page at the bottom.
parameters["footer"] = "";
// Convert JSON object to string
var jsonPayload = JSON.stringify(parameters);
// Prepare request to `HTML To PDF` API endpoint
var url = '/v1/pdf/convert/from/html';
var reqOptions = {
host: "api.pdf.co",
path: url,
method: "POST",
headers: {
"x-api-key": API_KEY,
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(jsonPayload, 'utf8')
}
};
// Send request
var postRequest = https.request(reqOptions, (response) => {
response.on("data", (d) => {
// Parse JSON response
var data = JSON.parse(d);
if (data.error == false) {
// Download PDF file
var file = fs.createWriteStream(DestinationFile);
https.get(data.url, (response2) => {
response2.pipe(file)
.on("close", () => {
console.log(`Generated PDF file saved as "${DestinationFile}" file.`);
});
});
}
else {
// Service reported error
console.log(data.message);
}
});
}).on("error", (e) => {
// Request error
console.log(e);
});
// Write request data
postRequest.write(jsonPayload);
postRequest.end();
import os
import json
import requests # pip install requests
# The authentication key (API Key).
# Get your own by registering at https://app.pdf.co
API_KEY = "**************************"
# Base URL for PDF.co Web API requests
BASE_URL = "https://api.pdf.co/v1"
# HTML template
file_read = open(".\\sample.html", mode='r', encoding= 'utf-8')
SampleHtml = file_read.read()
file_read.close()
# Destination PDF file name
DestinationFile = ".\\result.pdf"
def main(args = None):
GeneratePDFFromHtml(SampleHtml, DestinationFile)
def GeneratePDFFromHtml(SampleHtml, destinationFile):
"""Converts HTML to PDF using PDF.co Web API"""
# Prepare requests params as JSON
parameters = {}
# Input HTML code to be converted. Required.
parameters["html"] = SampleHtml
# Name of resulting file
parameters["name"] = os.path.basename(destinationFile)
# Set to css style margins like 10 px or 5px 5px 5px 5px.
parameters["margins"] = "5px 5px 5px 5px"
# Can be Letter, A4, A5, A6 or custom size like 200x200
parameters["paperSize"] = "Letter"
# Set to Portrait or Landscape. Portrait by default.
parameters["orientation"] = "Portrait"
# true by default. Set to false to disable printing of background.
parameters["printBackground"] = "true"
# If large input document, process in async mode by passing true
parameters["async"] = "false"
# Set to HTML for header to be applied on every page at the header.
parameters["header"] = ""
# Set to HTML for footer to be applied on every page at the bottom.
parameters["footer"] = ""
# Prepare URL for 'HTML To PDF' API request
url = "{}/pdf/convert/from/html".format(
BASE_URL
)
# Execute request and get response as JSON
response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# Get URL of result file
resultFileUrl = json["url"]
# Download result file
r = requests.get(resultFileUrl, stream=True)
if (r.status_code == 200):
with open(destinationFile, 'wb') as file:
for chunk in r:
file.write(chunk)
print(f"Result file saved as \"{destinationFile}\" file.")
else:
print(f"Request error: {response.status_code} {response.reason}")
else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
if __name__ == '__main__':
main()
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PDFcoApiExample
{
class Program
{
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
const String API_KEY = "******************************";
static void Main(string[] args)
{
// HTML input
string inputSample = File.ReadAllText(@".\sample.html");
// Destination PDF file name
string destinationFile = @".\result.pdf";
// Create standard .NET web client instance
WebClient webClient = new WebClient();
// Set API Key
webClient.Headers.Add("x-api-key", API_KEY);
// Set JSON content type
webClient.Headers.Add("Content-Type", "application/json");
try
{
// Prepare requests params as JSON
Dictionary<string, object> parameters = new Dictionary<string, object>();
// Input HTML code to be converted. Required.
parameters.Add("html", inputSample);
// Name of resulting file
parameters.Add("name", Path.GetFileName(destinationFile));
// Set to css style margins like 10 px or 5px 5px 5px 5px.
parameters.Add("margins", "5px 5px 5px 5px");
// Can be Letter, A4, A5, A6 or custom size like 200x200
parameters.Add("paperSize", "Letter");
// Set to Portrait or Landscape. Portrait by default.
parameters.Add("orientation", "Portrait");
// true by default. Set to false to disbale printing of background.
parameters.Add("printBackground", true);
// If large input document, process in async mode by passing true
parameters.Add("async", false);
// Set to HTML for header to be applied on every page at the header.
parameters.Add("header", "");
// Set to HTML for footer to be applied on every page at the bottom.
parameters.Add("footer", "");
// Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
// Prepare URL for `HTML to PDF` API call
string url = "https://api.pdf.co/v1/pdf/convert/from/html";
// Execute POST request with JSON payload
string response = webClient.UploadString(url, jsonPayload);
// Parse JSON response
JObject json = JObject.Parse(response);
if (json["error"].ToObject<bool>() == false)
{
// Get URL of generated PDF file
string resultFileUrl = json["url"].ToString();
webClient.Headers.Remove("Content-Type"); // remove the header required for only the previous request
// Download the PDF file
webClient.DownloadFile(resultFileUrl, destinationFile);
Console.WriteLine("Generated PDF document saved as \"{0}\" file.", destinationFile);
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
webClient.Dispose();
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
package com.company;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import okhttp3.*;
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main
{
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
final static String API_KEY = "***********************************";
public static void main(String[] args) throws IOException
{
// HTML input
final String inputSample = new String(Files.readAllBytes(Paths.get(".\\sample.html")));
// Destination PDF file name
final Path destinationFile = Paths.get(".\\result.pdf");
// Create HTTP client instance
OkHttpClient webClient = new OkHttpClient();
// Prepare URL for `HTML to PDF` API call
String apiUrl = "https://api.pdf.co/v1/pdf/convert/from/html";
// Make correctly escaped (encoded) URL
URL url = null;
try
{
url = new URI(null, apiUrl, null).toURL();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
// Prepare request body in JSON format
JsonObject jsonBody = new JsonObject();
// Input HTML code to be converted. Required.
jsonBody.add("html", new JsonPrimitive(inputSample));
// Name of resulting file
jsonBody.add("name", new JsonPrimitive(destinationFile.getFileName().toString()));
// Set to css style margins like 10 px or 5px 5px 5px 5px.
jsonBody.add("margins", new JsonPrimitive("5px 5px 5px 5px"));
// Can be Letter, A4, A5, A6 or custom size like 200x200
jsonBody.add("paperSize", new JsonPrimitive("Letter"));
// Set to Portrait or Landscape. Portrait by default.
jsonBody.add("orientation", new JsonPrimitive("Portrait"));
// true by default. Set to false to disable printing of background.
jsonBody.add("printBackground", new JsonPrimitive(true));
// If large input document, process in async mode by passing true
jsonBody.add("async", new JsonPrimitive(false));
// Set to HTML for header to be applied on every page at the header.
jsonBody.add("header", new JsonPrimitive(""));
// Set to HTML for footer to be applied on every page at the bottom.
jsonBody.add("footer", new JsonPrimitive(""));
RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody.toString());
// Prepare request
Request request = new Request.Builder()
.url(url)
.addHeader("x-api-key", API_KEY) // (!) Set API Key
.addHeader("Content-Type", "application/json")
.post(body)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
if (response.code() == 200)
{
// Parse JSON response
JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();
boolean error = json.get("error").getAsBoolean();
if (!error)
{
// Get URL of generated PDF file
String resultFileUrl = json.get("url").getAsString();
// Download PDF file
downloadFile(webClient, resultFileUrl, destinationFile.toFile());
System.out.printf("Generated PDF file saved as \"%s\" file.", destinationFile.toString());
}
else
{
// Display service reported error
System.out.println(json.get("message").getAsString());
}
}
else
{
// Display request error
System.out.println(response.code() + " " + response.message());
}
}
public static void downloadFile(OkHttpClient webClient, String url, File destinationFile) throws IOException
{
// Prepare request
Request request = new Request.Builder()
.url(url)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
byte[] fileBytes = response.body().bytes();
// Save downloaded bytes to file
OutputStream output = new FileOutputStream(destinationFile);
output.write(fileBytes);
output.flush();
output.close();
response.close();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML to PDF Result</title>
</head>
<body>
<?php
// Get submitted form data
$apiKey = $_POST["apiKey"]; // The authentication key (API Key). Get your own by registering at https://app.pdf.co
// HTML input
$inputHtml = file_get_contents("./inputHtml.html");
// Prepare URL for HTML to PDF API call
$url = "https://api.pdf.co/v1/pdf/convert/from/html";
// Prepare requests params
$parameters = array();
// Input HTML code to be converted. Required.
$parameters["html"] = utf8_encode($inputHtml);
// Name of resulting file
$parameters["name"] = "result.pdf";
// Set to css style margins like 10 px or 5px 5px 5px 5px.
$parameters["margins"] = "5px 5px 5px 5px";
// Can be Letter, A4, A5, A6 or custom size like 200x200
$parameters["paperSize"] = "Letter";
// Set to Portrait or Landscape. Portrait by default.
$parameters["orientation"] = "Portrait";
// true by default. Set to false to disbale printing of background.
$parameters["printBackground"] = true;
// If large input document, process in async mode by passing true
$parameters["async"] = false;
// Set to HTML for header to be applied on every page at the header.
$parameters["header"] = "";
// Set to HTML for footer to be applied on every page at the bottom.
$parameters["footer"] = "";
// Create Json payload
$data = json_encode($parameters);
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-type: application/json"));
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// Execute request
$result = curl_exec($curl);
if (curl_errno($curl) == 0)
{
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status_code == 200)
{
$json = json_decode($result, true);
if (isset($json["error"]) && $json["error"] == true)
{
// Display service reported error
echo "<p>Error: " . $json["message"] . "</p>";
}
else
{
$resultFileUrl = $json["url"];
// Display link to the file with conversion results
echo "<div><h2>Conversion Result:</h2><a href='" . $resultFileUrl . "' target='_blank'>" . $resultFileUrl . "</a></div>";
}
}
else
{
// Display request error
echo "<p>Status code: " . $status_code . "</p>";
echo "<p>" . $result . "</p>";
}
}
else
{
// Display CURL error
echo "Error: " . curl_error($curl);
}
// Cleanup
curl_close($curl);
?>
</body>
</html>
var https = require("https");
var path = require("path");
var fs = require("fs");
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
const API_KEY = "***************************";
// HTML Input
const inputHtml = "./sample.html";
// Destination PDF file name
const DestinationFile = "./result.pdf";
// Prepare requests params as JSON
var parameters = {};
// Input HTML code to be converted. Required.
parameters["html"] = fs.readFileSync(inputHtml, "utf8");
// Name of resulting file
parameters["name"] = path.basename(DestinationFile);
// Set to css style margins like 10 px or 5px 5px 5px 5px.
parameters["margins"] = "5px 5px 5px 5px";
// Can be Letter, A4, A5, A6 or custom size like 200x200
parameters["paperSize"] = "Letter";
// Set to Portrait or Landscape. Portrait by default.
parameters["orientation"] = "Portrait";
// true by default. Set to false to disbale printing of background.
parameters["printBackground"] = true;
// If large input document, process in async mode by passing true
parameters["async"] = false;
// Set to HTML for header to be applied on every page at the header.
parameters["header"] = "";
// Set to HTML for footer to be applied on every page at the bottom.
parameters["footer"] = "";
// Convert JSON object to string
var jsonPayload = JSON.stringify(parameters);
// Prepare request to `HTML To PDF` API endpoint
var url = '/v1/pdf/convert/from/html';
var reqOptions = {
host: "api.pdf.co",
path: url,
method: "POST",
headers: {
"x-api-key": API_KEY,
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(jsonPayload, 'utf8')
}
};
// Send request
var postRequest = https.request(reqOptions, (response) => {
response.on("data", (d) => {
// Parse JSON response
var data = JSON.parse(d);
if (data.error == false) {
// Download PDF file
var file = fs.createWriteStream(DestinationFile);
https.get(data.url, (response2) => {
response2.pipe(file)
.on("close", () => {
console.log(`Generated PDF file saved as "${DestinationFile}" file.`);
});
});
}
else {
// Service reported error
console.log(data.message);
}
});
}).on("error", (e) => {
// Request error
console.log(e);
});
// Write request data
postRequest.write(jsonPayload);
postRequest.end();