Skip to main content

Template to PDF

Use a predefined or custom template and populate it using JSON data that gets passed into the request to generate high-quality and professional PDF documents such as Invoices, Receipts, Lease Agreements, and more.

Endpoints

POST /template/pdf

POST /template/pdf
https://api.cloudlayer.io/v2/template/pdf

Request types

When using templates, you have a couple of options to choose from on how you send the request. You can use an inline request, where you specify everything in the JSON data, or you can use a multipart request and send the options as JSON, the template as a file, and the data as a file.

  • Inline Request
  • Multipart Request

Inline Request

An inline request is where you send the entire request as a single JSON string. The template and data are part of the JSON string.

Multipart Request

A multipart request is where you send multiple parts of the request—also known as multipart/form-data. Which can allow for greater flexibility as you can use files or binary blobs to represent the data instead of having to base64 encode or deal with large JSON strings.

The following form fields are required:

  • options - This is where all of the parameters are defined.
  • template - The template (does not need to be base64 encoded when using multipart form data)
  • data - The data parameter
Template to PDF Example - cURL
curl --request POST \
--url 'https://api.cloudlayer.io/v2/template/pdf?=' \
--header 'Content-Type: multipart/form-data' \
--header 'x-api-key: <API-KEY>' \
--form 'options={
"name": "test",
}' \
--form 'template=@<PATH-TO-TEMPLATE>\template.njk' \
--form 'data=@\<PATH-TO-DATA>\sample-data.json'
Template to Image Example - cURL
curl --request POST \
--url 'https://api.cloudlayer.io/v2/template/image?=' \
--header 'Content-Type: multipart/form-data' \
--header 'x-api-key: <API-KEY>' \
--form 'options={
"name": "test",
}' \
--form 'template=@<PATH-TO-TEMPLATE>\template.njk' \
--form 'data=@\<PATH-TO-DATA>\sample-data.json'

Template types

There are two template types you can use with the template API.

Predefined Template

A predefined template is already created, which you choose from the PDF or Image Template Library use by providing the templateId parameter and providing the correct data parameter for the template.

Example - Predefined Template
{
"templateId": "<template-id>",
"data": "..."
}

Custom Template

A custom template is one you create yourself and pass in through the template parameter. When using a custom template, you may want to read the Templating Reference

Example Custom Template
{
"template": "PGh0bWw+CiAgPGJvZHk+CiAgICBIZWxsbyB7e25hbWV9fSEKICA8L2JvZHk+CjwvaHRtbD4=",
"data": {
"name": "Bob"
}
}

Template Parameters

Parameters that exist on Template services.

templateId

Required when the template is not specified.

The string indicating the template to use from the PDF or Image template gallery. In this example it's using the PDF Template, the same format and options are used for Image templates.

Example - templateId for Invoice PDF Template
{
"templateId": "professional-invoice",
"data": "..."
}
note

Data was left out for brevity in this example, to see a full example of data being used take a look at the data parameter.

template

Required when the templateId is not specified.

The base64 encoded HTML Nunjucks template string.
(Used for custom templates.)

string Default: ""

Template (Before it gets encoded for illustration purposes)
<html>
<body>
Hello {{name}}!
</body>
</html>

data

Required

JSON string representing the data for the template.

string Default: ""

