Templates API

Templates API

Templates allow you to create reusable PDF designs with variables that can be injected at generation time. Use block-based templates for complex layouts.

Endpoints

Method Endpoint Description
POST /v1/templates Create a new template
GET /v1/templates List all templates
GET /v1/templates/:id Get template details
PUT /v1/templates/:id Update a template
DELETE /v1/templates/:id Delete a template

Create Template

POST /v1/templates

Request Body

{
  "name": "Invoice Template",
  "description": "Standard invoice layout",
  "html": "<h1>Invoice for {{customer_name}}</h1><table>{{#each items}}<tr><td>{{name}}</td><td>${{price}}</td></tr>{{/each}}</table><p>Total: ${{total}}</p>",
  "variables": {
    "customer_name": "string",
    "items": "array",
    "total": "number"
  },
  "options": {
    "format": "A4",
    "print_background": true
  }
}

Response

{
  "success": true,
  "data": {
    "template_id": "tpl_abc123",
    "name": "Invoice Template",
    "created_at": "2024-01-15T10:30:00Z"
  }
}

Template Variables

Templates support Handlebars-style variable interpolation:

Basic Variables

<h1>Hello {{name}}!</h1>
<p>Email: {{email}}</p>
{
  "template_id": "tpl_abc123",
  "variables": {
    "name": "John Doe",
    "email": "john@example.com"
  }
}

Loops

