How to Generate PDFs in Python with LightningPDF
Generate professional PDF documents from HTML or templates using Python and the LightningPDF API.
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.
PDF generation in Python is the process of programmatically creating PDF documents from HTML, data, or templates using Python libraries or cloud APIs, commonly used for automating invoice, report, and certificate creation.
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
- Get your free API key (50 PDFs/month)
- Browse the template marketplace for ready-to-use designs
- Read the full API docs
Frequently Asked Questions
How do I generate a PDF in Python?
The simplest way to generate a PDF in Python is using the requests library with the LightningPDF API. Send a POST request with your HTML content or template variables as JSON, then decode the base64 response to get your PDF bytes. It takes about 5 lines of code.
What Python library is best for PDF generation?
For most use cases, using a cloud API like LightningPDF with the requests library is better than local libraries like ReportLab or WeasyPrint. The API handles all rendering complexity, supports full HTML and CSS, and generates PDFs in under 100 milliseconds without installing any system dependencies.
Can I batch generate PDFs with Python?
Yes, LightningPDF's batch API lets you generate up to 100 PDFs in a single API call from Python. Send an array of template data objects and receive all generated PDFs. This is significantly faster and simpler than making individual API calls in a loop.
How do I convert HTML to PDF in Python?
Send your HTML string to the LightningPDF API using Python's requests library. The API converts HTML with full CSS support, including flexbox and grid layouts, into a pixel-perfect PDF. You can also pass a URL instead of raw HTML for converting existing web pages.
Related Reading
- Generate PDFs in Node.js — Node.js integration guide
- Generate PDFs in Go — Go tutorial with invoice example
- HTML to PDF: The Complete Guide — All approaches compared
- How to Fix PDF Page Breaks — Solve page break issues
- Best PDF APIs in 2026 — Full API comparison
LightningPDF Team
Building fast, reliable PDF generation tools for developers.