Sample Data
{
"templateId": "professional-invoice",
"data": {
"__auto_calculate": true,
"address1": "1711 Bushnell Avenue",
"amount": null,
"bill_to_address1": "1680 Ralph Drive",
"bill_to_city": "Cleveland",
"bill_to_country": "United States",
"bill_to_fullname": "Terry G. Brown",
"bill_to_state_province_region": "OH",
"bill_to_zip_postal_code": "44114",
"city": "South Pasadena",
"company_name": "Acme Inc.",
"country": "United States",
"currency": "EUR",
"due_date": "04/04/2020",
"email": "email@gmail.com",
"invoice_date": "27 March, 2020",
"invoice_no": "000ABC123",
"items": [
{
"amount": null,
"description": "Lorem, ipsum dolor sit amet consectetur adipisicing elit. Undedeleniti minus blanditiis repudiandae provident, hic laborum eaiure doloremque ipsum, obcaecati, dicta dignissimos optio. Porrodolores voluptatum consequuntur ab doloremque?",
"quantity": 40,
"title": "Home Page",
"unit_price": 150.1
},
{
"amount": null,
"description": "Lorem, ipsum dolor sit amet consectetur adipisicing elit.",
"quantity": 40,
"title": "Home Page 2",
"unit_price": 150
},
{
"amount": null,
"description": "Lorem, ipsum dolor sit amet consectetur adipisicing elit. Undedeleniti minus blanditiis repudiandae provident.",
"quantity": 10,
"title": "Home Page 3",
"unit_price": 10
}
],
"locale": "en-GB",
"logo_href": "https://cloudlayerio.nyc3.digitaloceanspaces.com/cdn/logo1.svg",
"notes": "Lorem, ipsum dolor sit amet consectetur adipisicing elit. Undedeleniti minus blanditiis repudiandae provident, hic laborum eaiure doloremque ipsum, obcaecati, dicta dignissimos optio. Porrodolores voluptatum consequuntur ab doloremque?",
"phone_number": "555-555-5555",
"product_service_title": "Web Design Services",
"reference_no": "INV-621",
"state_province_region": "California",
"subTotal": null,
"tax_label": "Tax",
"tax_percentage": 6,
"terms": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Labore, debitis vitae autem pariatur sunt eligendi error accusantium deserunt dolorem atque beatae quasi eaque repudiandae, ex, quaerat deleniti dignissimos? Cupiditate, explicabo. dolorem atque beatae quasi eaque repudiandae, ex, quaerat deleniti dignissimos? Cupiditate, explicabo.",
"totalTax": null,
"website": "https://acmeinc.com",
"zip_postal_code": "91030"
}
}
note

Any values that are null are auto-calculated fields. If you wish to populate those fields instead, set __auto_calculate: false and pass data into the fields instead.

Base Parameters

Parameters that exist on all services.

waitUntil

When to consider the navigation has been completed and begin the conversion.

string Default: "networkidle2"

Accepted Values

  • load - consider navigation to be finished when the load event is fired.
  • domcontentloaded - consider navigation to be finsihed when the DOMContentLoaded event is fired.
  • networkidle0 - consider navigation to be finished when there are no more than 0 network connections for at least 500 ms.
  • networkidle2 - consider navigation to be finished when there are no more than 2 network connections for at least `500' ms.
{ "waitUntil": "load" }

timeout

Amount of time that Chrome is allowed to run. If exceeded, your job will terminate.

number Default: 30000ms

{ "timeout": 30000 }

delay

The amount of time in milliseconds to wait for the page to complete rendering before conversion.

number Default: 0ms

{ "delay": 1000 }

autoScroll

Will auto-scroll the page down to the very end. Helpful in forcing lazy-loaded content to load.

boolean Default: false

{ "autoScroll": true }

filename

If used with the inline: false, will set the Content-Disposition filename so that the downloaded file will assign to this value in the user's browser. For inline: true, it has no effect.

string Default: ""

{ "filename": "filename.ext" }

inline

If set to true, the Content-Disposition gets set to inline. If set to false, it gets set to attachment. See filename property if you want to set the filename value for the attachment.

boolean Default: false

{ "inline": true }

projectId

The project's id you would like the job and any assets the job generates to be a member.

string Default: ""

{ "projectId": "N77VCoAVTHHwgmUfCYlD" }

viewPort

Set the Viewport of the page before navigation.

{
"viewPort": {
"width": 1024,
"height": 768,
"deviceScaleFactor": 2
}
}

width

Page width in pixels only. Required

number Default: <null>

{
"viewPort": {
"width": 1024
}
}

height

Page height in pixels only. Required

number Default: <null>

{
"viewPort": {
"height": 768
}
}

deviceScaleFactor

Specify device scale factor (DPR). Height and Width are always required.

number Default: 1

{
"viewPort": {
"width": 640,
"height": 480,
"deviceScaleFactor": 1
}
}

isMobile

Whether the meta viewport tag is taken into account. Height and Width are always required.

boolean Default: false

{
"viewPort": {
"width": 640,
"height": 480,
"isMobile": true
}
}

hasTouch

Specifies if viewport supports touch events. Height and Width are always required.

boolean Default: false

{
"viewPort": {
"width": 640,
"height": 480,
"hasTouch": true
}
}

isLandscape

Specifies if viewport is in landscape mode. Height and Width are always required.

boolean Default: false

{
"viewPort": {
"width": 640,
"height": 480,
"isLandscape": true
}
}

timeZone

Changes the timezone of the page. See ICU's metaZones.txt for a list of supported timezone IDs.

string Default: <null>

{ "timeZone": "Europe/Rome" }

waitForSelector

Allows for more complex wait behavior to control when the Chrome rendering engine decides when a page has finished before the conversion.

selector

The selector of an element to wait for before performing the conversion.

string Default: <null>

{
"waitForSelector": {
"selector": "img"
}
}

options

The selector of an element to wait for before performing the conversion.

visible

Wait for the selector element to be present in the DOM and to be visible, i.e. to not have display:none or visibility:hidden CSS properties. Not to be combined with the hidden property.

boolean Default: false

{
"waitForSelector": {
"selector": "img",
"options": {
"visible": true
}
}
}

hidden

Wait for the selector element to be present in the DOM and to be hidden, i.e. to have display: none or visibility: hidden CSS properties. Not to be combined with the visible property.

boolean Default: false

{
"waitForSelector": {
"selector": "img",
"options": {
"hidden": true
}
}
}

timeout

Maximum amount of time to wait in milliseconds for the selector to meet the visible or hidden criteria.

number Default: 30000

visible
{
"waitForSelector": {
"selector": "img",
"options": {
"visible": true,
"timeout": 30000
}
}
}
hidden
{
"waitForSelector": {
"selector": "img",
"options": {
"hidden": true,
"timeout": 30000
}
}
}

preferCSSPageSize

Give any CSS @page size declared in the page priority over what is declared in width and height or format options.

boolean Default: false

{ "preferCSSPageSize": true }

scale

Scale of the webpage rendering. Must be between 0.1 and 2.

number Default: 0

{ "scale": 0.5 }

height

Paper height. Must be supported type of units or number.

string|number Default: <null>

{ "height": 100 }
{ "height": "1.25in" }

width

Paper width. Must be supported type of units or number.

string|number Default: <null>

{ "width": 100 }
{ "width": "1.25in" }

landscape

Paper orientation, false sets it to portrait and true to landscape.

boolean `Default: false

