school-timetracker/backend/pdf.go

110 lines
2.7 KiB
Go

package main
import (
"fmt"
"time"
"github.com/jung-kurt/gofpdf"
)
func GenerateYearlySummaryPDF(schoolYear *SchoolYear, summary []WeeklyHours) ([]byte, error) {
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "B", 20)
title := fmt.Sprintf("Stundenjahresübersicht für Schuljahr %s", schoolYear.Name)
pdf.Cell(0, 15, title)
pdf.Ln(10)
pdf.SetFont("Arial", "", 12)
subtitle := fmt.Sprintf("%s bis %s", schoolYear.StartDate, schoolYear.EndDate)
pdf.Cell(0, 10, subtitle)
pdf.Ln(15)
pdf.SetFont("Arial", "B", 10)
pdf.SetFillColor(52, 152, 219)
pdf.SetTextColor(255, 255, 255)
colWidths := []float64{60, 40, 40, 40}
headers := []string{"Mitarbeiter", "Soll (Std.)", "Ist (Std.)", "Differenz (Std.)"}
for i, header := range headers {
pdf.CellFormat(colWidths[i], 10, header, "1", 0, "C", true, 0, "")
}
pdf.Ln(-1)
pdf.SetFont("Arial", "", 10)
pdf.SetTextColor(0, 0, 0)
fill := false
for _, entry := range summary {
if fill {
pdf.SetFillColor(240, 240, 240)
} else {
pdf.SetFillColor(255, 255, 255)
}
pdf.CellFormat(colWidths[0], 8, entry.Username, "1", 0, "L", true, 0, "")
pdf.CellFormat(colWidths[1], 8, fmt.Sprintf("%.1f", entry.YearlyTarget), "1", 0, "R", true, 0, "")
pdf.CellFormat(colWidths[2], 8, fmt.Sprintf("%.1f", entry.YearlyActual), "1", 0, "R", true, 0, "")
diffStr := fmt.Sprintf("%.1f", entry.RemainingYearly)
if entry.RemainingYearly > 0 {
pdf.SetTextColor(220, 53, 69)
} else {
pdf.SetTextColor(40, 167, 69)
}
pdf.CellFormat(colWidths[3], 8, diffStr, "1", 0, "R", true, 0, "")
pdf.SetTextColor(0, 0, 0)
pdf.Ln(-1)
fill = !fill
}
pdf.Ln(5)
pdf.SetFont("Arial", "B", 10)
totalTarget := 0.0
totalActual := 0.0
totalRemaining := 0.0
for _, entry := range summary {
totalTarget += entry.YearlyTarget
totalActual += entry.YearlyActual
totalRemaining += entry.RemainingYearly
}
pdf.SetFillColor(52, 152, 219)
pdf.SetTextColor(255, 255, 255)
pdf.CellFormat(colWidths[0], 10, "GESAMT", "1", 0, "L", true, 0, "")
pdf.CellFormat(colWidths[1], 10, fmt.Sprintf("%.1f", totalTarget), "1", 0, "R", true, 0, "")
pdf.CellFormat(colWidths[2], 10, fmt.Sprintf("%.1f", totalActual), "1", 0, "R", true, 0, "")
pdf.CellFormat(colWidths[3], 10, fmt.Sprintf("%.1f", totalRemaining), "1", 0, "R", true, 0, "")
pdf.Ln(15)
pdf.SetFont("Arial", "I", 8)
pdf.SetTextColor(128, 128, 128)
pdf.Cell(0, 10, fmt.Sprintf("Erstellt am: %s", time.Now().Format("02.01.2006 15:04")))
var buf []byte
w := &pdfWriter{buf: &buf}
err := pdf.Output(w)
if err != nil {
return nil, err
}
return buf, nil
}
type pdfWriter struct {
buf *[]byte
}
func (w *pdfWriter) Write(p []byte) (n int, err error) {
*w.buf = append(*w.buf, p...)
return len(p), nil
}