How to Use PDF Template with Reusable Content Blocks/Fields

This tutorial and the sample source codes explain generating a PDF using an HTML template with reusable content blocks or fields. The users can follow this python tutorial and use PDF.co’s “Convert HTML template to PDF” API to add reusable content such as header and footer to their PDF pages.

  1. PDF Converter Web API
  2. API Features
  3. How to Use PDF.co Web API to Add Header
  4. Adding Advanced Header to the PDF File
  5. Using PDF.co Web API to Add Footer
  6. Additional Customization
  7. Combined Source Code

 

PDF Template with Reusable Content Blocks/Fields

PDF Converter Web API

PDF.co provides the web API named “HTML to PDF Web API” to generate PDF pages from:

  1. HTML

The users can use this web API to create PDFs from raw HTML code.

  1. URLs

The users can integrate this web API with their existing applications or use the existing HTML pages on the web URL to convert them to PDF files.

  1. HTML templates

The users can create PDF files from the HTML templates containing variables, reusable content, conditional logic, and custom code such as barcodes using “Mustache” and “Handlebars” templates.

API Features

This web API is not limited to header and footer customization but also provides various other benefits, as mentioned in the “PDF Template with Built-in Barcode” article. However, this article only involves its usage to add reusable content to the HTML templates, such as headers and footers. Moreover, it also explores its functionality to add custom information to the PDF pages such as document title, documentation location, current page number, print date, total pages.

Endpoint Parameters

  1. HTML

It is a required parameter containing HTML code. The users can also read the HTML code from some template files using python’s built-in file reading methods and pass it to this parameter.

  1. margins

It is an optional parameter to set page margins.

  1. orientation

It is an optional parameter, set to portrait by default, to set page orientation, i.e., landscape or portrait.

  1. paperSize

It is an optional parameter to set page sizes such as A2, A3, and A4.

  1. printBackground

It is an optional parameter to disable background printing.

  1. header

It is an optional parameter to add an HTML header to the whole PDF file.

  1. footer

It is an optional parameter to add an HTML footer to the whole PDF file.

  1. async

It is an optional boolean parameter, “false” by default, to perform the task asynchronously.

  1. templateData

It is an optional parameter to insert values to the HTML macros. For instance, this article inserts the QR code’s value using this parameter.

  1. profiles

It is an optional parameter to set custom configurations.

Note: The users can read more on the API endpoints in the “PDF template with Built-in barcodes” article.

How to Use PDF.co Web API to Add Header

The following sample code demonstrates the usage of this conversion API to add a custom header to the PDF file. This python code uses the inline HTML to create a basic HTML template that uses the macros for barcode generation, thus providing a basic knowledge of using the API to add in-built barcodes. Moreover, the users can modify the barcode by modifying the “templateData” value.

The following python code adds the basic header above the QR code, which reads “My Document.”

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"

# Runs processing asynchronously. Returns Use JobId that the user may use with /job/check to check the state of the processing (possible
states: working, failed, aborted, and success). Must be one of: true,false.

Async = "False"
def main(args = None):
convertFromHTML()
def convertFromHTML():
"""Converts HTML template to PDF using PDF.co Web API"""

# Prepare requests params as JSON
# See documentation: https://apidocs.pdf.co
parameters = {}
parameters["html"] ="<div><img src=\" [[ barcode:QRCode {{variable1}}]]\" /></div> "
parameters["templateData"] = "{\"variable1\": \"12345\"}"
parameters["name"] = "result.pdf"
parameters["async"] = Async
parameters["header"]="<span style='width:100%'><spanstyle='font-size:10px;'>My Document</span>.</span>"

# Prepare URL for 'Convert from HTML' API request
url = "{}/pdf/convert/from/html".format(BASE_URL)

# Execute request and get response as JSON
response = requests.post(url, data=parameters, headers={ "x-api-key":API_KEY })

if (response.status_code == 200):
json = response.json()
print(json)
else:
print(f"Request error: {response.status_code} {response.reason}")

if (__name__ == '__main__'):
main()

 

Step-by-Step Guide

  1. The code imports the necessary modules to make an API request, such as requests.
  2. It then declares and initiates the API_Key and base URL variables needed to make the API request to PDF.co Web API. The users can get their API Ke by signing up or logging in to the PDF.co website.
  3. After it, it sets the “Async” variable to true to use its value in the API parameter, “async,” thus making an asynchronous call to the API.
  4. It defines the main method to call the “convertFromHTML” function, which it defines later in the code.
  5. The “convertFromHTML” method firstly sets the API parameters, such as HTML, templateData, and header. It then prepares the URL for the web API request and executes it to get the JSON response.
  6. If the response code is “200”, meaning, if the request was successful, it prints the JSON response on the user’s screen. Otherwise, it prints the error code and its reason for the user to rectify the request.