<ul>
  {{#each items}}
    <li>{{name}}: ${{price}}</li>
  {{/each}}
</ul>
{
  "variables": {
    "items": [
      { "name": "Widget", "price": 10 },
      { "name": "Gadget", "price": 20 }
    ]
  }
}

Conditionals

{{#if is_paid}}
  <p style="color: green;">PAID</p>
{{else}}
  <p style="color: red;">UNPAID</p>
{{/if}}
{
  "variables": {
    "is_paid": true
  }
}

Nested Objects

<p>{{customer.name}}</p>
<p>{{customer.address.city}}, {{customer.address.state}}</p>
{
  "variables": {
    "customer": {
      "name": "John Doe",
      "address": {
        "city": "San Francisco",
        "state": "CA"
      }
    }
  }
}

Block-Based Templates

For complex layouts, use block-based templates with predefined components:

{
  "name": "Report Template",
  "blocks": [
    {
      "type": "header",
      "content": "<h1>{{title}}</h1><p>Generated: {{date}}</p>"
    },
    {
      "type": "section",
      "title": "Summary",
      "content": "<p>{{summary}}</p>"
    },
    {
      "type": "table",
      "columns": ["Name", "Value", "Change"],
      "rows": "{{data}}"
    },
    {
      "type": "footer",
      "content": "<p>© {{year}} {{company}}</p>"
    }
  ]
}

List Templates

GET /v1/templates

Query Parameters

Parameter Type Description
page integer Page number (default: 1)
limit integer Results per page (default: 20, max: 100)
search string Search by name or description

Example

curl https://lightningpdf.dev/api/v1/templates?page=1&limit=10 \
  -H "Authorization: Bearer lpdf_your_api_key"

Response

{
  "success": true,
  "data": {
    "templates": [
      {
        "template_id": "tpl_abc123",
        "name": "Invoice Template",
        "description": "Standard invoice layout",
        "created_at": "2024-01-15T10:30:00Z",
        "updated_at": "2024-01-15T10:30:00Z"
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 10,
      "total": 1,
      "total_pages": 1
    }
  }
}

Get Template

GET /v1/templates/:id
curl https://lightningpdf.dev/api/v1/templates/tpl_abc123 \
  -H "Authorization: Bearer lpdf_your_api_key"

Response

{
  "success": true,
  "data": {
    "template_id": "tpl_abc123",
    "name": "Invoice Template",
    "description": "Standard invoice layout",
    "html": "<h1>Invoice for {{customer_name}}</h1>...",
    "variables": {
      "customer_name": "string",
      "items": "array",
      "total": "number"
    },
    "options": {
      "format": "A4",
      "print_background": true
    },
    "created_at": "2024-01-15T10:30:00Z",
    "updated_at": "2024-01-15T10:30:00Z"
  }
}

Update Template

PUT /v1/templates/:id

Request Body

{
  "name": "Updated Invoice Template",
  "html": "<h1>INVOICE</h1><p>Customer: {{customer_name}}</p>",
  "variables": {
    "customer_name": "string"
  }
}

Response

{
  "success": true,
  "data": {
    "template_id": "tpl_abc123",
    "updated_at": "2024-01-15T14:30:00Z"
  }
}

Delete Template

DELETE /v1/templates/:id
curl -X DELETE https://lightningpdf.dev/api/v1/templates/tpl_abc123 \
  -H "Authorization: Bearer lpdf_your_api_key"

Response

{
  "success": true,
  "message": "Template deleted successfully"
}

Complete Example: Invoice System

1. Create Template

import requests

API_KEY = "lpdf_your_api_key"
BASE_URL = "https://lightningpdf.dev/api/v1"

def create_invoice_template():
    html = """
    <!DOCTYPE html>
    <html>
    <head>
      <style>
        body { font-family: Arial; margin: 2cm; }
        .header { text-align: center; margin-bottom: 2cm; }
        .invoice-table { width: 100%; border-collapse: collapse; }
        .invoice-table th, .invoice-table td {
          border: 1px solid #ddd;
          padding: 8px;
        }
        .total { text-align: right; font-size: 18px; margin-top: 1cm; }
      </style>
    </head>
    <body>
      <div class="header">
        <h1>INVOICE #{{invoice_number}}</h1>
        <p>Date: {{date}}</p>
        <p>Customer: {{customer_name}}</p>
      </div>
      <table class="invoice-table">
        <thead>
          <tr>
            <th>Item</th>
            <th>Quantity</th>
            <th>Price</th>
            <th>Total</th>
          </tr>
        </thead>
        <tbody>
          {{#each items}}
          <tr>
            <td>{{description}}</td>
            <td>{{quantity}}</td>
            <td>${{price}}</td>
            <td>${{total}}</td>
          </tr>
          {{/each}}
        </tbody>
      </table>
      <div class="total">
        <p>Subtotal: ${{subtotal}}</p>
        <p>Tax ({{tax_rate}}%): ${{tax_amount}}</p>
        <p><strong>Total: ${{total}}</strong></p>
      </div>
      {{#if notes}}
      <div style="margin-top: 2cm;">
        <p><strong>Notes:</strong></p>
        <p>{{notes}}</p>
      </div>
      {{/if}}
    </body>
    </html>
    """

    response = requests.post(
        f"{BASE_URL}/templates",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "name": "Invoice Template v1",
            "description": "Standard invoice with line items and tax",
            "html": html,
            "variables": {
                "invoice_number": "string",
                "date": "string",
                "customer_name": "string",
                "items": "array",
                "subtotal": "number",
                "tax_rate": "number",
                "tax_amount": "number",
                "total": "number",
                "notes": "string"
            },
            "options": {
                "format": "Letter",
                "print_background": True
            }
        }
    )

    return response.json()["data"]["template_id"]

2. Generate Invoice

def generate_invoice(template_id, invoice_data):
    response = requests.post(
        f"{BASE_URL}/pdf/generate",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "template_id": template_id,
            "variables": invoice_data
        }
    )

    result = response.json()
    if result["success"]:
        import base64
        pdf_bytes = base64.b64decode(result["data"]["pdf"])
        return pdf_bytes
    else:
        raise Exception(result["error"]["message"])

# Usage
template_id = create_invoice_template()

invoice_data = {
    "invoice_number": "INV-2024-001",
    "date": "January 15, 2024",
    "customer_name": "Acme Corp",
    "items": [
        {"description": "Widget", "quantity": 10, "price": 25.00, "total": 250.00},
        {"description": "Gadget", "quantity": 5, "price": 50.00, "total": 250.00}
    ],
    "subtotal": 500.00,
    "tax_rate": 8.5,
    "tax_amount": 42.50,
    "total": 542.50,
    "notes": "Payment due within 30 days"
}

pdf = generate_invoice(template_id, invoice_data)
with open("invoice.pdf", "wb") as f:
    f.write(pdf)

Error Codes

Code Description
template_not_found Template ID does not exist
invalid_template Template HTML or structure is invalid
missing_variables Required variables not provided
invalid_variables Variable types don't match schema

Best Practices

  1. Version your templates: Use descriptive names like "Invoice v2" when updating
  2. Define variable schemas: Always specify variable types for validation
  3. Test with sample data: Use the preview feature before production
  4. Cache template IDs: Store template IDs in your database for faster lookups
  5. Use blocks for complex layouts: Block-based templates are easier to maintain