2025-08-31 19:12:12 +02:00

101 lines
3.7 KiB
C#

using System.Collections.Generic;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace FahrzeugVerwaltung
{
public class PdfService
{
// Erstellt ein PDF mit formatierten Daten eines Fahrzeugs
public bool ErstelleFahrzeugPdf(Fahrzeug fahrzeug, string dateiPfad)
{
try
{
using var document = new Document(PageSize.A4);
PdfWriter.GetInstance(document, new FileStream(dateiPfad, FileMode.Create));
document.Open();
var titelSchrift = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16);
document.Add(new Paragraph("Fahrzeugdaten", titelSchrift)
{
Alignment = Element.ALIGN_CENTER,
SpacingAfter = 20f
});
var tabelle = new PdfPTable(2) { WidthPercentage = 80 };
tabelle.SetWidths(new float[] { 1f, 2f });
void Zeile(string text, string wert)
{
tabelle.AddCell(new PdfPCell(new Phrase(text)) { BackgroundColor = BaseColor.LIGHT_GRAY });
tabelle.AddCell(new Phrase(wert));
}
Zeile("Marke", fahrzeug.Marke);
Zeile("Modell", fahrzeug.Modell);
Zeile("Baujahr", fahrzeug.Baujahr.ToString());
Zeile("Leistung", $"{fahrzeug.Leistung} PS");
Zeile("Kilometer", fahrzeug.KilometerstandFormatiert);
Zeile("Farbe", fahrzeug.Farbe);
Zeile("Kaufpreis", fahrzeug.KaufpreisFormatiert);
Zeile("Aktueller Wert", fahrzeug.AktuellerWertFormatiert);
document.Add(tabelle);
document.Close();
return true;
}
catch
{
return false;
}
}
// Erstellt eine übersichtliche Liste aller Fahrzeuge als PDF
public bool ErstelleFahrzeuglistePdf(List<Fahrzeug> fahrzeuge, string dateiPfad)
{
try
{
using var document = new Document(PageSize.A4.Rotate());
PdfWriter.GetInstance(document, new FileStream(dateiPfad, FileMode.Create));
document.Open();
var titelSchrift = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16);
document.Add(new Paragraph("Fahrzeugliste", titelSchrift)
{
Alignment = Element.ALIGN_CENTER,
SpacingAfter = 20f
});
var tabelle = new PdfPTable(8) { WidthPercentage = 100 };
string[] ueberschriften = { "Marke", "Modell", "Baujahr", "Leistung", "Kilometer", "Kaufpreis", "Farbe", "Aktueller Wert" };
foreach (var u in ueberschriften)
{
tabelle.AddCell(new PdfPCell(new Phrase(u)) { BackgroundColor = BaseColor.LIGHT_GRAY });
}
foreach (var f in fahrzeuge)
{
tabelle.AddCell(f.Marke);
tabelle.AddCell(f.Modell);
tabelle.AddCell(f.Baujahr.ToString());
tabelle.AddCell($"{f.Leistung} PS");
tabelle.AddCell(f.KilometerstandFormatiert);
tabelle.AddCell(f.KaufpreisFormatiert);
tabelle.AddCell(f.Farbe);
tabelle.AddCell(f.AktuellerWertFormatiert);
}
document.Add(tabelle);
document.Close();
return true;
}
catch
{
return false;
}
}
}
}