{ "landscape": true }

Pdf Parameters

Parameters that exist on PDF services.

generatePreview

Generates an image preview (thumbnail) of the first page of the PDF document. Storage must be enabled.

All parameters are optional, if you pass in true to generatePreview instead of options it will use defaults.

{
"width": "600",
"height": "776",
"type": "webp",
"quality": "high"
}

width

Width of the image to generate for the preview

number Optional - Either width or height must be provided. If maintainAspectRatio is being used, you may specify either one or the other.

{
"width": "300"
}

height

Height of the image to generate for the preview

number Optional - Either width or height must be provided. If maintainAspectRatio is being used, you may specify either one or the other.

 "height": "600"

type

Optional

string Default: "webp"

Type of image to generate for the preview.

Must be one of the following:

  • png
  • jpg
  • webp
{
"type": "webp"
}

maintainAspectRatio

boolean Default: true

Either true or false to indicate if the image generated should maintain aspect ratio based on width/height.

Can result in a blurry and skewed image if the aspect ratio is not maintained

{
"maintainAspectRatio": true
}

quality

string Default: ""

Required

Specifies the quality of the generated preview, has no default and must be specified if defining custom generatePreview options.

Must be one of the following:

  • low
  • medium
  • high
{
"quality": "medium"
}
info

Generating a preview can add significant processing time depending on the quality and size of the preview image and PDF document. It's important to balance quality and rendering time.

pageRanges

Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.

string Default: <null>

{ "pageRanges": "1-5" }

format

Paper format, which takes priority over width and height. Do not use with width and height. Use one or the other. Must be supported type of formats.

string Default: false

{ "format": "letter" }

margin

Paper margins.
(When using templates, the margins are all set to 0 by default.)

{
"margin": {
"top": 0,
"bottom": 0,
"left": 0,
"right": 0
}
}

top

Top paper margin, must be supported type of units.

string|number Default: "0.4in"

{
"margin": {
"top": 100
}
}

bottom

Bottom paper margin, must be supported type of units.

string|number Default: "0.39in"

{
"margin": {
"bottom": 100
}
}

left

Left paper margin, must be supported type of units.

string|number Default: "0.4in"

{
"margin": {
"left": 0
}
}

right

Left paper margin, must be supported type of units.

string|number Default: "0.39in"

{
"margin": {
"right": 0
}
}

