Python Integration
Learn how to generate PDFs from your Python application using the popular requests library.
Why use PixelToPdf with Python?
Python developers love PixelToPdf for its simplicity. With the requests library, you can generate professional PDFs in just a few lines of code. Perfect for data reports, invoices, certificates, and automated document workflows.
Prerequisites
- Python 3.7+ (any recent version will work)
- The requests library:
pip install requests - A PixelToPdf API key from your dashboard (free tier available)
Basic Example
This example shows the simplest way to convert a webpage to PDF. We use os.environ to securely read the API key from environment variables.
import os
import requests
response = requests.post(
'https://api.pixeltopdf.com/convert/pdf',
headers={'X-API-Key': os.environ['PIXELTOPDF_API_KEY']},
json={'source': 'https://example.com'}
)
response.raise_for_status()
with open('output.pdf', 'wb') as f:
f.write(response.content)
print('PDF saved to output.pdf')How it works: The json parameter automatically serializes the dictionary and sets the Content-Type header. The response.content contains the raw PDF bytes, which we write in binary mode ('wb').
Convert HTML String
For dynamic documents, pass your HTML directly as a string. This is ideal for generating invoices, reports, or any content you build programmatically. Triple quotes (""") make it easy to write multi-line HTML.
import os
import requests
html = """
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
h1 { color: #333; }
</style>
</head>
<body>
<h1>Hello, PixelToPdf!</h1>
<p>This PDF was generated from HTML.</p>
</body>
</html>
"""
response = requests.post(
'https://api.pixeltopdf.com/convert/pdf',
headers={'X-API-Key': os.environ['PIXELTOPDF_API_KEY']},
json={
'source': html,
'format': 'A4',
'margin': {'top': '20mm', 'bottom': '20mm', 'left': '20mm', 'right': '20mm'}
}
)
response.raise_for_status()
with open('output.pdf', 'wb') as f:
f.write(response.content)Tip: You can use Python template engines like Jinja2 to generate your HTML dynamically before sending it to PixelToPdf. The margin option accepts values in mm, cm, in, or px.
With Flask
This Flask example creates an endpoint that generates PDFs on-demand. When users visit /invoice/123, they'll download the invoice as a PDF file.
import os
import requests
from flask import Flask, Response
app = Flask(__name__)
@app.route('/invoice/<invoice_id>')
def get_invoice(invoice_id):
response = requests.post(
'https://api.pixeltopdf.com/convert/pdf',
headers={'X-API-Key': os.environ['PIXELTOPDF_API_KEY']},
json={'source': f'https://yourapp.com/invoice/{invoice_id}/html'}
)
if not response.ok:
return 'PDF generation failed', 500
return Response(
response.content,
mimetype='application/pdf',
headers={'Content-Disposition': f'attachment; filename=invoice-{invoice_id}.pdf'}
)
if __name__ == '__main__':
app.run()How it works: The Response object wraps the PDF bytes with the appropriate MIME type. The Content-Disposition header tells the browser to download the file with a specific filename instead of displaying it inline.
With Django
Django's template system makes it easy to render HTML before converting it to PDF. This view renders an invoice template with context data, then sends it to PixelToPdf for conversion.
import os
import requests
from django.http import HttpResponse
from django.template.loader import render_to_string
def download_invoice(request, invoice_id):
html = render_to_string('invoice.html', {'invoice_id': invoice_id})
response = requests.post(
'https://api.pixeltopdf.com/convert/pdf',
headers={'X-API-Key': os.environ['PIXELTOPDF_API_KEY']},
json={'source': html, 'format': 'A4'}
)
if not response.ok:
return HttpResponse('PDF generation failed', status=500)
return HttpResponse(
response.content,
content_type='application/pdf',
headers={'Content-Disposition': f'attachment; filename="invoice-{invoice_id}.pdf"'}
)Best practice: Use render_to_string() to convert Django templates to HTML strings. Store your API key in Django settings and access it via settings.PIXELTOPDF_API_KEY for better configuration management.
Error Handling
This reusable function wraps the API call with proper error handling. Custom exceptions make it easy to catch and handle specific error cases in your application logic.
import os
import requests
class PixelToPdfError(Exception):
pass
def generate_pdf(source: str) -> bytes:
response = requests.post(
'https://api.pixeltopdf.com/convert/pdf',
headers={'X-API-Key': os.environ['PIXELTOPDF_API_KEY']},
json={'source': source}
)
if response.status_code == 401:
raise PixelToPdfError('Invalid API key')
elif response.status_code == 402:
raise PixelToPdfError('No credits remaining')
elif response.status_code == 429:
raise PixelToPdfError('Rate limit exceeded')
elif not response.ok:
raise PixelToPdfError(f'PDF generation failed: {response.text}')
return response.contentImportant: The API returns different status codes for different error types: 401 for authentication issues, 402 when you need more credits, and 429 when you've hit the rate limit. Handle each appropriately in production.
Next steps
You've mastered the basics! Learn about headers, footers, page breaks, and advanced styling in our API documentation.