Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Génération de rapports

APERTO-NOTA

Table des matières

Ateliers

Gestion d’un document contenant la flotte de navires

Solution to Exercise 1 #
import csv
from datetime import datetime
import requests
from jinja2 import Template
from xhtml2pdf import pisa

# Étape 1 : Télécharger le fichier CSV
url = "https://www.data.gouv.fr/fr/datasets/r/69d7461e-9849-4641-a5c6-fa90cee2f56b"
response = requests.get(url)
csv_content = response.content.decode('utf-8')

# Étape 2 : Lire les données CSV sans pandas
navires = []
reader = csv.DictReader(csv_content.splitlines())
for row in reader:
    try:
        longueur = float(row["longueur_hors_tout"])
        if longueur > 20:
            navires.append({
                "nom_bateau": row["nom_bateau"],
                "immatriculation": row["immatriculation"],
                "type_navire": row["type_navire"],
                "longueur_hors_tout": longueur,
                "port_d_attache": row["port_d_attache"]
            })
    except ValueError:
        continue

# Étape 3 : Garder les 20 premiers navires filtrés
navires = navires[:20]

# Étape 4 : Template HTML avec Jinja2
template_html = """
<!DOCTYPE html>
<html lang='fr'>
<head>
  <meta charset='UTF-8'>
  <title>Registre des navires</title>
  <style>
    body { font-family: Arial, sans-serif; }
    h1 { text-align: center; color: navy; }
    table { width: 100%; border-collapse: collapse; margin-top: 20px; }
    th, td { border: 1px solid #000; padding: 8px; }
    th { background-color: #f2f2f2; }
  </style>
</head>
<body>
  <h1>Registre des navires</h1>
  <p>Date : {{ date }}</p>
  <table>
    <tr>
      <th>Nom du bateau</th>
      <th>Immatriculation</th>
      <th>Type de navire</th>
      <th>Longueur hors tout (m)</th>
      <th>Port d'attache</th>
    </tr>
    {% for navire in navires %}
    <tr>
      <td>{{ navire.nom_bateau }}</td>
      <td>{{ navire.immatriculation }}</td>
      <td>{{ navire.type_navire }}</td>
      <td>{{ navire.longueur_hors_tout }}</td>
      <td>{{ navire.port_d_attache }}</td>
    </tr>
    {% endfor %}
  </table>
</body>
</html>
"""

# Étape 5 : Rendu HTML avec Jinja2
template = Template(template_html)
html_content = template.render(navires=navires, date=datetime.now().strftime("%Y-%m-%d"))

# Étape 6 : Génération du PDF avec xhtml2pdf
with open("navires.pdf", "wb") as f:
    pisa.CreatePDF(html_content, dest=f)

print("Le fichier navires.pdf a été généré avec succès.")

Utilisation de la librairie pandas

On se propose maintenant de refaire l’exercice précédent en utilisant la librairie pandas.

Solution to Exercise 2 #