Output

Following is the screenshot to demonstrate the above code’s output:


Adding Advanced Header to the PDF File

Following is the sample of an advanced header that uses multiple spans and CSS styles to create a PDF file header. Also, this code teaches how to create the subheaders on either side of the PDF page.

"<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>"

Using PDF.co Web API to Add Footer

Following is the python sample code to demonstrate the use of PDF.co Web API to add a footer to the PDF page. This source code is reusing the above python code to generate a barcode and replacing the header parameter with the footer parameter. So, the code generates the output PDF file containing the QR code and the footer saying “My document.” Like, the header parameter, the users can customize this footer by adding their HTML elements to create a  custom footer for their PDF files.

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"

# Runs processing asynchronously.
Async = "False"
def main(args = None):
convertFromHTML()
def convertFromHTML():

"""Converts HTML template to PDF using PDF.co Web API"""
# Prepare requests params as JSON
# See documentation: https://apidocs.pdf.co
parameters = {}
parameters["html"] ="<div><img src=\" [[ barcode:QRCode {{variable1}}]]\" /></div> "
parameters["templateData"] = "{\"variable1\": \"12345\"}"
parameters["name"] = "result.pdf"
parameters["async"] = Async
parameters["footer"]="<span

style='width:100%;text-align:right;float:right'><spanstyle='font-size:10px;'>My Document</span>.</span>"
parameters["footer"]= "<div style='width:100%;text-align:right'><span
style='font-size:10px;margin-right:20px'>Page <spanclass='pageNumber'></span> of <span class='totalPages'></span>.</span></div>"

# Prepare URL for 'Convert from HTML' API request
url = "{}/pdf/convert/from/html".format(BASE_URL)

# Execute request and get response as JSON
response = requests.post(url, data=parameters, headers={ "x-api-key":API_KEY })

if (response.status_code == 200):
json = response.json()
print(json)
else:
print(f"Request error: {response.status_code} {response.reason}")
if (__name__ == '__main__'):
main()

Output

Below is the screenshot to demonstrate the above code’s output:

HTML Template to PDF with Web API

Note: The API added the current date at the top in the absence of any predefined header.

Additional Customization

The users can use the following in-built classes to inject the custom values into the field:

  1. date

This class prints the current date in a formatted manner.

  1. title

This class prints the document title in the HTML element.

  1. url

This class prints the output URL or the location of the document.

  1. pageNumber

This class prints the current page number of the PDF file.

  1. totalPages

This class prints the total pages in the PDF file.

Combined Source Code

Below is the source code containing the advanced version of both header and footer. This code generates the PDF file with the QR code, header, and footer. The footer section uses the built-in “pageNumber” and “totalPages” classes to print “page ‘k’ of ‘kk’ pages,” such as page 2 of 4. Similarly, the header section uses more CSS styles to customize the above subheaders.

Note: The users can comment and uncomment the code lines below to add the date, URL, or page number of the PDF file.

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"

# Runs processing asynchronously. Returns Use JobId that the user may use with /job/check to check the state of the processing (possible states: working, failed, aborted, and success). Must be one of: true,false.

Async = "False"
def main(args = None):
convertFromHTML()
def convertFromHTML():

"""Converts HTML template to PDF using PDF.co Web API"""
# Prepare requests params as JSON
# See documentation: https://apidocs.pdf.co
parameters = {}
parameters["html"] ="<div><img src=\" [[ barcode:QRCode {{variable1}}]]\" /></div> "
parameters["templateData"] = "{\"variable1\": \"12345\"}"
parameters["name"] = "result.pdf"
parameters["async"] = Async
parameters["header"]="<span style='width:100%'><span style='font-size:10px;'>My Document</span>.</span>"
# parameters["header"]= "<div style='width:100%;'><span style='font-size:10px;margin-left:20px;width:50%;float:left;color:red'>LEFT SUBHEADER</span>
<span style='font-size:8px;width:30%;float:right'>RIGHT SUBHEADER</span></div>",
# parameters["header"]="<span style='width:100%'><span style='font-size:10px;' class='url'></span>.</span>"

parameters["footer"]= "<div style='width:100%;text-align:right'><span style='font-size:10px;margin-right:20px'>Page</span>
<span class='pageNumber'></span> 
<span class='totalPages'></span>.</span></div>"

# Prepare URL for 'Convert from HTML' API request
url = "{}/pdf/convert/from/html".format(BASE_URL)
# Execute request and get response as JSON
response = requests.post(url, data=parameters, headers={ "x-api-key":API_KEY })
if (response.status_code == 200):
json = response.json()
print(json)
else:
print(f"Request error: {response.status_code} {response.reason}")
if (__name__ == '__main__'):
main()