printBackground

Print background graphics.

boolean Default: false

{ "printBackground": true }

headerTemplate

Template for the PDF header. There are two types of template styles: a basic HTML template and an HTML body extraction method.

selector

Template string if using template method type, otherwise ignored.

string Default: <null>

{ "selector": ".my-div" }

method

string Default: "text"

  • text - Uses the default text template method.
  • extract - Extracts the header from the HTML body based on the selector, encodes it, and applies styles before adding it to the PDF Header.
{ "method": "extract" }

margin

Margin that is applied to the header container. Must be supported type of margin.

string Default: <null>

{
"margin": {
"top": "100px",
"bottom": "100px"
}
}

style

CSS style that gets applied to the header container. Chrome does not support all CSS styles in the header, some values may be ignored.

string Default: <null>

{
"style": {
"width": "100%",
"border": "1px soilid red"
}
}

imageStyle

CSS style that gets applied to the header image container. Chrome does not support all CSS styles in the header, some values may be ignored.

string Default: <null>

{
"imageStyle": {
"padding-bottom": "10px",
"height": "500px",
"max-width": "75%"
}
}

Example - Extract Header Template

Html
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class="page-header-bob" style="text-align: center">
<div id="header">
<span style="font-size: 20px; color: red">Header</span>
</div>
</div>
<h1>Page 1</h1>
<div style="height: 842px"></div>
<h1>Page 2</h1>
</body>
</html>
Parameters
{
"html": "PCFET0NUWVBFIGh0bWw+CjxodG1sPgogIDxoZWFkPiA8L2hlYWQ+CiAgPGJvZHk+CiAgICA8ZGl2IGNsYXNzPSJwYWdlLWhlYWRlci1ib2IiIHN0eWxlPSJ0ZXh0LWFsaWduOiBjZW50ZXIiPgogICAgICA8ZGl2IGlkPSJoZWFkZXIiPgogICAgICAgIDxzcGFuIHN0eWxlPSJmb250LXNpemU6IDIwcHg7IGNvbG9yOiByZWQiPkhlYWRlcjwvc3Bhbj4KCiAgICAgIDwvZGl2PgogICAgPC9kaXY+CiAgICA8aDE+UGFnZSAxPC9oMT4KICAgIDxkaXYgc3R5bGU9ImhlaWdodDogODQycHgiPjwvZGl2PgogICAgPGgxPlBhZ2UgMjwvaDE+CiAgPC9ib2R5Pgo8L2h0bWw+Cg=="
"margin": {
"top": "120px"
},
"headerTemplate": {
"method": "extract",
"selector": ".page-header-bob",
"style": {
"width": "100%",
"border": "1px solid red"
}
}
}

In the above code snippet called Parameters, the HTML is a base64 encoded string of the Html example above it. In this example, you can see how the div has a class named page-header-bob. This div is the header element extracted out of the body and moved into the header.

A caveat of using headers with PDFs is that the header exists inside the margins on PDF files. So, in this example, a margin-top of 120px is applied to make room for the header element to live. Otherwise, it will be covered up and not visible. By default, when the Chrome rendering engine renders HTML that exists in a header, it uses a font size that is extremely small and not legible, so a font size of 20px gets set on the span inside the header to allow the text to be readable.

footerTemplate

Template for the PDF header. See headerTemplate for reference. Can be used identically to the headerTemplate, only difference is the property name.

{
"footerTemplate": "<...same as headerTemplate>"
}

Units

For properties that accept string unit types, the following units are valid.

Note: If the property accepts a number it defaults to pixels.

  • px - pixel
  • in - inch
  • cm - centimeter
  • mm - millimeter
px - pixel (number)
{ "width": 100 }
px - pixel
{ "width": "100px" }
in - inch
{ "width": "100in" }
cm - centimeter
{ "width": "100cm" }
mm - millimeter
{ "width": "100mm" }

Formats

The acceptable format options for PDF are valid.

  • letter: 8.5in x 11in
  • legal: 8.5in x 14in
  • tabloid: 11in x 17in
  • ledger: 17in x 11in
  • a0: 33.1in x 46.8in
  • a1: 23.4in x 33.11in
  • a2: 16.54in x 23.4in
  • a3: 11.7in x 16.54in
  • a4: 8.27in x 11.7in
  • a5: 5.83in x 8.27in
  • a6: 4.13in x 5.83in