Skip to main content

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.

Attributes

Attributes are case-sensitive and should be inside JSON for POST request. for example: { "url": "https://example.com/file1.pdf" }
Remember to ensure that request sizes are less than 4 mb in file size. For more information, see Request Size Limits.
AttributeTypeRequiredDefaultDescription
templateIdintegerYes-Set ID of HTML template to be used. View and manage your templates at HTML to PDF Templates.
templateDatastringYes-Set it to a string with input JSON data (recommended) or CSV data. See Sample JSON input and Sample CSV input for more information.
callbackstringNo-The callback URL (or Webhook) used to receive the POST data. see Webhooks & Callbacks. This is only applicable when async is set to true.
marginsstringNo-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.
paperSizestringNoA4Specifies 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’.
orientationstringNoPortraitSets the document orientation. Options: Portrait for vertical layout, and Landscape for horizontal layout.
printBackgroundbooleanNotrueSet to false to disable background colors and images are included when generating PDFs from HTML/URL
mediaTypestringNoprintControls how content is rendered when converting to PDF. Options: print (uses print styles), screen (uses screen styles), none (no media type applied).
DoNotWaitFullLoadbooleanNofalseControls 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.
headerstringNo-Set this to can add user definable HTML for the header to be applied on every page header. The format is html.
footerstringNo-Set this to can add user definable HTML for the footer to be applied on every page bottom. The format is html.
asyncbooleanNofalseSet 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 & Callbacks
namestringNo-File name for the generated output, the input must be in string format.
expirationintegerNo60Set 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.
profilesobjectNo-See Profiles for more information.
    outputDataFormatstringNo-If you require your output as base64 format, set this to base64
    DataEncryptionAlgorithmstringNo-Controls the encryption algorithm used for data encryption. See User-Controlled Encryption for more information. The available algorithms are: AES128, AES192, AES256.
    DataEncryptionKeystringNo-Controls the encryption key used for data encryption. See User-Controlled Encryption for more information.
    DataEncryptionIVstringNo-Controls the encryption IV used for data encryption. See User-Controlled Encryption for more information.
    DataDecryptionAlgorithmstringNo-Controls the decryption algorithm used for data decryption. See User-Controlled Encryption for more information. The available algorithms are: AES128, AES192, AES256.
    DataDecryptionKeystringNo-Controls the decryption key used for data decryption. See User-Controlled Encryption for more information.
    DataDecryptionIVstringNo-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.
Use the dashboard to manage your HTML to PDF Templates. Templates use {{Mustache}} and Handlebars templating syntax. You just need to insert macros surrounded by double brackets like {{ and }}. Some Examples of macro inside html template:
  • {{variable1}} will be replaced with test if you set templateData to { "variable1": "test" }
  • {{object1.variable1}} will be replaced with test if you set templateData to { "object1": { "variable1": "test" } }
  • Simple conditions are also supported. For example: {{#if paid}} invoice was paid {{/if}} will show invoice was paid when templateData is 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"
The header and footer parameters can contain valid HTML markup with the following classes used to inject printing values into them:
  • date: formatted print date
  • title: document title
  • url: document location
  • pageNumber: current page number
  • totalPages: total pages in the document
img: tag is supported in both the header and footer parameter, provided that the 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>
An example with an advanced header 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.\"}"
}

Query parameters

No query parameters accepted.

Responses

ParameterTypeDescription
urlstringDirect URL to the final PDF file stored in S3.
outputLinkValidTillstringTimestamp indicating when the output link will expire
pageCountintegerNumber of pages in the PDF document.
errorbooleanIndicates whether an error occurred (false means success)
statusstringStatus code of the request (200, 404, 500, etc.). For more information, see Response Codes.
namestringName of the output file
creditsintegerNumber of credits consumed by the request
remainingCreditsintegerNumber of credits remaining in the account
durationintegerTime taken for the operation in milliseconds

Example Payload

To see the request size limits, please refer to the Request Size Limits.
{
    "templateId": 1,
    "name": "newDocument.pdf",
    "mediaType": "print",
    "margins": "40px 20px 20px 20px",
    "paperSize": "Letter",
    "orientation": "Portrait",
    "printBackground": true,
    "header": "",
    "footer": "",
    "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.\"}"
}

Example Response

To see the main response codes, please refer to the Response Codes page.
{
  "url": "https://pdf-temp-files.s3.amazonaws.com/97dc323f32794eae8fa6602f5bd981c1/result.pdf",
  "pageCount": 1,
  "error": false,
  "status": 200,
  "name": "result.pdf",
  "remainingCredits": 60646
}

Code Samples

  • CURL
  • JavaScript/Node.js
  • Python
  • C#
  • Java
  • PHP
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!\"}"
}'