using Khaemhat.Application.Files; using Khaemhat.Application.Security; using Khaemhat.Infrastructure.Files; namespace Khaemhat.Application.Documents; /// /// The PDF of a document (SPEC §9.4, issue #52): A4, letterhead with logo and company data, address box, conditions, /// lines over as many pages as needed (the headings repeat), VAT summary, totals, installments, transport and signature /// boxes, notes and footer. Saved as a generated attachment of the document, so every print is a new version and /// Rigenera writes the current state after a change. /// /// The printed form of documents. /// The attachments (the logo of the company). public sealed class DocumentPdfGenerator(DocumentPrintService prints, AttachmentService attachments) : IFileGenerator { /// The code of the generator. public const string GeneratorCode = "documents.pdf"; private const double Margin = 42; private const double Bottom = 60; private static readonly PdfColor Accent = PdfColor.FromHex("#1F5F8B"); private static readonly PdfColor Muted = PdfColor.Gray(105); private static readonly PdfColor Rule = PdfColor.Gray(205); private static readonly PdfColor Band = PdfColor.Gray(238); private static readonly PdfColor Warning = PdfColor.FromHex("#B54708"); /// public string Code => GeneratorCode; /// public string TitleKey => "files.generators.document_pdf"; /// public string MediaType => PdfWriter.MediaType; /// public string Extension => ".pdf"; /// public bool Supports(string entity) => DocumentPrintService.FamilyOf(entity) is not null; /// public string FileName(FileGenerationContext context) { ArgumentNullException.ThrowIfNull(context); return Stem(context) + Extension; } /// public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); var model = await ModelAsync(context, cancellationToken).ConfigureAwait(false); await WriteAsync(model, context, output, [], cancellationToken).ConfigureAwait(false); } /// /// The courtesy copy of an e-invoice (SPEC §11.9, issue #79): the print of the document with the XML sent to the /// exchange system embedded as an associated file (structure of PDF/A-3, /AF). /// /// The document. /// The name of the XML file. /// The XML file. /// The stream that receives the PDF. /// Cancellation. /// A task. public async Task CourtesyCopyAsync(FileGenerationContext context, string xmlName, byte[] xml, Stream output, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); var model = await ModelAsync(context, cancellationToken).ConfigureAwait(false); await WriteAsync(model, context, output, [(xmlName, xml)], cancellationToken).ConfigureAwait(false); } // The file name follows the document (number and kind); without the logo, which the name does not need. private string Stem(FileGenerationContext context) { try { return prints.BuildAsync(context.Actor, context.CompanyCode, FamilyOf(context), context.EntityId).GetAwaiter().GetResult().FileStem; } catch (KeyNotFoundException) { return "documento-" + context.EntityId.ToString(System.Globalization.CultureInfo.InvariantCulture); } } private static Core.Documents.DocumentFamily FamilyOf(FileGenerationContext context) => DocumentPrintService.FamilyOf(context.Entity) ?? throw new ValidationFailedException([FileGenerationService.UnknownGeneratorError]); private Task ModelAsync(FileGenerationContext context, CancellationToken cancellationToken) => prints.BuildAsync(context.Actor, context.CompanyCode, FamilyOf(context), context.EntityId, (id, ct) => LogoAsync(context, id, ct), cancellationToken); // The logo, when it is a JPEG the actor may read; the PDF writer embeds JPEG only. private async Task LogoAsync(FileGenerationContext context, long id, CancellationToken cancellationToken) { try { await using var content = await attachments.OpenAsync(context.Actor, context.CompanyCode, id, cancellationToken).ConfigureAwait(false); if (content.Attachment.Mime != "image/jpeg") { return null; } using var buffer = new MemoryStream(); await content.Content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false); return buffer.ToArray(); } catch (Exception ex) when (ex is KeyNotFoundException or AccessDeniedException) { return null; } } private static async Task WriteAsync( DocumentPrintModel model, FileGenerationContext context, Stream output, IReadOnlyList<(string Name, byte[] Content)> embedded, CancellationToken cancellationToken) { var info = new PdfDocumentInfo { Title = model.Title + " " + model.Number, Author = model.Company.Name, Subject = model.Title + " " + model.Number + " · " + model.Party.Name, CreationDate = new DateTimeOffset(DateTime.SpecifyKind(context.Now, DateTimeKind.Utc)), }; await using var pdf = new PdfWriter(output, info, leaveOpen: true); var sheet = new Sheet(pdf, model, cancellationToken); await sheet.FirstPageAsync().ConfigureAwait(false); await sheet.LinesAsync().ConfigureAwait(false); await sheet.FooterBlocksAsync().ConfigureAwait(false); sheet.Finish(); foreach (var (name, content) in embedded) { pdf.AddAttachment(name, "application/xml", content, "Fattura elettronica " + model.Number, "Source"); } await pdf.CloseAsync(cancellationToken).ConfigureAwait(false); } // The pen on the pages: where it is, and how to go on to the next page. private sealed class Sheet(PdfWriter pdf, DocumentPrintModel model, CancellationToken cancellationToken) { // Code, description, unit, quantity, price, discounts, VAT, amount: the left edge of each column and the right end. private double[] _edges = []; private PdfPage _page = null!; private int _pages; private double _y; private double Right => _page.Width - Margin; public async Task FirstPageAsync() { await NewPageAsync(first: true).ConfigureAwait(false); } public async Task LinesAsync() { Headings(); foreach (var line in model.Lines) { var width = _edges[2] - _edges[1] - 8; var wrapped = PdfTextLayout.Wrap(line.Description, line.IsDescription ? PdfFont.HelveticaOblique : PdfFont.Helvetica, 8.5, line.IsDescription ? Right - _edges[1] - 8 : width); var height = Math.Max(1, wrapped.Count) * 11 + 5; if (_y - height < Bottom + 20) { await NewPageAsync(first: false).ConfigureAwait(false); Headings(); } var y = _y; if (!line.IsDescription) { _page.DrawText(line.Code, _edges[0] + 3, y, PdfFont.Courier, 8); _page.DrawText(line.Unit, _edges[2] + 3, y, PdfFont.Helvetica, 8.5); _page.DrawTextRight(line.Quantity, _edges[4] - 3, y, PdfFont.Helvetica, 8.5); _page.DrawTextRight(line.Price, _edges[5] - 3, y, PdfFont.Helvetica, 8.5); _page.DrawTextRight(line.Discount, _edges[6] - 3, y, PdfFont.Helvetica, 8.5); _page.DrawTextRight(line.Tax, _edges[7] - 3, y, PdfFont.Helvetica, 8.5); _page.DrawTextRight(line.Amount, _edges[8] - 3, y, PdfFont.Helvetica, 8.5); } foreach (var text in wrapped) { _page.DrawText(text, _edges[1] + 3, y, line.IsDescription ? PdfFont.HelveticaOblique : PdfFont.Helvetica, 8.5, line.IsDescription ? Muted : null); y -= 11; } _y -= height; _page.DrawLine(Margin, _y + 8, Right, _y + 8, 0.25, Rule); } _y -= 6; } public async Task FooterBlocksAsync() { foreach (var note in model.Notes) { var wrapped = PdfTextLayout.Wrap(note, PdfFont.Helvetica, 8.5, Right - Margin); await RoomAsync(wrapped.Count * 11 + 4).ConfigureAwait(false); foreach (var text in wrapped) { _page.DrawText(text, Margin, _y, PdfFont.Helvetica, 8.5); _y -= 11; } _y -= 4; } // VAT summary on the left, totals on the right, side by side. var middle = Margin + (Right - Margin) * 0.58; var summaryHeight = model.Summary is { } s ? 20 + s.Rows.Count * 13 : 0; var totalsHeight = model.Totals.Count * 14 + 8; await RoomAsync(Math.Max(summaryHeight, totalsHeight) + 10).ConfigureAwait(false); var top = _y - 4; var afterSummary = model.Summary is { } summary ? Table(summary, Margin, middle - 14, top) : top; var y = top; _page.DrawRectangle(middle, y - totalsHeight + 10, Right - middle, totalsHeight, fill: Band, stroke: Band); foreach (var row in model.Totals) { var font = row.Strong ? PdfFont.HelveticaBold : PdfFont.Helvetica; var size = row.Strong ? 11 : 8.5; if (row.Strong) { y -= 3; } _page.DrawText(row.Label, middle + 8, y, font, size, row.Strong ? Accent : null); _page.DrawTextRight(row.Value, Right - 8, y, font, size, row.Strong ? Accent : null); y -= 14; } _y = Math.Min(afterSummary, y) - 12; if (model.Installments is { } installments) { await RoomAsync(22 + installments.Rows.Count * 13).ConfigureAwait(false); _y = Table(installments, Margin, middle - 14, _y) - 12; } if (model.Transport.Count > 0) { await RoomAsync(110).ConfigureAwait(false); _y = Fields(model.Transport, 4) - 10; var width = (Right - Margin - 24) / Math.Max(1, model.Signatures.Count); for (var i = 0; i < model.Signatures.Count; i++) { var x = Margin + i * (width + 12); _page.DrawText(model.Signatures[i], x, _y, PdfFont.Helvetica, 7.5, Muted); _page.DrawLine(x, _y - 28, x + width, _y - 28, 0.5, Rule); } _y -= 40; } } public void Finish() => Foot(); private async Task RoomAsync(double height) { if (_y - height < Bottom) { await NewPageAsync(first: false).ConfigureAwait(false); } } private async Task NewPageAsync(bool first) { if (_page is not null) { Foot(); } _page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false); _pages++; var right = _page.Width - Margin; double[] widths = [62, 0, 30, 50, 62, 44, 30, 66]; var description = right - Margin - widths.Sum(); _edges = new double[9]; _edges[0] = Margin; for (var i = 0; i < widths.Length; i++) { _edges[i + 1] = _edges[i] + (i == 1 ? description : widths[i]); } _y = _page.Height - Margin; if (!first) { _page.DrawText(model.Company.Name, Margin, _y - 8, PdfFont.HelveticaBold, 9); _page.DrawTextRight(model.Title + " " + model.Number + " · " + model.Date, right, _y - 8, PdfFont.Helvetica, 9, Muted); _y -= 18; _page.DrawLine(Margin, _y, right, _y, 0.75, Accent); _y -= 16; return; } Letterhead(right); } private void Letterhead(double right) { var top = _y; var x = Margin; if (model.Logo is { } logo) { try { var info = JpegInfo.Read(logo); var image = pdf.AddJpeg(logo); const double height = 44; var width = Math.Min(130, height * info.Width / Math.Max(1, info.Height)); _page.DrawImage(image, Margin, top - height, width, height); x = Margin + width + 12; } catch (InvalidDataException) { // Not a JPEG the writer can embed: the name alone. } } var y = top - 12; _page.DrawText(model.Company.Name, x, y, PdfFont.HelveticaBold, 13, Accent); y -= 13; foreach (var line in model.Company.Lines) { _page.DrawText(PdfTextLayout.Fit(line, PdfFont.Helvetica, 7.5, right - x - 190), x, y, PdfFont.Helvetica, 7.5, Muted); y -= 9.5; } // Kind, number and date on the right; a mark for drafts, cancelled and demo documents. _page.DrawTextRight(model.Title.ToUpperInvariant(), right, top - 10, PdfFont.HelveticaBold, 9, Accent); _page.DrawTextRight(model.Number, right, top - 28, PdfFont.HelveticaBold, 16); _page.DrawTextRight(model.Date, right, top - 42, PdfFont.Helvetica, 9, Muted); if (model.Watermark is { } mark) { _page.DrawTextRight(mark.ToUpperInvariant(), right, top - 56, PdfFont.HelveticaBold, 9, Warning); } _y = Math.Min(y, top - 62) - 8; _page.DrawLine(Margin, _y, right, _y, 1, Accent); _y -= 14; // The address box on the right half, the conditions on the left. var boxLeft = Margin + (right - Margin) * 0.52; var boxTop = _y + 6; var lines = 2 + model.Party.Lines.Count; var boxHeight = lines * 11 + 14; _page.DrawRectangle(boxLeft, boxTop - boxHeight, right - boxLeft, boxHeight, stroke: Rule); var by = boxTop - 13; _page.DrawText(model.PartyLabel, boxLeft + 8, by, PdfFont.Helvetica, 7.5, Muted); if (model.Party.Code is { } code) { _page.DrawTextRight(code, right - 8, by, PdfFont.Courier, 7.5, Muted); } by -= 13; _page.DrawText(PdfTextLayout.Fit(model.Party.Name, PdfFont.HelveticaBold, 10, right - boxLeft - 16), boxLeft + 8, by, PdfFont.HelveticaBold, 10); foreach (var line in model.Party.Lines) { by -= 11; _page.DrawText(PdfTextLayout.Fit(line, PdfFont.Helvetica, 8.5, right - boxLeft - 16), boxLeft + 8, by, PdfFont.Helvetica, 8.5); } var fy = _y - 6; foreach (var field in model.Fields) { _page.DrawText(field.Label, Margin, fy, PdfFont.Helvetica, 7.5, Muted); _page.DrawText(PdfTextLayout.Fit(field.Value, PdfFont.Helvetica, 8.5, boxLeft - Margin - 100), Margin + 92, fy, PdfFont.Helvetica, 8.5); fy -= 12; } _y = Math.Min(boxTop - boxHeight, fy) - 14; } private void Headings() { _page.DrawRectangle(Margin, _y - 5, Right - Margin, 16, fill: Band, stroke: Band); for (var i = 0; i < model.LineHeaders.Count; i++) { if (i is 0 or 1 or 2) { _page.DrawText(model.LineHeaders[i], _edges[i] + 3, _y, PdfFont.HelveticaBold, 7.5); } else { _page.DrawTextRight(model.LineHeaders[i], _edges[i + 1] - 3, _y, PdfFont.HelveticaBold, 7.5); } } _y -= 17; } // A small table; returns the y under it. private double Table(PrintTable table, double left, double right, double y) { _page.DrawText(table.Title, left, y, PdfFont.HelveticaBold, 8.5, Accent); y -= 13; var width = (right - left) / table.Headers.Count; for (var i = 0; i < table.Headers.Count; i++) { Cell(table.Headers[i], left + i * width, width, y, table.Numeric[i], PdfFont.HelveticaBold, 7.5); } _page.DrawLine(left, y - 4, right, y - 4, 0.5, Rule); y -= 13; foreach (var row in table.Rows) { for (var i = 0; i < row.Count; i++) { Cell(row[i], left + i * width, width, y, table.Numeric[i], PdfFont.Helvetica, 8); } y -= 13; } return y; } private void Cell(string text, double x, double width, double y, bool numeric, PdfFont font, double size) { var fitted = PdfTextLayout.Fit(text, font, size, width - 6); if (numeric) { _page.DrawTextRight(fitted, x + width - 3, y, font, size); } else { _page.DrawText(fitted, x + 3, y, font, size); } } // Label and value pairs in columns; returns the y under them. private double Fields(IReadOnlyList fields, int columns) { var width = (Right - Margin) / columns; var y = _y; for (var i = 0; i < fields.Count; i++) { var x = Margin + (i % columns) * width; _page.DrawText(fields[i].Label, x, y, PdfFont.Helvetica, 7.5, Muted); _page.DrawText(PdfTextLayout.Fit(fields[i].Value, PdfFont.Helvetica, 8.5, width - 8), x, y - 11, PdfFont.Helvetica, 8.5); if (i % columns == columns - 1 || i == fields.Count - 1) { y -= 26; } } return y; } private void Foot() { var right = _page.Width - Margin; _page.DrawLine(Margin, 46, right, 46, 0.5, Rule); if (model.Footer is { } footer) { _page.DrawText(PdfTextLayout.Fit(footer, PdfFont.Helvetica, 7, right - Margin - 80), Margin, 34, PdfFont.Helvetica, 7, Muted); } _page.DrawTextRight(_pages.ToString(System.Globalization.CultureInfo.InvariantCulture), right, 34, PdfFont.Helvetica, 7, Muted); } } }