Link Search Menu Expand Document

Generate PDF Invoice From HTML Template - Python

PDF from HTML template (Mustache or HandleBars style) sample in Python demonstrating ‘Generate PDF Invoice From HTML Template’
import os
import  json
import requests # pip install requests

# The authentication key (API Key).
# Get your own by registering at
API_KEY = "***********************************************"

# Base URL for Web API requests

# HTML template
file_read = open(".\\invoice_template.html", mode='r')
Template =

# Data to fill the template
file_read = open(".\\invoice_data.json", mode='r')
TemplateData = json.dumps(

# Destination PDF file name
DestinationFile = ".\\result.pdf"

def main(args = None):
    GeneratePDFFromTemplate(Template, TemplateData, DestinationFile)

def GeneratePDFFromTemplate(template, templateData, destinationFile):
    """Converts HTML to PDF using Web API"""

    data = {
        'templateData': templateData,
        'html': template

    # Prepare URL for 'HTML To PDF' API request
    url = "{}/pdf/convert/from/html?name={}".format(

    # Execute request and get response as JSON

    response =, 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:
                print(f"Result file saved as \"{destinationFile}\" file.")
                print(f"Request error: {response.status_code} {response.reason}")
            # Show service reported error
        print(f"Request error: {response.status_code} {response.reason}")

if __name__ == '__main__':
    "number": "1234567",
    "date": "April 30, 2016",
    "from": "Acme Inc., City, Street 3rd , +1 888 123-456,",
    "to": "Food Delivery Inc., New York, Some Street, 42",
    "lines": [{
        "title": "Setting up new web-site",
        "quantity": 3,
        "price": 50
    }, {
        "title": "Configuring mail server and mailboxes",
        "quantity": 5,
        "price": 50
<!DOCTYPE html>
<html xmlns="" lang="" xml:lang="">

	<title>Invoice {{ number}}</title>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
	<style type="text/css">
		.invoice-title h2,
		.invoice-title h3 {
			display: inline-block;
		.table > tbody > tr > .no-line {
			border-top: none;
		.table > thead > tr > .thick-line {
			border-bottom: 2px solid;
			border-bottom-color: #888888;
		.table > tbody > tr > .thick-line {
			border-top: 2px solid;
			border-top-color: #888888;
	<script type="text/javascript">
		Handlebars.registerHelper('getTotal', function(quantity, price) {
			var total = quantity * price;
			return total;
		Handlebars.registerHelper('getTotalLines', function(lines) {
			var total = 0;
			lines.forEach(function(line) {
				total += line.quantity * line.price;
			return total;

		Handlebars.registerHelper("formatDate", function(timestamp) {
			var date = new Date(timestamp);
			return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes();

	<div class="container">
		<div class="row">
			<div class="col-xs-12">
				<div class="invoice-title">
					<h2>Invoice #{{ number }}</h2>

				<div class="row">
					<div class="col-xs-12">
	    					<strong>Date:</strong> {{ formatDate date }}

				<div class="row">
					<div class="col-xs-12">
	        				<strong>From:</strong> {{ from }}
					<div class="col-xs-12">
	        				<strong>To:</strong> {{ to }}

		<div class="row">
			<div class="col-md-12">
				<div class="panel panel-default">
					<table class="table table-condensed">
							<tr class="active">
								<td class="thick-line"><strong>Service</strong></td>
								<td class="thick-line"><strong>Quantity</strong></td>
								<td class="text-center thick-line"><strong>Price</strong></td>
								<td class="text-right thick-line"><strong>Sub-Total</strong></td>
							<!-- foreach ($order->lineItems as $line) or some such thing here -->
							{{#each lines}}
								<td class="text-center">${{price}}</td>
								<td class="text-right">{{ getTotal quantity price }}</td>

								<td class="thick-line"></td>
								<td colspan='3' class="thick-line text-right"><strong>Total Due: ${{ getTotalLines lines}}</strong></td>


				<div class='text-left'>
					<strong>Terms:</strong> Due on receipt.


				<div class='text-left'>
					Thank you for your business!


</html> Web API: the Web API with a set of tools for documents manipulation, data conversion, data extraction, splitting and merging of documents. Includes image recognition, built-in OCR, barcode generation and barcode decoders to decode bar codes from scans, pictures and pdf.

Get your API key here!

Download Source Code (.zip)

return to the previous page explore PDF from HTML template (Mustache or HandleBars style) endpoint