PDF from HTML Template#
Create PDF’s from HTML template input.
One you have obtained a template then use the /pdf/convert/from/html API with the required templateId
& templateData
parameters defined.
Available Methods#
/templates/html#
Return all HTML templates for the current user.
Use the dashboard to manage your HTML to PDF Templates.
Method: GET
Endpoint: /v1/templates/html
Query parameters#
No query parameters accepted.
Response 2#
{
"templates": [
{
"id": 1,
"type": "system",
"title": "General Invoice Template",
"description": "sample invoice template showcasing use of Mustache templates syntax for generating invoices"
},
{
"id": 15,
"type": "user",
"title": "User Template 1",
"description": ""
}
],
"remainingCredits": 99204004,
"credits": 2
}
CURL#
curl --location --request GET 'https://api.pdf.co/v1/templates/html' \
--header 'Content-Type: application/json' \
--header 'x-api-key: '
/templates/html/:id#
Returns HTML template by template’s id.
Use the dashboard to manage your HTML to PDF Templates.
Method: GET
Endpoint: /v1/templates/html/:id
Query parameters#
No query parameters accepted.
Response 2#
{
"id": 1,
"type": "system",
"title": "General Invoice Template",
"description": "sample invoice template showcasing use of Mustache templates syntax for generating invoices",
"body": "<!doctype html>\r\n<html lang=\"en-US\">\r\n<head>\r\n<title>Invoice </title> \r\n<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css\" integrity=\"sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn\" crossorigin=\"anonymous\">\r\n</head> \r\n<body>\r\n \r\n <div style=\"border-width: 3px;border-style: solid; border-color: #008000;border-radius: 8px; color: #008000; opacity:0.4; position: absolute; z-index: 1; left:80%; top:3%; font-size: 60pt;transform: rotate(-20deg)\">\r\n PAID </div>\r\n \r\n \r\n <div class=\"container\">\r\n <div class=\"\">\r\n <div class=\"\">\r\n \r\n <!-- invoice: header begin-->\r\n <div class=\"row col-md-12\">\r\n <div class=\"col col-md-6\">\r\n <div class=\"font-weight-bold\"></div>\r\n\r\n <div class=\"\"></div>\r\n <div class=\"\"></div>\r\n <div class=\"\"></div>\r\n <div class=\"\"></div>\r\n </div>\r\n <div class=\"col col-md-6\">\r\n <div class=\"\">\r\n <div class=\"\">\r\n <span class=\"font-weight-bold\">Invoice Number:</span> \r\n </div>\r\n <div class=\"\">\r\n <span class=\"font-weight-bold\">Invoice Date:</span> \r\n </div>\r\n <div class=\"\">\r\n <span class=\"font-weight-bold\">Invoice Due Date:</span> \r\n </div>\r\n </div>\r\n </div>\r\n </div>\r\n \r\n<div class=\"row col-md-12\">\r\n <div class=\"col col-md-6\"></div>\r\n\r\n <div class=\"col col-md-6\">\r\n <div class=\"font-weight-bold footer-title\">BILL TO</div>\r\n <div class=\"\">\r\n <div class=\"\"><strong>Name:</strong> </div>\r\n <div class=\"\"><strong>Company:</strong> </div>\r\n <div class=\"\"><strong>Address:</strong> </div>\r\n <div class=\"\"><strong>Email:</strong> </div>\r\n </div>\r\n </div> \r\n </div>\r\n \r\n <div class=\"row col-md-12\">\r\n <div class=\"col col-md-12\">\r\n <table class=\"table table-striped\" cellspacing=\"0\">\r\n <thead>\r\n <tr class=\"table-head\">\r\n <th class=\"text-left\">Item</th>\r\n <th class=\"text-right\">Price</th>\r\n </tr>\r\n </thead>\r\n <tbody>\r\n \r\n <tr>\r\n <td class=\"text-left\"></td>\r\n <td class=\"text-right\"></td>\r\n </tr>\r\n \r\n </tbody>\r\n </table> \r\n </div> \r\n\r\n </div>\r\n <div class=\"row col-md-12\">\r\n <div class=\"col col-md-6\">\r\n </div>\r\n <div class=\"col col-md-6 text-right\">\r\n <div style=\"margin-bottom: 10px;\">Discount: <span class=\"amount\"></span></div>\r\n <div style=\"margin-bottom: 10px;\">Tax: <span class=\"amount\"></span></div>\r\n <div class=\"font-weight-bold footer-title\">TOTAL: <span class=\"total-amount amount font-weight-bold\"></span></div> \r\n </div>\r\n \r\n </div>\r\n </div> \r\n </div>\r\n </div>\r\n <div class=\"container text-muted\"></div>\r\n </div>\r\n</body>\r\n</html>\r\n",
"remainingCredits": 99204002,
"credits": 2
}
CURL#
curl --location --request GET 'https://api.pdf.co/v1/templates/html/1' \
--header 'Content-Type: application/json' \
--header 'x-api-key: *******************' \
--data-raw ''
Code samples#
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/bytescout/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/bytescout/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;
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)
{
// --TemplateID--
/*
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/bytescout/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
var templateId = 2;
// Data to fill the template
string templateData = File.ReadAllText(@".\invoice_data.json");
// 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);
webClient.Headers.Add("Content-Type", "application/json");
try
{
// URL for `HTML to PDF` API call
string url = Uri.EscapeUriString(string.Format(
"https://api.pdf.co/v1/pdf/convert/from/html?name={0}",
Path.GetFileName(destinationFile)));
// Prepare requests params as JSON
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("name", Path.GetFileName(destinationFile));
parameters.Add("templateId", templateId);
parameters.Add("templateData", templateData);
// Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
// Execute request
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
{
/*
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/bytescout/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();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PDF Invoice Generation Results</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
// 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"] = "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/bytescout/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
$parameters["templateId"] = 1;
// Data to fill the template
$templateData = file_get_contents("./invoice_data.json");
$parameters["templateData"] = $templateData;
// 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"] == false)
{
$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 service reported error
echo "<p>Error: " . $json["message"] . "</p>";
}
}
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>
Template Samples#
Footnotes
- 1
Supports publicly accessible links from any source, including Google Drive, Dropbox, and PDF.co Built-In Files Storage. To upload files via the API, check out the File Upload section. Note: If you experience intermittent Access Denied or Too Many Requests errors, please try adding
cache:
to enable built-in URL caching (e.g.,cache:https://example.com/file1.pdf
). For data security, you have the option to encrypt output files and decrypt input files. Learn more about user-controlled data encryption.- 2(1,2)
Main response codes as follows:
Code
Description
200
Success
400
Bad request. Typically happens because of bad input parameters, or because the input URLs can’t be reached, possibly due to access restrictions like needing a login or password.
401
Unauthorized
402
Not enough credits
445
Timeout error. To process large documents or files please use asynchronous mode (set the
async
parameter totrue
) and then check status using the /job/check endpoint. If a file contains many pages then specify a page range using thepages
parameter. The number of pages of the document can be obtained using the /pdf/info endpoint.Note
For more see the complete list of available response codes.
- 3(1,2)
PDF.co Request size: API requests do not support request sizes of more than
4
megabytes in size. Please ensure that request sizes do not exceed this limit.