Jinja2 (Python)
This guide explains how to generate an HTML string using Python's Jinja2 template engine and convert it to PDF by sending it to pdfg's API.
Technical Overview
- Create a Jinja2 template
- Pass data to the template to generate an HTML string
- Send the generated HTML string to pdfg's API to convert it to PDF
Sample
Defining the Template
{# templates/invoice.html #}
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class="invoice">
<h1>Invoice</h1>
<table>
<thead>
<tr>
<th>Item</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
{% for item in items %}
<tr>
<td>{{ item.name }}</td>
<td>{{ item.price }} USD</td>
</tr>
{% endfor %}
</tbody>
</table>
<p class="total">Total: {{ total }} USD</p>
</div>
</body>
</html>
Using the Template and Generating PDF
# generate_pdf.py
from jinja2 import Environment, FileSystemLoader
import requests
# Configure Jinja2 environment
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('invoice.html')
# Prepare data
items = [
{'name': '商品A', 'price': 1000},
{'name': '商品B', 'price': 2000},
]
total = 3000
# Generate HTML string
html = template.render(items=items, total=total)
# Request to pdfg's API
response = requests.post(
'https://api.pdfg.net/v1',
headers={
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
json={
'html': html,
'pdfOptions': {
'format': 'A4'
}
}
)
# Save PDF
if response.status_code == 200:
with open('invoice.pdf', 'wb') as f:
f.write(response.content)