sostituisce pylatex con reportlab: genera PDF senza LaTeX di sistema

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 4.6 committed 2026-05-14 10:15:14 +02:00
1 parent ec799466cf
commit 777b3de338
2 files changed
+104 -85

No files matched your search

+103 -84
View File
@@ -1,7 +1,10 @@
from pathlib import Path from pathlib import Path
from pylatex import (Document, Section, Subsection, Command, Figure, from reportlab.lib.pagesizes import A4
Tabular, Math, NoEscape, Package) from reportlab.lib.units import cm
from pylatex.utils import bold from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.platypus import (SimpleDocTemplate, Paragraph, Spacer, Table,
TableStyle, Image, HRFlowable, PageBreak)
BASE = Path(__file__).parent BASE = Path(__file__).parent
@@ -50,103 +53,119 @@ INDUTTORI = [
}, },
] ]
HEADER_COLOR = colors.HexColor("#2c5f8a")
LIGHT_GRAY = colors.HexColor("#f2f2f2")
TABLE_STYLE = TableStyle([
("BACKGROUND", (0, 0), (-1, 0), HEADER_COLOR),
("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("FONTSIZE", (0, 0), (-1, 0), 10),
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, LIGHT_GRAY]),
("FONTNAME", (0, 1), (-1, -1), "Helvetica"),
("FONTSIZE", (0, 1), (-1, -1), 9),
("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#cccccc")),
("TOPPADDING", (0, 0), (-1, -1), 5),
("BOTTOMPADDING", (0, 0), (-1, -1), 5),
("LEFTPADDING", (0, 0), (-1, -1), 8),
])
def build_doc(): def build_doc():
doc = Document(geometry_options={"margin": "2.5cm"}) out = str(BASE / "report_completo.pdf")
doc = SimpleDocTemplate(out, pagesize=A4,
leftMargin=2.5*cm, rightMargin=2.5*cm,
topMargin=2.5*cm, bottomMargin=2.5*cm)
doc.packages.append(Package("booktabs")) styles = getSampleStyleSheet()
doc.packages.append(Package("graphicx")) style_title = styles["Title"]
doc.packages.append(Package("amsmath")) style_h1 = styles["Heading1"]
doc.packages.append(Package("float")) style_h2 = styles["Heading2"]
doc.packages.append(Package("caption")) style_body = styles["BodyText"]
doc.packages.append(Package("inputenc", options="utf8")) style_eq = ParagraphStyle("Equation", parent=styles["BodyText"],
fontName="Courier", fontSize=10,
leftIndent=20, spaceAfter=6)
# Titolo story = []
doc.preamble.append(Command("title", "Report Analisi Termica Forno"))
doc.preamble.append(Command("author", "Analisi IR -- Cevolani"))
doc.preamble.append(Command("date", NoEscape(r"\today")))
doc.append(NoEscape(r"\maketitle"))
# Introduzione # --- Titolo ---
with doc.create(Section("Modello di fitting")): story.append(Paragraph("Report Analisi Termica Forno", style_title))
doc.append( story.append(Paragraph("Analisi IR – Cevolani", styles["Normal"]))
"Ogni intervallo è interpolato con il modello di raffreddamento di Newton:" story.append(Spacer(1, 0.5*cm))
) story.append(HRFlowable(width="100%", thickness=1, color=HEADER_COLOR))
doc.append(Math(data=[NoEscape( story.append(Spacer(1, 0.5*cm))
r"T(t) = T_\infty + A \cdot e^{-(t - t_0)/\tau}"
)], escape=False))
doc.append(NoEscape(
r"dove $T_\infty = 22.99\,^\circ\mathrm{C}$ è la temperatura ambiente media ponderata. "
r"La regressione non lineare usa il metodo \textit{Trust Region Reflective} (TRF) "
r"di \texttt{scipy.optimize.curve\_fit}."
))
# Sezione per ogni induttore # --- Modello ---
story.append(Paragraph("Modello di fitting", style_h1))
story.append(Paragraph(
"Ogni intervallo è interpolato con il modello di raffreddamento di Newton:",
style_body))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph("T(t) = T_inf + A · exp( -(t - t0) / τ )", style_eq))
story.append(Paragraph(
"dove <b>T_inf = 22.99 °C</b> è la temperatura ambiente media ponderata. "
"La regressione non lineare usa il metodo <i>Trust Region Reflective</i> (TRF) "
"di <font name='Courier'>scipy.optimize.curve_fit</font>.",
style_body))
story.append(Spacer(1, 0.4*cm))
# --- Sezione per ogni induttore ---
for ind in INDUTTORI: for ind in INDUTTORI:
with doc.create(Section(ind["nome"])): story.append(HRFlowable(width="100%", thickness=0.5, color=colors.lightgrey))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph(ind["nome"], style_h1))
with doc.create(Subsection("Intervallo di campionamento")): # Tabella intervallo
with doc.create(Tabular("|l|l|")) as tab: story.append(Paragraph("Intervallo di campionamento", style_h2))
tab.add_hline() rows = [["Parametro", "Valore"],
tab.add_row([bold("Parametro"), bold("Valore")]) ["Inizio", f"{ind['t0']} s"],
tab.add_hline() ["Fine", f"{ind['t_end']} s"],
tab.add_row(["Inizio", f"{ind['t0']} s"]) ["Numero di punti", ind["n_punti"]]]
tab.add_row(["Fine", f"{ind['t_end']} s"])
tab.add_row(["Numero di punti", ind["n_punti"]])
if ind["zona_exc"]: if ind["zona_exc"]:
tab.add_row(["Zona esclusa (peso = 0)", ind["zona_exc"]]) rows.append(["Zona esclusa (peso = 0)", ind["zona_exc"]])
tab.add_hline() t = Table(rows, colWidths=[8*cm, 6*cm])
t.setStyle(TABLE_STYLE)
story.append(t)
story.append(Spacer(1, 0.3*cm))
with doc.create(Subsection("Equazione trovata")): # Equazione
t0 = ind["t0"] story.append(Paragraph("Equazione trovata", style_h2))
A = ind["A"] eq = (f"T(t) = 22.99 + {ind['A']} · exp( -(t - {ind['t0']}) / {ind['tau']} )")
tau = ind["tau"] story.append(Paragraph(eq, style_eq))
doc.append(Math(data=[NoEscape( story.append(Spacer(1, 0.2*cm))
rf"T(t) = 22.99 + {A} \cdot e^{{-(t - {t0}) / {tau}}}"
)], escape=False))
doc.append(NoEscape(r"\vspace{4pt}")) # Tabella parametri
with doc.create(Tabular("|l|l|l|")) as tab: param_rows = [
tab.add_hline() ["Parametro", "Valore", "Incertezza (1σ)"],
tab.add_row([bold("Parametro"), bold("Valore"), bold("Incertezza (1σ)")]) ["A", f"{ind['A']} °C", f"± {ind['A_err']} °C"],
tab.add_hline() ["τ", f"{ind['tau']} s", f"± {ind['tau_err']} s"],
tab.add_row(["A", ["R²", ind["r2"], ""],
NoEscape(rf"${ind['A']}\,^\circ\mathrm{{C}}$"), ]
NoEscape(rf"$\pm\,{ind['A_err']}\,^\circ\mathrm{{C}}$")]) t2 = Table(param_rows, colWidths=[4*cm, 6*cm, 5*cm])
tab.add_row([NoEscape(r"$\tau$"), t2.setStyle(TABLE_STYLE)
NoEscape(rf"${ind['tau']}\,\mathrm{{s}}$"), story.append(t2)
NoEscape(rf"$\pm\,{ind['tau_err']}\,\mathrm{{s}}$")]) story.append(Spacer(1, 0.3*cm))
tab.add_hline()
doc.append(NoEscape(r"\vspace{4pt}")) # Plot
doc.append(NoEscape(rf"$R^2 = {ind['r2']}$")) story.append(Paragraph("Grafico", style_h2))
img = Image(str(ind["png"]), width=14*cm, height=8.4*cm)
story.append(img)
story.append(Spacer(1, 0.5*cm))
with doc.create(Subsection("Grafico")): # --- Tabella riepilogativa ---
with doc.create(Figure(position="H")) as fig: story.append(PageBreak())
fig.add_image(str(ind["png"]), width=NoEscape(r"0.9\textwidth")) story.append(Paragraph("Riepilogo", style_h1))
fig.add_caption(f"Fit esponenziale — {ind['nome']} [{ind['intervallo']}]") summary = [["Induttore", "Intervallo [s]", "A [°C]", "τ [s]", "R²"]]
# Tabella riepilogativa
with doc.create(Section("Riepilogo")):
with doc.create(Tabular("|l|l|l|l|l|")) as tab:
tab.add_hline()
tab.add_row([bold("Induttore"), bold("Intervallo [s]"),
bold("A [°C]"), bold(NoEscape(r"$\tau$ [s]")), bold(NoEscape(r"$R^2$"))])
tab.add_hline()
for ind in INDUTTORI: for ind in INDUTTORI:
tab.add_row([ind["nome"], ind["intervallo"], summary.append([ind["nome"], ind["intervallo"],
ind["A"], ind["tau"], ind["r2"]]) ind["A"], ind["tau"], ind["r2"]])
tab.add_hline() t3 = Table(summary, colWidths=[3.5*cm, 4.5*cm, 3*cm, 3*cm, 3*cm])
t3.setStyle(TABLE_STYLE)
story.append(t3)
out = BASE / "report_completo" doc.build(story)
doc.generate_tex(str(out)) print(f"report_completo.pdf generato.")
print(f"report_completo.tex generato.")
try:
doc.generate_pdf(str(out), clean_tex=False, compiler="pdflatex")
print("report_completo.pdf generato.")
except Exception as e:
print(f"Compilazione PDF non disponibile ({e}).")
print("Installa MikTeX o TeX Live per generare il PDF da report_completo.tex.")
if __name__ == "__main__": if __name__ == "__main__":
build_doc() build_doc()
+1 -1
View File
@@ -1,4 +1,4 @@
pandas pandas
matplotlib matplotlib
scipy scipy
pylatex reportlab