Back to Blog

How to Generate PDFs in Python with LightningPDF

Generate professional PDF documents from HTML or templates using Python and the LightningPDF API.

By LightningPDF Team ·

How to Generate PDFs in Python

Python is one of the most popular languages for automation, data processing, and web development. Here's how to generate PDFs using the LightningPDF API with Python's requests library.

Installation

pip install requests

Basic HTML to PDF

import requests
import base64

response = requests.post(
    'https://lightningpdf.dev/api/v1/pdf/generate',
    headers={
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
    },
    json={
        'html': '<h1>Invoice #2026-001</h1><p>Thank you for your business.</p>',
        'options': {
            'format': 'A4',
            'print_background': True
        }
    }
)

result = response.json()
pdf_bytes = base64.b64decode(result['data']['pdf'])

with open('output.pdf', 'wb') as f:
    f.write(pdf_bytes)

print(f"PDF generated in {result['data']['generation_time_ms']}ms")

Using Templates with Variables

response = requests.post(
    'https://lightningpdf.dev/api/v1/pdf/generate',
    headers={
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
    },
    json={
        'template_id': 'receipt-retail',
        'variables': {
            'store_name': 'Coffee Shop',
            'date': '2026-02-10',
            'items': [
                {'name': 'Latte', 'price': 4.50},
                {'name': 'Croissant', 'price': 3.00}
            ],
            'total': 7.50,
            'payment_method': 'Credit Card'
        }
    }
)

Batch Generation

Generate up to 100 PDFs in a single API call:

response = requests.post(
    'https://lightningpdf.dev/api/v1/pdf/batch',
    headers={
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
    },
    json={
        'items': [
            {
                'template_id': 'invoice-standard',
                'variables': {'invoice_number': f'INV-{i}', 'customer': f'Customer {i}'}
            }
            for i in range(1, 51)
        ]
    }
)

batch = response.json()
print(f"Queued {batch['data']['total']} jobs")

Error Handling

response = requests.post(url, headers=headers, json=payload)

if response.status_code == 200:
    # Success
    result = response.json()
    print(f"Credits remaining: {response.headers.get('X-Credits-Remaining')}")
elif response.status_code == 402:
    print("Out of credits! Upgrade at /pricing")
elif response.status_code == 429:
    print("Rate limited. Slow down.")
else:
    error = response.json()
    print(f"Error: {error['error']['message']}")

Next Steps

Ready to generate PDFs?

Start free with 50 PDFs per month. No credit card required.

Get Started Free