xhtml2pdf¶
Le module xhtml2pdf permet de convertir du contenu HTML/CSS en fichiers PDF. Il est utile pour générer des rapports, factures ou tout autre document imprimable à partir de modèles HTML.
Installation¶
pip install xhtml2pdfExemple de génération PDF¶
from xhtml2pdf import pisa
html = """
<html>
<head>
<meta charset="UTF-8">
<style>
body { font-family: Arial; }
h1 { color: navy; }
</style>
</head>
<body>
<h1>Rapport</h1>
<p>Ceci est un exemple de document PDF généré avec xhtml2pdf.</p>
</body>
</html>
"""
with open("rapport.pdf", "wb") as f:
pisa.CreatePDF(html, dest=f)Exercice¶
Solution to Exercise 1 #
from xhtml2pdf import pisa
produits = [
{"nom": "Clavier", "prix": 49.99, "description": "Clavier mécanique rétroéclairé"},
{"nom": "Souris", "prix": 29.99, "description": "Souris ergonomique sans fil"},
{"nom": "Écran", "prix": 199.99, "description": "Écran 27 pouces Full HD"}
]
html = """
<html>
<head>
<meta charset="UTF-8">
<style>
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #000; padding: 8px; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h1>Catalogue des produits</h1>
<table>
<tr><th>Nom</th><th>Prix (€)</th><th>Description</th></tr>
"""
for p in produits:
html += f"<tr><td>{p['nom']}</td><td>{p['prix']}</td><td>{p['description']}</td></tr>"
html += """
</table>
</body>
</html>
"""
with open("produits.pdf", "wb") as f:
pisa.CreatePDF(html, dest=f)