Sample request
cURL
curl --location --request POST 'https://api.pdf.co/v1/pdf/convert/from/html' \
--header 'x-api-key: add_your_api_key_here' \
--header 'Content-Type: application/json' \
--data-raw '{
"templateId": 2,
"name": "newDocument.pdf",
"margins": "40px 20px 20px 20px",
"paperSize": "Letter",
"orientation": "Portrait",
"printBackground": true,
"header": "",
"footer": "",
"async": false,
"encrypt": false,
"templateData": "{\"invoice_id\":\"1234567\",\"invoice_date\":\"April 30, 2016\",\"invoice_dateDue\":\"May 15, 2016\",\"paid\":false,\"issuer_name\":\"Acme Inc\",\"issuer_company\":\"Acme International\",\"issuer_address\":\"City, Street 3rd\",\"issuer_email\":\"support@example.com\",\"issuer_website\":\"http://example.com\",\"client_name\":\"Food Delivery Inc.\",\"client_company\":\"Food Delivery International\",\"client_address\":\"New York, Some Street, 42\",\"client_email\":\"client@example.com\",\"items\":[{\"name\":\"Setting up new web-site\",\"price\":250},{\"name\":\"Website Content Addition\",\"price\":700},{\"name\":\"Database Setup\",\"price\":200},{\"name\":\"Record Digitalization\",\"price\":1800},{\"name\":\"Cloud Storage\",\"price\":500},{\"name\":\"Short Messages\",\"price\":35},{\"name\":\"Search Engine Optimization\",\"price\":200},{\"name\":\"Priority Support\",\"price\":75},{\"name\":\"Configuring mail server and mailboxes\",\"price\":50}],\"tax\":0.065,\"discount\":0.01,\"note\":\"Thank You For Your Business!\"}"
}'
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 = "***********************************";
// Data to fill the template
const templateData = "./invoice_data.json";
// Destination PDF file name
const DestinationFile = "./result.pdf";
/*
Please follow below steps to create your own HTML Template and get "templateId".
1. Add new html template in app.pdf.co/templates/html
2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
3. Save this new template
4. Copy it’s ID to clipboard
5. Now set ID of the template into “templateId” parameter
*/
// HTML template using built-in template
// see https://app.pdf.co/templates/html/2/edit
const template_id = 2;
// Prepare request to `HTML To PDF` API endpoint
var queryPath = `/v1/pdf/convert/from/html?name=${path.basename(DestinationFile)}&async=True`;
var reqOptions = {
host: "api.pdf.co",
path: encodeURI(queryPath),
method: "POST",
headers: {
"x-api-key": API_KEY,
"Content-Type": "application/json"
}
};
var requestBody = JSON.stringify({
"templateId": template_id,
"templateData": fs.readFileSync(templateData, "utf8"),
"async": true
});
// Send request
var postRequest = https.request(reqOptions, (response) => {
response.on("data", (d) => {
// Parse JSON response
var data = JSON.parse(d);
if (data.error == false) {
console.log(`Job #${data.jobId} has been created!`);
checkIfJobIsCompleted(data.jobId, data.url);
}
else {
// Service reported error
console.log(data.message);
}
});
}).on("error", (e) => {
// Request error
console.log(e);
});
// Write request data
postRequest.write(requestBody);
postRequest.end();
function checkIfJobIsCompleted(jobId, resultFileUrl) {
let queryPath = `/v1/job/check`;
// JSON payload for api request
let jsonPayload = JSON.stringify({
jobid: jobId
});
let reqOptions = {
host: "api.pdf.co",
path: queryPath,
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) => {
response.setEncoding("utf8");
// Parse JSON response
let data = JSON.parse(d);
console.log(`Checking Job #${jobId}, Status: ${data.status}, Time: ${new Date().toLocaleString()}`);
if (data.status == "working") {
// Check again after 3 seconds
setTimeout(function(){ checkIfJobIsCompleted(jobId, resultFileUrl);}, 3000);
}
else if (data.status == "success") {
// Download PDF file
var file = fs.createWriteStream(DestinationFile);
https.get(resultFileUrl, (response2) => {
response2.pipe(file)
.on("close", () => {
console.log(`Generated PDF file saved as "${DestinationFile}" file.`);
});
});
}
else {
console.log(`Operation ended with status: "${data.status}".`);
}
})
});
// Write request data
postRequest.write(jsonPayload);
postRequest.end();
}
import os
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 ID--
# Please follow below steps to create your own HTML Template and get "templateId".
# 1. Add new html template in app.pdf.co/templates/html
# 2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
# 3. Save this new template
# 4. Copy it’s ID to clipboard
# 5. Now set ID of the template into “templateId” parameter
# HTML template using built-in template
# see https://app.pdf.co/templates/html/2/edit
template_id = 2
# Data to fill the template
file_read = open(".\\invoice_data.json", mode='r')
TemplateData = file_read.read()
file_read.close()
# Destination PDF file name
DestinationFile = ".\\result.pdf"
def main(args = None):
GeneratePDFFromTemplate(template_id, TemplateData, DestinationFile)
def GeneratePDFFromTemplate(template_id, templateData, destinationFile):
"""Converts HTML to PDF using PDF.co Web API"""
data = {
'templateData': templateData,
'templateId': template_id
}
# Prepare URL for 'HTML To PDF' API request
url = "{}/pdf/convert/from/html?name={}".format(
BASE_URL,
os.path.basename(destinationFile)
)
# Execute request and get response as JSON
response = requests.post(url, data=data, 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.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PDFcoCodeSample
{
class Program
{
const String API_KEY = "***********************************";
const string DestinationFile = @".\newDocument.pdf";
const bool Async = true; // Enable asynchronous processing
static async Task Main(string[] args)
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("x-api-key", API_KEY);
string url = "https://api.pdf.co/v1/pdf/convert/from/html";
// Prepare requests params as JSON
Dictionary<string, object> parameters = new Dictionary<string, object>
{
{ "templateId", 1 },
{ "name", Path.GetFileName(DestinationFile) },
{ "margins", "40px 20px 20px 20px" },
{ "paperSize", "Letter" },
{ "orientation", "Portrait" },
{ "header", "" },
{ "printBackground", true },
{ "footer", "" },
{ "async", Async }, // Enable asynchronous processing
{ "encrypt", false },
{ "templateData", "{\"paid\": true,\"invoice_id\": \"0021\",\"invoice_date\": \"August 29, 2041\",\"invoice_dateDue\": \"September 29, 2041\",\"issuer_name\": \"Sarah Connor\",\"issuer_company\": \"T-800 Research Lab\",\"issuer_address\": \"435 South La Fayette Park Place, Los Angeles, CA 90057\",\"issuer_website\": \"www.example.com\",\"issuer_email\": \"info@example.com\",\"client_name\": \"Cyberdyne Systems\",\"client_company\": \"Cyberdyne Systems\",\"client_address\": \"18144 El Camino Real, Sunnyvale, California\",\"client_email\": \"sales@example.com\",\"items\": [ { \"name\": \"T-800 Prototype Research\", \"price\": 1000.00 }, { \"name\": \"T-800 Cloud Sync Setup\", \"price\": 300.00 } ],\"discount\": 100,\"tax\": 87,\"total\": 1287,\"note\": \"Thank you for your support of advanced robotics.\"}" }
};
// Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
try
{
// Send POST request asynchronously
var content = new StringContent(jsonPayload, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// Read response asynchronously
string responseBody = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(responseBody);
if (json["error"].ToObject<bool>() == false)
{
// Get Job ID for asynchronous processing
string jobId = json["jobId"].ToString();
Console.WriteLine($"Job ID: {jobId}");
// Check job status in a loop
bool isJobCompleted = false;
while (!isJobCompleted)
{
string status = await CheckJobStatusAsync(httpClient, jobId);
Console.WriteLine($"Job Status: {status}");
if (status == "success")
{
// Get URL of generated PDF file
string resultFileUrl = json["url"].ToString();
// Download PDF file asynchronously
byte[] fileBytes = await httpClient.GetByteArrayAsync(resultFileUrl);
await File.WriteAllBytesAsync(DestinationFile, fileBytes);
Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile);
isJobCompleted = true;
}
else if (status == "working")
{
// Wait for a few seconds before checking again
await Task.Delay(3000);
}
else
{
Console.WriteLine($"Job failed or aborted. Status: {status}");
isJobCompleted = true;
}
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
static async Task<string> CheckJobStatusAsync(HttpClient httpClient, string jobId)
{
string url = $"https://api.pdf.co/v1/job/check?jobid={jobId}";
// Send GET request to check job status
HttpResponseMessage response = await httpClient.GetAsync(url);
string responseBody = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(responseBody);
return json["status"].ToString();
}
}
}
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
{
/*
Please follow below steps to create your own HTML Template and get "templateId".
1. Add new html template in app.pdf.co/templates/html
2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
3. Save this new template
4. Copy it’s ID to clipboard
5. Now set ID of the template into “templateId” parameter
*/
// HTML template using built-in template
// see https://app.pdf.co/templates/html/2/edit
final String templateId = "2";
// Data to fill the template
final String templateData = new String(Files.readAllBytes(Paths.get(".\\invoice_data.json")));
// 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 query = String.format(
"https://api.pdf.co/v1/pdf/convert/from/html?name=%s",
destinationFile.getFileName());
// Make correctly escaped (encoded) URL
URL url = null;
try
{
url = new URI(null, query, null).toURL();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
// Prepare request body in JSON format
JsonObject jsonBody = new JsonObject();
jsonBody.add("templateId", new JsonPrimitive(templateId));
jsonBody.add("templateData", new JsonPrimitive(templateData));
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();
}
}
<?php
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
$API_KEY = "***********************************";
/*
Please follow below steps to create your own HTML Template and get "templateId".
1. Add new html template in app.pdf.co/templates/html
2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
3. Save this new template
4. Copy it’s ID to clipboard
5. Now set ID of the template into “templateId” parameter
*/
// HTML template using built-in template
// see https://app.pdf.co/templates/html/1/edit
$TemplateId = 1;
// Local JSON file with the data to fill the template
$TemplateDataFile = "./invoice_data.json";
// Destination PDF file name
$DestinationFile = "./result.pdf";
generatePdfFromTemplate($API_KEY, $TemplateId, $TemplateDataFile, $DestinationFile);
function generatePdfFromTemplate($apiKey, $templateId, $templateDataFile, $destinationFile)
{
// Data to fill the template
$templateData = file_get_contents($templateDataFile);
if ($templateData === false) {
echo "generatePdfFromTemplate(): unable to read " . $templateDataFile . PHP_EOL;
return;
}
// Prepare URL for `HTML to PDF` API call
$url = "https://api.pdf.co/v1/pdf/convert/from/html";
// Prepare requests params
$parameters = array();
$parameters["name"] = basename($destinationFile);
$parameters["templateId"] = $templateId;
$parameters["templateData"] = $templateData;
// Create Json payload
$data = json_encode($parameters);
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-Type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "generatePdfFromTemplate(): " . $curlError . PHP_EOL;
return;
}
if ($statusCode != 200) {
// Display request error
echo "generatePdfFromTemplate(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return;
}
$json = json_decode($result, true);
if (!empty($json["error"])) {
// Display service reported error
echo "generatePdfFromTemplate(): " . $json["message"] . PHP_EOL;
return;
}
// Get URL of generated PDF file
$resultFileUrl = $json["url"];
// Download PDF file
if (downloadFile($resultFileUrl, $destinationFile)) {
echo "Generated PDF file saved as \"" . $destinationFile . "\" file." . PHP_EOL;
}
}
function downloadFile($url, $destinationFile)
{
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "downloadFile(): " . $curlError . PHP_EOL;
return false;
}
if ($statusCode != 200) {
// Display request error
echo "downloadFile(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return false;
}
// Write the file only after a successful response so failures leave no file behind
if (file_put_contents($destinationFile, $result) === false) {
echo "downloadFile(): unable to create " . $destinationFile . PHP_EOL;
return false;
}
return true;
}
?>
{
"url": "https://pdf-temp-files.s3.amazonaws.com/97dc323f32794eae8fa6602f5bd981c1/result.pdf",
"pageCount": 1,
"error": false,
"status": 200,
"name": "result.pdf",
"remainingCredits": 60646
}
{
"error": true,
"status": 400,
"message": "Bad request. Typically due to bad input parameters or unreachable input URLs (e.g., access restrictions like login or password)."
}
{
"error": true,
"status": 401,
"message": "Unauthorized. Authentication is required and has failed or has not yet been provided."
}
{
"error": true,
"status": 402,
"message": "Not enough credits."
}
{
"error": true,
"status": 403,
"message": "Access forbidden for input URL."
}
{
"error": true,
"status": 404,
"message": "The requested resource could not be found."
}
{
"error": true,
"status": 408,
"message": "The server timed out waiting for the request."
}
{
"error": true,
"status": 429,
"message": "Too many requests in a given time period."
}
{
"error": true,
"status": 441,
"message": "Invalid Password. Password protected document."
}
{
"error": true,
"status": 442,
"message": "Input document is damaged or of incorrect type."
}
{
"error": true,
"status": 443,
"message": "Permissions. The operation is prohibited by document security settings."
}
{
"error": true,
"status": 444,
"message": "Profiles parsing error. Please ensure that the configuration is supported."
}
{
"error": true,
"status": 445,
"message": "Timeout error. For large documents, use asynchronous mode (async=true) and check status via /job/check."
}
{
"error": true,
"status": 446,
"message": "Some files required for conversion are missing."
}
{
"error": true,
"status": 447,
"message": "Invalid template."
}
{
"error": true,
"status": 448,
"message": "Invalid URL or HTML. Ensure the provided URL is valid and accessible."
}
{
"error": true,
"status": 449,
"message": "Invalid index range. Page index is out of range."
}
{
"error": true,
"status": 450,
"message": "Invalid page range specified."
}
{
"error": true,
"status": 452,
"message": "Invalid URL."
}
{
"error": true,
"status": 454,
"message": "Invalid parameters."
}
{
"error": true,
"status": 500,
"message": "Something went wrong. Please try again or contact support."
}
cURL
curl --location --request POST 'https://api.pdf.co/v1/pdf/convert/from/html' \
--header 'x-api-key: add_your_api_key_here' \
--header 'Content-Type: application/json' \
--data-raw '{
"templateId": 2,
"name": "newDocument.pdf",
"margins": "40px 20px 20px 20px",
"paperSize": "Letter",
"orientation": "Portrait",
"printBackground": true,
"header": "",
"footer": "",
"async": false,
"encrypt": false,
"templateData": "{\"invoice_id\":\"1234567\",\"invoice_date\":\"April 30, 2016\",\"invoice_dateDue\":\"May 15, 2016\",\"paid\":false,\"issuer_name\":\"Acme Inc\",\"issuer_company\":\"Acme International\",\"issuer_address\":\"City, Street 3rd\",\"issuer_email\":\"support@example.com\",\"issuer_website\":\"http://example.com\",\"client_name\":\"Food Delivery Inc.\",\"client_company\":\"Food Delivery International\",\"client_address\":\"New York, Some Street, 42\",\"client_email\":\"client@example.com\",\"items\":[{\"name\":\"Setting up new web-site\",\"price\":250},{\"name\":\"Website Content Addition\",\"price\":700},{\"name\":\"Database Setup\",\"price\":200},{\"name\":\"Record Digitalization\",\"price\":1800},{\"name\":\"Cloud Storage\",\"price\":500},{\"name\":\"Short Messages\",\"price\":35},{\"name\":\"Search Engine Optimization\",\"price\":200},{\"name\":\"Priority Support\",\"price\":75},{\"name\":\"Configuring mail server and mailboxes\",\"price\":50}],\"tax\":0.065,\"discount\":0.01,\"note\":\"Thank You For Your Business!\"}"
}'
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 = "***********************************";
// Data to fill the template
const templateData = "./invoice_data.json";
// Destination PDF file name
const DestinationFile = "./result.pdf";
/*
Please follow below steps to create your own HTML Template and get "templateId".
1. Add new html template in app.pdf.co/templates/html
2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
3. Save this new template
4. Copy it’s ID to clipboard
5. Now set ID of the template into “templateId” parameter
*/
// HTML template using built-in template
// see https://app.pdf.co/templates/html/2/edit
const template_id = 2;
// Prepare request to `HTML To PDF` API endpoint
var queryPath = `/v1/pdf/convert/from/html?name=${path.basename(DestinationFile)}&async=True`;
var reqOptions = {
host: "api.pdf.co",
path: encodeURI(queryPath),
method: "POST",
headers: {
"x-api-key": API_KEY,
"Content-Type": "application/json"
}
};
var requestBody = JSON.stringify({
"templateId": template_id,
"templateData": fs.readFileSync(templateData, "utf8"),
"async": true
});
// Send request
var postRequest = https.request(reqOptions, (response) => {
response.on("data", (d) => {
// Parse JSON response
var data = JSON.parse(d);
if (data.error == false) {
console.log(`Job #${data.jobId} has been created!`);
checkIfJobIsCompleted(data.jobId, data.url);
}
else {
// Service reported error
console.log(data.message);
}
});
}).on("error", (e) => {
// Request error
console.log(e);
});
// Write request data
postRequest.write(requestBody);
postRequest.end();
function checkIfJobIsCompleted(jobId, resultFileUrl) {
let queryPath = `/v1/job/check`;
// JSON payload for api request
let jsonPayload = JSON.stringify({
jobid: jobId
});
let reqOptions = {
host: "api.pdf.co",
path: queryPath,
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) => {
response.setEncoding("utf8");
// Parse JSON response
let data = JSON.parse(d);
console.log(`Checking Job #${jobId}, Status: ${data.status}, Time: ${new Date().toLocaleString()}`);
if (data.status == "working") {
// Check again after 3 seconds
setTimeout(function(){ checkIfJobIsCompleted(jobId, resultFileUrl);}, 3000);
}
else if (data.status == "success") {
// Download PDF file
var file = fs.createWriteStream(DestinationFile);
https.get(resultFileUrl, (response2) => {
response2.pipe(file)
.on("close", () => {
console.log(`Generated PDF file saved as "${DestinationFile}" file.`);
});
});
}
else {
console.log(`Operation ended with status: "${data.status}".`);
}
})
});
// Write request data
postRequest.write(jsonPayload);
postRequest.end();
}
import os
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 ID--
# Please follow below steps to create your own HTML Template and get "templateId".
# 1. Add new html template in app.pdf.co/templates/html
# 2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
# 3. Save this new template
# 4. Copy it’s ID to clipboard
# 5. Now set ID of the template into “templateId” parameter
# HTML template using built-in template
# see https://app.pdf.co/templates/html/2/edit
template_id = 2
# Data to fill the template
file_read = open(".\\invoice_data.json", mode='r')
TemplateData = file_read.read()
file_read.close()
# Destination PDF file name
DestinationFile = ".\\result.pdf"
def main(args = None):
GeneratePDFFromTemplate(template_id, TemplateData, DestinationFile)
def GeneratePDFFromTemplate(template_id, templateData, destinationFile):
"""Converts HTML to PDF using PDF.co Web API"""
data = {
'templateData': templateData,
'templateId': template_id
}
# Prepare URL for 'HTML To PDF' API request
url = "{}/pdf/convert/from/html?name={}".format(
BASE_URL,
os.path.basename(destinationFile)
)
# Execute request and get response as JSON
response = requests.post(url, data=data, 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.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PDFcoCodeSample
{
class Program
{
const String API_KEY = "***********************************";
const string DestinationFile = @".\newDocument.pdf";
const bool Async = true; // Enable asynchronous processing
static async Task Main(string[] args)
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("x-api-key", API_KEY);
string url = "https://api.pdf.co/v1/pdf/convert/from/html";
// Prepare requests params as JSON
Dictionary<string, object> parameters = new Dictionary<string, object>
{
{ "templateId", 1 },
{ "name", Path.GetFileName(DestinationFile) },
{ "margins", "40px 20px 20px 20px" },
{ "paperSize", "Letter" },
{ "orientation", "Portrait" },
{ "header", "" },
{ "printBackground", true },
{ "footer", "" },
{ "async", Async }, // Enable asynchronous processing
{ "encrypt", false },
{ "templateData", "{\"paid\": true,\"invoice_id\": \"0021\",\"invoice_date\": \"August 29, 2041\",\"invoice_dateDue\": \"September 29, 2041\",\"issuer_name\": \"Sarah Connor\",\"issuer_company\": \"T-800 Research Lab\",\"issuer_address\": \"435 South La Fayette Park Place, Los Angeles, CA 90057\",\"issuer_website\": \"www.example.com\",\"issuer_email\": \"info@example.com\",\"client_name\": \"Cyberdyne Systems\",\"client_company\": \"Cyberdyne Systems\",\"client_address\": \"18144 El Camino Real, Sunnyvale, California\",\"client_email\": \"sales@example.com\",\"items\": [ { \"name\": \"T-800 Prototype Research\", \"price\": 1000.00 }, { \"name\": \"T-800 Cloud Sync Setup\", \"price\": 300.00 } ],\"discount\": 100,\"tax\": 87,\"total\": 1287,\"note\": \"Thank you for your support of advanced robotics.\"}" }
};
// Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
try
{
// Send POST request asynchronously
var content = new StringContent(jsonPayload, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// Read response asynchronously
string responseBody = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(responseBody);
if (json["error"].ToObject<bool>() == false)
{
// Get Job ID for asynchronous processing
string jobId = json["jobId"].ToString();
Console.WriteLine($"Job ID: {jobId}");
// Check job status in a loop
bool isJobCompleted = false;
while (!isJobCompleted)
{
string status = await CheckJobStatusAsync(httpClient, jobId);
Console.WriteLine($"Job Status: {status}");
if (status == "success")
{
// Get URL of generated PDF file
string resultFileUrl = json["url"].ToString();
// Download PDF file asynchronously
byte[] fileBytes = await httpClient.GetByteArrayAsync(resultFileUrl);
await File.WriteAllBytesAsync(DestinationFile, fileBytes);
Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile);
isJobCompleted = true;
}
else if (status == "working")
{
// Wait for a few seconds before checking again
await Task.Delay(3000);
}
else
{
Console.WriteLine($"Job failed or aborted. Status: {status}");
isJobCompleted = true;
}
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
static async Task<string> CheckJobStatusAsync(HttpClient httpClient, string jobId)
{
string url = $"https://api.pdf.co/v1/job/check?jobid={jobId}";
// Send GET request to check job status
HttpResponseMessage response = await httpClient.GetAsync(url);
string responseBody = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(responseBody);
return json["status"].ToString();
}
}
}
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
{
/*
Please follow below steps to create your own HTML Template and get "templateId".
1. Add new html template in app.pdf.co/templates/html
2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
3. Save this new template
4. Copy it’s ID to clipboard
5. Now set ID of the template into “templateId” parameter
*/
// HTML template using built-in template
// see https://app.pdf.co/templates/html/2/edit
final String templateId = "2";
// Data to fill the template
final String templateData = new String(Files.readAllBytes(Paths.get(".\\invoice_data.json")));
// 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 query = String.format(
"https://api.pdf.co/v1/pdf/convert/from/html?name=%s",
destinationFile.getFileName());
// Make correctly escaped (encoded) URL
URL url = null;
try
{
url = new URI(null, query, null).toURL();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
// Prepare request body in JSON format
JsonObject jsonBody = new JsonObject();
jsonBody.add("templateId", new JsonPrimitive(templateId));
jsonBody.add("templateData", new JsonPrimitive(templateData));
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();
}
}
<?php
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
$API_KEY = "***********************************";
/*
Please follow below steps to create your own HTML Template and get "templateId".
1. Add new html template in app.pdf.co/templates/html
2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
3. Save this new template
4. Copy it’s ID to clipboard
5. Now set ID of the template into “templateId” parameter
*/
// HTML template using built-in template
// see https://app.pdf.co/templates/html/1/edit
$TemplateId = 1;
// Local JSON file with the data to fill the template
$TemplateDataFile = "./invoice_data.json";
// Destination PDF file name
$DestinationFile = "./result.pdf";
generatePdfFromTemplate($API_KEY, $TemplateId, $TemplateDataFile, $DestinationFile);
function generatePdfFromTemplate($apiKey, $templateId, $templateDataFile, $destinationFile)
{
// Data to fill the template
$templateData = file_get_contents($templateDataFile);
if ($templateData === false) {
echo "generatePdfFromTemplate(): unable to read " . $templateDataFile . PHP_EOL;
return;
}
// Prepare URL for `HTML to PDF` API call
$url = "https://api.pdf.co/v1/pdf/convert/from/html";
// Prepare requests params
$parameters = array();
$parameters["name"] = basename($destinationFile);
$parameters["templateId"] = $templateId;
$parameters["templateData"] = $templateData;
// Create Json payload
$data = json_encode($parameters);
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-Type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "generatePdfFromTemplate(): " . $curlError . PHP_EOL;
return;
}
if ($statusCode != 200) {
// Display request error
echo "generatePdfFromTemplate(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return;
}
$json = json_decode($result, true);
if (!empty($json["error"])) {
// Display service reported error
echo "generatePdfFromTemplate(): " . $json["message"] . PHP_EOL;
return;
}
// Get URL of generated PDF file
$resultFileUrl = $json["url"];
// Download PDF file
if (downloadFile($resultFileUrl, $destinationFile)) {
echo "Generated PDF file saved as \"" . $destinationFile . "\" file." . PHP_EOL;
}
}
function downloadFile($url, $destinationFile)
{
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "downloadFile(): " . $curlError . PHP_EOL;
return false;
}
if ($statusCode != 200) {
// Display request error
echo "downloadFile(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return false;
}
// Write the file only after a successful response so failures leave no file behind
if (file_put_contents($destinationFile, $result) === false) {
echo "downloadFile(): unable to create " . $destinationFile . PHP_EOL;
return false;
}
return true;
}
?>
{
"url": "https://pdf-temp-files.s3.amazonaws.com/97dc323f32794eae8fa6602f5bd981c1/result.pdf",
"pageCount": 1,
"error": false,
"status": 200,
"name": "result.pdf",
"remainingCredits": 60646
}
{
"error": true,
"status": 400,
"message": "Bad request. Typically due to bad input parameters or unreachable input URLs (e.g., access restrictions like login or password)."
}
{
"error": true,
"status": 401,
"message": "Unauthorized. Authentication is required and has failed or has not yet been provided."
}
{
"error": true,
"status": 402,
"message": "Not enough credits."
}
{
"error": true,
"status": 403,
"message": "Access forbidden for input URL."
}
{
"error": true,
"status": 404,
"message": "The requested resource could not be found."
}
{
"error": true,
"status": 408,
"message": "The server timed out waiting for the request."
}
{
"error": true,
"status": 429,
"message": "Too many requests in a given time period."
}
{
"error": true,
"status": 441,
"message": "Invalid Password. Password protected document."
}
{
"error": true,
"status": 442,
"message": "Input document is damaged or of incorrect type."
}
{
"error": true,
"status": 443,
"message": "Permissions. The operation is prohibited by document security settings."
}
{
"error": true,
"status": 444,
"message": "Profiles parsing error. Please ensure that the configuration is supported."
}
{
"error": true,
"status": 445,
"message": "Timeout error. For large documents, use asynchronous mode (async=true) and check status via /job/check."
}
{
"error": true,
"status": 446,
"message": "Some files required for conversion are missing."
}
{
"error": true,
"status": 447,
"message": "Invalid template."
}
{
"error": true,
"status": 448,
"message": "Invalid URL or HTML. Ensure the provided URL is valid and accessible."
}
{
"error": true,
"status": 449,
"message": "Invalid index range. Page index is out of range."
}
{
"error": true,
"status": 450,
"message": "Invalid page range specified."
}
{
"error": true,
"status": 452,
"message": "Invalid URL."
}
{
"error": true,
"status": 454,
"message": "Invalid parameters."
}
{
"error": true,
"status": 500,
"message": "Something went wrong. Please try again or contact support."
}
PDF from HTML
PDF from HTML Template
Convert HTML template into PDF.
Sample request
cURL
curl --location --request POST 'https://api.pdf.co/v1/pdf/convert/from/html' \
--header 'x-api-key: add_your_api_key_here' \
--header 'Content-Type: application/json' \
--data-raw '{
"templateId": 2,
"name": "newDocument.pdf",
"margins": "40px 20px 20px 20px",
"paperSize": "Letter",
"orientation": "Portrait",
"printBackground": true,
"header": "",
"footer": "",
"async": false,
"encrypt": false,
"templateData": "{\"invoice_id\":\"1234567\",\"invoice_date\":\"April 30, 2016\",\"invoice_dateDue\":\"May 15, 2016\",\"paid\":false,\"issuer_name\":\"Acme Inc\",\"issuer_company\":\"Acme International\",\"issuer_address\":\"City, Street 3rd\",\"issuer_email\":\"support@example.com\",\"issuer_website\":\"http://example.com\",\"client_name\":\"Food Delivery Inc.\",\"client_company\":\"Food Delivery International\",\"client_address\":\"New York, Some Street, 42\",\"client_email\":\"client@example.com\",\"items\":[{\"name\":\"Setting up new web-site\",\"price\":250},{\"name\":\"Website Content Addition\",\"price\":700},{\"name\":\"Database Setup\",\"price\":200},{\"name\":\"Record Digitalization\",\"price\":1800},{\"name\":\"Cloud Storage\",\"price\":500},{\"name\":\"Short Messages\",\"price\":35},{\"name\":\"Search Engine Optimization\",\"price\":200},{\"name\":\"Priority Support\",\"price\":75},{\"name\":\"Configuring mail server and mailboxes\",\"price\":50}],\"tax\":0.065,\"discount\":0.01,\"note\":\"Thank You For Your Business!\"}"
}'
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 = "***********************************";
// Data to fill the template
const templateData = "./invoice_data.json";
// Destination PDF file name
const DestinationFile = "./result.pdf";
/*
Please follow below steps to create your own HTML Template and get "templateId".
1. Add new html template in app.pdf.co/templates/html
2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
3. Save this new template
4. Copy it’s ID to clipboard
5. Now set ID of the template into “templateId” parameter
*/
// HTML template using built-in template
// see https://app.pdf.co/templates/html/2/edit
const template_id = 2;
// Prepare request to `HTML To PDF` API endpoint
var queryPath = `/v1/pdf/convert/from/html?name=${path.basename(DestinationFile)}&async=True`;
var reqOptions = {
host: "api.pdf.co",
path: encodeURI(queryPath),
method: "POST",
headers: {
"x-api-key": API_KEY,
"Content-Type": "application/json"
}
};
var requestBody = JSON.stringify({
"templateId": template_id,
"templateData": fs.readFileSync(templateData, "utf8"),
"async": true
});
// Send request
var postRequest = https.request(reqOptions, (response) => {
response.on("data", (d) => {
// Parse JSON response
var data = JSON.parse(d);
if (data.error == false) {
console.log(`Job #${data.jobId} has been created!`);
checkIfJobIsCompleted(data.jobId, data.url);
}
else {
// Service reported error
console.log(data.message);
}
});
}).on("error", (e) => {
// Request error
console.log(e);
});
// Write request data
postRequest.write(requestBody);
postRequest.end();
function checkIfJobIsCompleted(jobId, resultFileUrl) {
let queryPath = `/v1/job/check`;
// JSON payload for api request
let jsonPayload = JSON.stringify({
jobid: jobId
});
let reqOptions = {
host: "api.pdf.co",
path: queryPath,
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) => {
response.setEncoding("utf8");
// Parse JSON response
let data = JSON.parse(d);
console.log(`Checking Job #${jobId}, Status: ${data.status}, Time: ${new Date().toLocaleString()}`);
if (data.status == "working") {
// Check again after 3 seconds
setTimeout(function(){ checkIfJobIsCompleted(jobId, resultFileUrl);}, 3000);
}
else if (data.status == "success") {
// Download PDF file
var file = fs.createWriteStream(DestinationFile);
https.get(resultFileUrl, (response2) => {
response2.pipe(file)
.on("close", () => {
console.log(`Generated PDF file saved as "${DestinationFile}" file.`);
});
});
}
else {
console.log(`Operation ended with status: "${data.status}".`);
}
})
});
// Write request data
postRequest.write(jsonPayload);
postRequest.end();
}
import os
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 ID--
# Please follow below steps to create your own HTML Template and get "templateId".
# 1. Add new html template in app.pdf.co/templates/html
# 2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
# 3. Save this new template
# 4. Copy it’s ID to clipboard
# 5. Now set ID of the template into “templateId” parameter
# HTML template using built-in template
# see https://app.pdf.co/templates/html/2/edit
template_id = 2
# Data to fill the template
file_read = open(".\\invoice_data.json", mode='r')
TemplateData = file_read.read()
file_read.close()
# Destination PDF file name
DestinationFile = ".\\result.pdf"
def main(args = None):
GeneratePDFFromTemplate(template_id, TemplateData, DestinationFile)
def GeneratePDFFromTemplate(template_id, templateData, destinationFile):
"""Converts HTML to PDF using PDF.co Web API"""
data = {
'templateData': templateData,
'templateId': template_id
}
# Prepare URL for 'HTML To PDF' API request
url = "{}/pdf/convert/from/html?name={}".format(
BASE_URL,
os.path.basename(destinationFile)
)
# Execute request and get response as JSON
response = requests.post(url, data=data, 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.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PDFcoCodeSample
{
class Program
{
const String API_KEY = "***********************************";
const string DestinationFile = @".\newDocument.pdf";
const bool Async = true; // Enable asynchronous processing
static async Task Main(string[] args)
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("x-api-key", API_KEY);
string url = "https://api.pdf.co/v1/pdf/convert/from/html";
// Prepare requests params as JSON
Dictionary<string, object> parameters = new Dictionary<string, object>
{
{ "templateId", 1 },
{ "name", Path.GetFileName(DestinationFile) },
{ "margins", "40px 20px 20px 20px" },
{ "paperSize", "Letter" },
{ "orientation", "Portrait" },
{ "header", "" },
{ "printBackground", true },
{ "footer", "" },
{ "async", Async }, // Enable asynchronous processing
{ "encrypt", false },
{ "templateData", "{\"paid\": true,\"invoice_id\": \"0021\",\"invoice_date\": \"August 29, 2041\",\"invoice_dateDue\": \"September 29, 2041\",\"issuer_name\": \"Sarah Connor\",\"issuer_company\": \"T-800 Research Lab\",\"issuer_address\": \"435 South La Fayette Park Place, Los Angeles, CA 90057\",\"issuer_website\": \"www.example.com\",\"issuer_email\": \"info@example.com\",\"client_name\": \"Cyberdyne Systems\",\"client_company\": \"Cyberdyne Systems\",\"client_address\": \"18144 El Camino Real, Sunnyvale, California\",\"client_email\": \"sales@example.com\",\"items\": [ { \"name\": \"T-800 Prototype Research\", \"price\": 1000.00 }, { \"name\": \"T-800 Cloud Sync Setup\", \"price\": 300.00 } ],\"discount\": 100,\"tax\": 87,\"total\": 1287,\"note\": \"Thank you for your support of advanced robotics.\"}" }
};
// Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
try
{
// Send POST request asynchronously
var content = new StringContent(jsonPayload, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// Read response asynchronously
string responseBody = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(responseBody);
if (json["error"].ToObject<bool>() == false)
{
// Get Job ID for asynchronous processing
string jobId = json["jobId"].ToString();
Console.WriteLine($"Job ID: {jobId}");
// Check job status in a loop
bool isJobCompleted = false;
while (!isJobCompleted)
{
string status = await CheckJobStatusAsync(httpClient, jobId);
Console.WriteLine($"Job Status: {status}");
if (status == "success")
{
// Get URL of generated PDF file
string resultFileUrl = json["url"].ToString();
// Download PDF file asynchronously
byte[] fileBytes = await httpClient.GetByteArrayAsync(resultFileUrl);
await File.WriteAllBytesAsync(DestinationFile, fileBytes);
Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile);
isJobCompleted = true;
}
else if (status == "working")
{
// Wait for a few seconds before checking again
await Task.Delay(3000);
}
else
{
Console.WriteLine($"Job failed or aborted. Status: {status}");
isJobCompleted = true;
}
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
static async Task<string> CheckJobStatusAsync(HttpClient httpClient, string jobId)
{
string url = $"https://api.pdf.co/v1/job/check?jobid={jobId}";
// Send GET request to check job status
HttpResponseMessage response = await httpClient.GetAsync(url);
string responseBody = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(responseBody);
return json["status"].ToString();
}
}
}
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
{
/*
Please follow below steps to create your own HTML Template and get "templateId".
1. Add new html template in app.pdf.co/templates/html
2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
3. Save this new template
4. Copy it’s ID to clipboard
5. Now set ID of the template into “templateId” parameter
*/
// HTML template using built-in template
// see https://app.pdf.co/templates/html/2/edit
final String templateId = "2";
// Data to fill the template
final String templateData = new String(Files.readAllBytes(Paths.get(".\\invoice_data.json")));
// 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 query = String.format(
"https://api.pdf.co/v1/pdf/convert/from/html?name=%s",
destinationFile.getFileName());
// Make correctly escaped (encoded) URL
URL url = null;
try
{
url = new URI(null, query, null).toURL();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
// Prepare request body in JSON format
JsonObject jsonBody = new JsonObject();
jsonBody.add("templateId", new JsonPrimitive(templateId));
jsonBody.add("templateData", new JsonPrimitive(templateData));
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();
}
}
<?php
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
$API_KEY = "***********************************";
/*
Please follow below steps to create your own HTML Template and get "templateId".
1. Add new html template in app.pdf.co/templates/html
2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
3. Save this new template
4. Copy it’s ID to clipboard
5. Now set ID of the template into “templateId” parameter
*/
// HTML template using built-in template
// see https://app.pdf.co/templates/html/1/edit
$TemplateId = 1;
// Local JSON file with the data to fill the template
$TemplateDataFile = "./invoice_data.json";
// Destination PDF file name
$DestinationFile = "./result.pdf";
generatePdfFromTemplate($API_KEY, $TemplateId, $TemplateDataFile, $DestinationFile);
function generatePdfFromTemplate($apiKey, $templateId, $templateDataFile, $destinationFile)
{
// Data to fill the template
$templateData = file_get_contents($templateDataFile);
if ($templateData === false) {
echo "generatePdfFromTemplate(): unable to read " . $templateDataFile . PHP_EOL;
return;
}
// Prepare URL for `HTML to PDF` API call
$url = "https://api.pdf.co/v1/pdf/convert/from/html";
// Prepare requests params
$parameters = array();
$parameters["name"] = basename($destinationFile);
$parameters["templateId"] = $templateId;
$parameters["templateData"] = $templateData;
// Create Json payload
$data = json_encode($parameters);
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-Type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "generatePdfFromTemplate(): " . $curlError . PHP_EOL;
return;
}
if ($statusCode != 200) {
// Display request error
echo "generatePdfFromTemplate(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return;
}
$json = json_decode($result, true);
if (!empty($json["error"])) {
// Display service reported error
echo "generatePdfFromTemplate(): " . $json["message"] . PHP_EOL;
return;
}
// Get URL of generated PDF file
$resultFileUrl = $json["url"];
// Download PDF file
if (downloadFile($resultFileUrl, $destinationFile)) {
echo "Generated PDF file saved as \"" . $destinationFile . "\" file." . PHP_EOL;
}
}
function downloadFile($url, $destinationFile)
{
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "downloadFile(): " . $curlError . PHP_EOL;
return false;
}
if ($statusCode != 200) {
// Display request error
echo "downloadFile(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return false;
}
// Write the file only after a successful response so failures leave no file behind
if (file_put_contents($destinationFile, $result) === false) {
echo "downloadFile(): unable to create " . $destinationFile . PHP_EOL;
return false;
}
return true;
}
?>
{
"url": "https://pdf-temp-files.s3.amazonaws.com/97dc323f32794eae8fa6602f5bd981c1/result.pdf",
"pageCount": 1,
"error": false,
"status": 200,
"name": "result.pdf",
"remainingCredits": 60646
}
{
"error": true,
"status": 400,
"message": "Bad request. Typically due to bad input parameters or unreachable input URLs (e.g., access restrictions like login or password)."
}
{
"error": true,
"status": 401,
"message": "Unauthorized. Authentication is required and has failed or has not yet been provided."
}
{
"error": true,
"status": 402,
"message": "Not enough credits."
}
{
"error": true,
"status": 403,
"message": "Access forbidden for input URL."
}
{
"error": true,
"status": 404,
"message": "The requested resource could not be found."
}
{
"error": true,
"status": 408,
"message": "The server timed out waiting for the request."
}
{
"error": true,
"status": 429,
"message": "Too many requests in a given time period."
}
{
"error": true,
"status": 441,
"message": "Invalid Password. Password protected document."
}
{
"error": true,
"status": 442,
"message": "Input document is damaged or of incorrect type."
}
{
"error": true,
"status": 443,
"message": "Permissions. The operation is prohibited by document security settings."
}
{
"error": true,
"status": 444,
"message": "Profiles parsing error. Please ensure that the configuration is supported."
}
{
"error": true,
"status": 445,
"message": "Timeout error. For large documents, use asynchronous mode (async=true) and check status via /job/check."
}
{
"error": true,
"status": 446,
"message": "Some files required for conversion are missing."
}
{
"error": true,
"status": 447,
"message": "Invalid template."
}
{
"error": true,
"status": 448,
"message": "Invalid URL or HTML. Ensure the provided URL is valid and accessible."
}
{
"error": true,
"status": 449,
"message": "Invalid index range. Page index is out of range."
}
{
"error": true,
"status": 450,
"message": "Invalid page range specified."
}
{
"error": true,
"status": 452,
"message": "Invalid URL."
}
{
"error": true,
"status": 454,
"message": "Invalid parameters."
}
{
"error": true,
"status": 500,
"message": "Something went wrong. Please try again or contact support."
}
cURL
curl --location --request POST 'https://api.pdf.co/v1/pdf/convert/from/html' \
--header 'x-api-key: add_your_api_key_here' \
--header 'Content-Type: application/json' \
--data-raw '{
"templateId": 2,
"name": "newDocument.pdf",
"margins": "40px 20px 20px 20px",
"paperSize": "Letter",
"orientation": "Portrait",
"printBackground": true,
"header": "",
"footer": "",
"async": false,
"encrypt": false,
"templateData": "{\"invoice_id\":\"1234567\",\"invoice_date\":\"April 30, 2016\",\"invoice_dateDue\":\"May 15, 2016\",\"paid\":false,\"issuer_name\":\"Acme Inc\",\"issuer_company\":\"Acme International\",\"issuer_address\":\"City, Street 3rd\",\"issuer_email\":\"support@example.com\",\"issuer_website\":\"http://example.com\",\"client_name\":\"Food Delivery Inc.\",\"client_company\":\"Food Delivery International\",\"client_address\":\"New York, Some Street, 42\",\"client_email\":\"client@example.com\",\"items\":[{\"name\":\"Setting up new web-site\",\"price\":250},{\"name\":\"Website Content Addition\",\"price\":700},{\"name\":\"Database Setup\",\"price\":200},{\"name\":\"Record Digitalization\",\"price\":1800},{\"name\":\"Cloud Storage\",\"price\":500},{\"name\":\"Short Messages\",\"price\":35},{\"name\":\"Search Engine Optimization\",\"price\":200},{\"name\":\"Priority Support\",\"price\":75},{\"name\":\"Configuring mail server and mailboxes\",\"price\":50}],\"tax\":0.065,\"discount\":0.01,\"note\":\"Thank You For Your Business!\"}"
}'
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 = "***********************************";
// Data to fill the template
const templateData = "./invoice_data.json";
// Destination PDF file name
const DestinationFile = "./result.pdf";
/*
Please follow below steps to create your own HTML Template and get "templateId".
1. Add new html template in app.pdf.co/templates/html
2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
3. Save this new template
4. Copy it’s ID to clipboard
5. Now set ID of the template into “templateId” parameter
*/
// HTML template using built-in template
// see https://app.pdf.co/templates/html/2/edit
const template_id = 2;
// Prepare request to `HTML To PDF` API endpoint
var queryPath = `/v1/pdf/convert/from/html?name=${path.basename(DestinationFile)}&async=True`;
var reqOptions = {
host: "api.pdf.co",
path: encodeURI(queryPath),
method: "POST",
headers: {
"x-api-key": API_KEY,
"Content-Type": "application/json"
}
};
var requestBody = JSON.stringify({
"templateId": template_id,
"templateData": fs.readFileSync(templateData, "utf8"),
"async": true
});
// Send request
var postRequest = https.request(reqOptions, (response) => {
response.on("data", (d) => {
// Parse JSON response
var data = JSON.parse(d);
if (data.error == false) {
console.log(`Job #${data.jobId} has been created!`);
checkIfJobIsCompleted(data.jobId, data.url);
}
else {
// Service reported error
console.log(data.message);
}
});
}).on("error", (e) => {
// Request error
console.log(e);
});
// Write request data
postRequest.write(requestBody);
postRequest.end();
function checkIfJobIsCompleted(jobId, resultFileUrl) {
let queryPath = `/v1/job/check`;
// JSON payload for api request
let jsonPayload = JSON.stringify({
jobid: jobId
});
let reqOptions = {
host: "api.pdf.co",
path: queryPath,
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) => {
response.setEncoding("utf8");
// Parse JSON response
let data = JSON.parse(d);
console.log(`Checking Job #${jobId}, Status: ${data.status}, Time: ${new Date().toLocaleString()}`);
if (data.status == "working") {
// Check again after 3 seconds
setTimeout(function(){ checkIfJobIsCompleted(jobId, resultFileUrl);}, 3000);
}
else if (data.status == "success") {
// Download PDF file
var file = fs.createWriteStream(DestinationFile);
https.get(resultFileUrl, (response2) => {
response2.pipe(file)
.on("close", () => {
console.log(`Generated PDF file saved as "${DestinationFile}" file.`);
});
});
}
else {
console.log(`Operation ended with status: "${data.status}".`);
}
})
});
// Write request data
postRequest.write(jsonPayload);
postRequest.end();
}
import os
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 ID--
# Please follow below steps to create your own HTML Template and get "templateId".
# 1. Add new html template in app.pdf.co/templates/html
# 2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
# 3. Save this new template
# 4. Copy it’s ID to clipboard
# 5. Now set ID of the template into “templateId” parameter
# HTML template using built-in template
# see https://app.pdf.co/templates/html/2/edit
template_id = 2
# Data to fill the template
file_read = open(".\\invoice_data.json", mode='r')
TemplateData = file_read.read()
file_read.close()
# Destination PDF file name
DestinationFile = ".\\result.pdf"
def main(args = None):
GeneratePDFFromTemplate(template_id, TemplateData, DestinationFile)
def GeneratePDFFromTemplate(template_id, templateData, destinationFile):
"""Converts HTML to PDF using PDF.co Web API"""
data = {
'templateData': templateData,
'templateId': template_id
}
# Prepare URL for 'HTML To PDF' API request
url = "{}/pdf/convert/from/html?name={}".format(
BASE_URL,
os.path.basename(destinationFile)
)
# Execute request and get response as JSON
response = requests.post(url, data=data, 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.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PDFcoCodeSample
{
class Program
{
const String API_KEY = "***********************************";
const string DestinationFile = @".\newDocument.pdf";
const bool Async = true; // Enable asynchronous processing
static async Task Main(string[] args)
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("x-api-key", API_KEY);
string url = "https://api.pdf.co/v1/pdf/convert/from/html";
// Prepare requests params as JSON
Dictionary<string, object> parameters = new Dictionary<string, object>
{
{ "templateId", 1 },
{ "name", Path.GetFileName(DestinationFile) },
{ "margins", "40px 20px 20px 20px" },
{ "paperSize", "Letter" },
{ "orientation", "Portrait" },
{ "header", "" },
{ "printBackground", true },
{ "footer", "" },
{ "async", Async }, // Enable asynchronous processing
{ "encrypt", false },
{ "templateData", "{\"paid\": true,\"invoice_id\": \"0021\",\"invoice_date\": \"August 29, 2041\",\"invoice_dateDue\": \"September 29, 2041\",\"issuer_name\": \"Sarah Connor\",\"issuer_company\": \"T-800 Research Lab\",\"issuer_address\": \"435 South La Fayette Park Place, Los Angeles, CA 90057\",\"issuer_website\": \"www.example.com\",\"issuer_email\": \"info@example.com\",\"client_name\": \"Cyberdyne Systems\",\"client_company\": \"Cyberdyne Systems\",\"client_address\": \"18144 El Camino Real, Sunnyvale, California\",\"client_email\": \"sales@example.com\",\"items\": [ { \"name\": \"T-800 Prototype Research\", \"price\": 1000.00 }, { \"name\": \"T-800 Cloud Sync Setup\", \"price\": 300.00 } ],\"discount\": 100,\"tax\": 87,\"total\": 1287,\"note\": \"Thank you for your support of advanced robotics.\"}" }
};
// Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
try
{
// Send POST request asynchronously
var content = new StringContent(jsonPayload, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// Read response asynchronously
string responseBody = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(responseBody);
if (json["error"].ToObject<bool>() == false)
{
// Get Job ID for asynchronous processing
string jobId = json["jobId"].ToString();
Console.WriteLine($"Job ID: {jobId}");
// Check job status in a loop
bool isJobCompleted = false;
while (!isJobCompleted)
{
string status = await CheckJobStatusAsync(httpClient, jobId);
Console.WriteLine($"Job Status: {status}");
if (status == "success")
{
// Get URL of generated PDF file
string resultFileUrl = json["url"].ToString();
// Download PDF file asynchronously
byte[] fileBytes = await httpClient.GetByteArrayAsync(resultFileUrl);
await File.WriteAllBytesAsync(DestinationFile, fileBytes);
Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile);
isJobCompleted = true;
}
else if (status == "working")
{
// Wait for a few seconds before checking again
await Task.Delay(3000);
}
else
{
Console.WriteLine($"Job failed or aborted. Status: {status}");
isJobCompleted = true;
}
}
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
static async Task<string> CheckJobStatusAsync(HttpClient httpClient, string jobId)
{
string url = $"https://api.pdf.co/v1/job/check?jobid={jobId}";
// Send GET request to check job status
HttpResponseMessage response = await httpClient.GetAsync(url);
string responseBody = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(responseBody);
return json["status"].ToString();
}
}
}
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
{
/*
Please follow below steps to create your own HTML Template and get "templateId".
1. Add new html template in app.pdf.co/templates/html
2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
3. Save this new template
4. Copy it’s ID to clipboard
5. Now set ID of the template into “templateId” parameter
*/
// HTML template using built-in template
// see https://app.pdf.co/templates/html/2/edit
final String templateId = "2";
// Data to fill the template
final String templateData = new String(Files.readAllBytes(Paths.get(".\\invoice_data.json")));
// 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 query = String.format(
"https://api.pdf.co/v1/pdf/convert/from/html?name=%s",
destinationFile.getFileName());
// Make correctly escaped (encoded) URL
URL url = null;
try
{
url = new URI(null, query, null).toURL();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
// Prepare request body in JSON format
JsonObject jsonBody = new JsonObject();
jsonBody.add("templateId", new JsonPrimitive(templateId));
jsonBody.add("templateData", new JsonPrimitive(templateData));
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();
}
}
<?php
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
$API_KEY = "***********************************";
/*
Please follow below steps to create your own HTML Template and get "templateId".
1. Add new html template in app.pdf.co/templates/html
2. Copy paste your html template code into this new template. Sample HTML templates can be found at "https://github.com/pdfdotco/pdf-co-api-samples/tree/master/PDF%20from%20HTML%20template/TEMPLATES-SAMPLES"
3. Save this new template
4. Copy it’s ID to clipboard
5. Now set ID of the template into “templateId” parameter
*/
// HTML template using built-in template
// see https://app.pdf.co/templates/html/1/edit
$TemplateId = 1;
// Local JSON file with the data to fill the template
$TemplateDataFile = "./invoice_data.json";
// Destination PDF file name
$DestinationFile = "./result.pdf";
generatePdfFromTemplate($API_KEY, $TemplateId, $TemplateDataFile, $DestinationFile);
function generatePdfFromTemplate($apiKey, $templateId, $templateDataFile, $destinationFile)
{
// Data to fill the template
$templateData = file_get_contents($templateDataFile);
if ($templateData === false) {
echo "generatePdfFromTemplate(): unable to read " . $templateDataFile . PHP_EOL;
return;
}
// Prepare URL for `HTML to PDF` API call
$url = "https://api.pdf.co/v1/pdf/convert/from/html";
// Prepare requests params
$parameters = array();
$parameters["name"] = basename($destinationFile);
$parameters["templateId"] = $templateId;
$parameters["templateData"] = $templateData;
// Create Json payload
$data = json_encode($parameters);
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-Type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "generatePdfFromTemplate(): " . $curlError . PHP_EOL;
return;
}
if ($statusCode != 200) {
// Display request error
echo "generatePdfFromTemplate(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return;
}
$json = json_decode($result, true);
if (!empty($json["error"])) {
// Display service reported error
echo "generatePdfFromTemplate(): " . $json["message"] . PHP_EOL;
return;
}
// Get URL of generated PDF file
$resultFileUrl = $json["url"];
// Download PDF file
if (downloadFile($resultFileUrl, $destinationFile)) {
echo "Generated PDF file saved as \"" . $destinationFile . "\" file." . PHP_EOL;
}
}
function downloadFile($url, $destinationFile)
{
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Execute request
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlError = curl_error($curl);
curl_close($curl);
if ($result === false) {
// Display CURL error
echo "downloadFile(): " . $curlError . PHP_EOL;
return false;
}
if ($statusCode != 200) {
// Display request error
echo "downloadFile(): request error " . $statusCode . PHP_EOL . $result . PHP_EOL;
return false;
}
// Write the file only after a successful response so failures leave no file behind
if (file_put_contents($destinationFile, $result) === false) {
echo "downloadFile(): unable to create " . $destinationFile . PHP_EOL;
return false;
}
return true;
}
?>
{
"url": "https://pdf-temp-files.s3.amazonaws.com/97dc323f32794eae8fa6602f5bd981c1/result.pdf",
"pageCount": 1,
"error": false,
"status": 200,
"name": "result.pdf",
"remainingCredits": 60646
}
{
"error": true,
"status": 400,
"message": "Bad request. Typically due to bad input parameters or unreachable input URLs (e.g., access restrictions like login or password)."
}
{
"error": true,
"status": 401,
"message": "Unauthorized. Authentication is required and has failed or has not yet been provided."
}
{
"error": true,
"status": 402,
"message": "Not enough credits."
}
{
"error": true,
"status": 403,
"message": "Access forbidden for input URL."
}
{
"error": true,
"status": 404,
"message": "The requested resource could not be found."
}
{
"error": true,
"status": 408,
"message": "The server timed out waiting for the request."
}
{
"error": true,
"status": 429,
"message": "Too many requests in a given time period."
}
{
"error": true,
"status": 441,
"message": "Invalid Password. Password protected document."
}
{
"error": true,
"status": 442,
"message": "Input document is damaged or of incorrect type."
}
{
"error": true,
"status": 443,
"message": "Permissions. The operation is prohibited by document security settings."
}
{
"error": true,
"status": 444,
"message": "Profiles parsing error. Please ensure that the configuration is supported."
}
{
"error": true,
"status": 445,
"message": "Timeout error. For large documents, use asynchronous mode (async=true) and check status via /job/check."
}
{
"error": true,
"status": 446,
"message": "Some files required for conversion are missing."
}
{
"error": true,
"status": 447,
"message": "Invalid template."
}
{
"error": true,
"status": 448,
"message": "Invalid URL or HTML. Ensure the provided URL is valid and accessible."
}
{
"error": true,
"status": 449,
"message": "Invalid index range. Page index is out of range."
}
{
"error": true,
"status": 450,
"message": "Invalid page range specified."
}
{
"error": true,
"status": 452,
"message": "Invalid URL."
}
{
"error": true,
"status": 454,
"message": "Invalid parameters."
}
{
"error": true,
"status": 500,
"message": "Something went wrong. Please try again or contact support."
}
Try it live: PDF from HTML Template → API Tester — send a real request from your browser.
POST /v1/pdf/convert/from/html
Converts a predefined HTML template into a PDF document using its Template ID. The template must be created and saved in the HTML to PDF Templates section of the dashboard.
Request body
Attributes are case-sensitive and should be inside JSON for POST request. for example:
{ "templateId": 1, "templateData": "{ \"paid\": true }" } No query parameters accepted.Remember to ensure that request sizes are less than
4 mb in file size. For more information, see Request Size Limits.integer
required
Set ID of HTML template to be used. View and manage your templates at HTML to PDF Templates.
string
required
Set it to a string with input
JSON data (recommended) or CSV data. See Sample JSON input and Sample CSV input for more information.string
The callback URL (or Webhook) used to receive the POST data. see Webhooks & Callbacks. This is only applicable when
async is set to true.string
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.string
default:"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’.string
default:"Portrait"
Sets the document orientation. Options:
Portrait for vertical layout, and Landscape for horizontal layout.boolean
default:"true"
Set to
false to disable background colors and images are included when generating PDFs from HTML/URLstring
default:"print"
Controls how content is rendered when converting to PDF. Options:
print (uses print styles), screen (uses screen styles), none (no media type applied).boolean
default:"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.
string
Set this to can add user definable HTML for the header to be applied on every page header. The format is html.
string
Set this to can add user definable HTML for the footer to be applied on every page bottom. The format is html.
boolean
default:"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 & Callbacksstring
File name for the generated output, the input must be in string format.
integer
default:"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.
object
See Profiles for more information.
Show profiles properties
Show profiles properties
string
If you require your output as
base64 format, set this to base64string
Controls the encryption algorithm used for data encryption. See User-Controlled Encryption for more information. The available algorithms are:
AES128, AES192, AES256.string
Controls the encryption key used for data encryption. See User-Controlled Encryption for more information.
string
Controls the encryption IV used for data encryption. See User-Controlled Encryption for more information.
string
Controls the decryption algorithm used for data decryption. See User-Controlled Encryption for more information. The available algorithms are:
AES128, AES192, AES256.string
Controls the decryption key used for data decryption. See User-Controlled Encryption for more information.
string
Controls the decryption IV used for data decryption. See User-Controlled Encryption for more information.
HTML Templates
During conversion, the API performs variable substitution and built-in helper evaluation using your templateData, but does not execute any arbitrary JavaScript within the template itself. After the template is rendered into HTML, a headless browser processes the page and executes any in-page JavaScript triggered on load. External or dynamically loaded JavaScript libraries may run if accessible, but execution is not guaranteed in all environments. This separation ensures secure, predictable template handling and accurate rendering of interactive web content.
{{Mustache}} and Handlebars templating syntax. You just need to insert macros surrounded by double brackets like {{ and }}.
- Find out more about Mustache.
- Find out more about Handlebars.
{{variable1}}will be replaced withtestif you settemplateDatato{ "variable1": "test" }{{object1.variable1}}will be replaced withtestif you settemplateDatato{ "object1": { "variable1": "test" } }- Simple conditions are also supported. For example:
{{#if paid}} invoice was paid {{/if}}will show invoice was paid whentemplateDatais set to{ "paid": true }.
Handlebars
Handlebars extends Mustache with powerful features like conditional logic, loops, and custom helper functions. You can use Handlebars helpers like#if, #unless, #each (see https://handlebarsjs.com/guide/builtin-helpers.html) but you can also define your own helper functions for complex calculations and data manipulation.
Key Handlebars Features:
- Variable substitution:
{{variable}}syntax for inserting data - Conditional logic:
{{#if}}and{{#unless}}blocks for conditional rendering - Loops:
{{#each}}for iterating over arrays and objects - Nested objects: Accessing properties with dot notation like
{{company.name}} - Built-in helpers: Using Handlebars’ built-in functionality for common operations
Sample JSON input
"templateData": "{ 'paid': true, 'invoice_id': '0002', 'total': '$999.99' }"
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\" }".Sample CSV input
"templateData": "paid,invoice_id,total
true,0002,$999.99"
Header & Footer
Theheader and footer parameters can contain valid HTML markup with the following classes used to inject printing values into them:
date: formatted print datetitle: document titleurl: document locationpageNumber: current page numbertotalPages: total pages in the document
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>
Sample Header & Footer
An example with an advancedheader and footer. Note that the top and bottom page margins are important because page content may overlap the footer or header.
{
"templateId": 1,
"name": "newDocument.pdf",
"mediaType": "print",
"margins": "40px 20px 20px 20px",
"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>",
"async": false,
"templateData": "{\"paid\": true,\"invoice_id\": \"0021\",\"invoice_date\": \"August 29, 2041\",\"invoice_dateDue\": \"September 29, 2041\",\"issuer_name\": \"Sarah Connor\",\"issuer_company\": \"T-800 Research Lab\",\"issuer_address\": \"435 South La Fayette Park Place, Los Angeles, CA 90057\",\"issuer_website\": \"www.example.com\",\"issuer_email\": \"info@example.com\",\"client_name\": \"Cyberdyne Systems\",\"client_company\": \"Cyberdyne Systems\",\"client_address\": \"18144 El Camino Real, Sunnyvale, California\",\"client_email\": \"sales@example.com\",\"items\": [ { \"name\": \"T-800 Prototype Research\", \"price\": 1000.00 }, { \"name\": \"T-800 Cloud Sync Setup\", \"price\": 300.00 } ],\"discount\": 100,\"tax\": 87,\"total\": 1287,\"note\": \"Thank you for your support of advanced robotics.\"}"
}
Responses
Synchronous response
{
"url": "https://pdf-temp-files.s3.amazonaws.com/97dc323f32794eae8fa6602f5bd981c1/result.pdf",
"pageCount": 1,
"error": false,
"status": 200,
"name": "result.pdf",
"remainingCredits": 60646
}
| Field | 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 | integer | 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 |
jobId | string | Present in the initial response when async is true. |
jobId and a reserved URL that should be used only after the job succeeds. Poll it via Background Job Check. Errors return error: true with a status code and message. See the response examples and Response Codes.
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.Was this page helpful?