OCR-FastAPI / pdf_generator.py
MISSAOUI's picture
Update pdf_generator.py
9100fe3 verified
raw
history blame
2.54 kB
from reportlab.lib.pagesizes import A5
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.lib.units import mm
def create_receipt(text, file_name):
# Nettoyage du texte source
text = text.replace('*', '').replace('#', '')
text = text.replace('Reçu', '').strip()
# Extraction des champs
lines = [l.strip() for l in text.split("\n") if l.strip()]
data_dict = {}
for line in lines:
if ":" in line:
key, val = line.split(":", 1)
data_dict[key.strip()] = val.strip()
# Récupération des informations
nom = data_dict.get("Nom", "")
adresse = data_dict.get("Adresse", "")
commande = data_dict.get("Commande", "")
prix_piece = data_dict.get("Prix par pièce", "")
prix_total = data_dict.get("Prix total", "")
date_livraison = data_dict.get("Date de livraison", "")
# Structure du PDF
doc = SimpleDocTemplate(
file_name,
pagesize=A5,
rightMargin=20,
leftMargin=20,
topMargin=20,
bottomMargin=20
)
styles = getSampleStyleSheet()
elements = []
# Titre
titre = Paragraph("<b>FACTURE</b>", styles["Title"])
elements.append(titre)
elements.append(Spacer(1, 8 * mm))
# Informations client
info_client = (
f"<b>Client :</b> {nom}<br/>"
f"<b>Adresse :</b> {adresse}<br/>"
f"<b>Date de livraison :</b> {date_livraison}<br/>"
)
elements.append(Paragraph(info_client, styles["Normal"]))
elements.append(Spacer(1, 8 * mm))
# Tableau du détail de commande
table_data = [
["Description", "Qté", "Prix unitaire", "Total"],
[commande, "", prix_piece, prix_total]
]
table = Table(table_data, colWidths=[60*mm, 15*mm, 30*mm, 30*mm])
table.setStyle(TableStyle([
("BACKGROUND", (0,0), (-1,0), colors.lightgrey),
("TEXTCOLOR", (0,0), (-1,0), colors.black),
("ALIGN", (1,1), (-1,-1), "CENTER"),
("FONTNAME", (0,0), (-1,0), "Helvetica-Bold"),
("BOTTOMPADDING", (0,0), (-1,0), 8),
("GRID", (0,0), (-1,-1), 0.5, colors.black),
]))
elements.append(table)
elements.append(Spacer(1, 12 * mm))
# Total général
total_paragraph = Paragraph(
f"<b>Total dû : {prix_total}</b>",
styles["Heading3"]
)
elements.append(total_paragraph)
# Génération PDF
doc.build(elements)