Convert HTML to PDF in Python
Convert HTML to PDF in Python using the HTML2PDFAPI REST API. Works with Django, Flask, FastAPI, and any Python framework.
Quick Start
Install the requests library and make your first API call:
pip install requests import requests
response = requests.post(
'https://html2pdfapi.com/render',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'html': '<h1>Hello World</h1>',
'format': 'pdf'
}
)
with open('output.pdf', 'wb') as f:
f.write(response.content)Convert URL to PDF
import requests
response = requests.post(
'https://html2pdfapi.com/render',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'url': 'https://example.com',
'format': 'pdf',
'options': {
'format': 'A4',
'printBackground': True
}
}
)
with open('webpage.pdf', 'wb') as f:
f.write(response.content)Django Integration
# views.py
from django.http import HttpResponse
import requests
import os
def generate_pdf(request):
html_content = render_to_string('invoice.html', {'data': invoice_data})
response = requests.post(
'https://html2pdfapi.com/render',
headers={
'Authorization': f"Bearer {os.environ['HTML2PDFAPI_KEY']}",
'Content-Type': 'application/json'
},
json={
'html': html_content,
'format': 'pdf'
}
)
return HttpResponse(
response.content,
content_type='application/pdf',
headers={'Content-Disposition': 'attachment; filename="invoice.pdf"'}
)Available Options
| Option | Type | Description |
|---|---|---|
| format | str | Output format: 'pdf', 'png', 'jpeg', 'webp' |
| html | str | HTML content to convert |
| url | str | URL to convert |
| options.format | str | Page size: 'A4', 'Letter', etc. |
| options.landscape | bool | Landscape orientation |
| options.printBackground | bool | Include background colors/images |
Other Integrations
See Use Cases
PDF generation for Django, Flask, and FastAPI
One requests call. Works with any Python web framework.