feat: attachments, file store and in-house PDF/CSV/XLSX/ZIP writers (#34)

Documents need attachments and generated files (SPEC 9.4) before the UI of
M3 can show them, and the spec forbids external libraries for PDF and
spreadsheets.

- VolumeFileStore keeps files under <data>/files/<COMPANY>/<yyyy>/<guid>,
  writing a .part file in the same folder with size limit and SHA-256, then
  quota and scanner checks (IFileScanner hook, no-op by default).
- attachments table (migration 007) with kind, version series, lock, trash
  and the uploading user; AttachmentService uploads, adds generated files as
  the next version, lists, opens, zips, locks, trashes, restores and purges
  after 30 days (new system job system.attachments-trash).
- FileGenerationService runs IFileGenerator implementations into the store;
  three generators for the fictitious test document (PDF, CSV, XLSX).
- CsvWriter (Italian Excel defaults, formula-injection guard), XlsxWriter,
  ZipStreamWriter and PdfWriter (standard Type1 fonts, WinAnsi, AFM widths,
  JPEG, Flate, xref) only write asynchronously, so they can stream to an
  HTTP response.
- ADR 0021 records versioning, storage layout, PDF scope and CSV defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 18:06:48 +01:00
1 parent cf6f849cc1
commit b341ade9e9
26 files changed
+5319 -2

No files matched your search

@@ -0,0 +1,82 @@
namespace Khaemhat.Infrastructure.Files;
/// <summary>
/// Sits between <see cref="System.IO.Compression.ZipArchive"/> and an output that refuses synchronous writes (an
/// ASP.NET Core response). The archive still writes some parts synchronously (entry trailers on dispose, the central
/// directory): those bytes are kept here and sent with the next asynchronous call or <see cref="DrainAsync"/>, while
/// the bulk of the data, written asynchronously, goes straight through. Memory stays bounded by the small synchronous
/// pieces, so archives are still streamed.
/// </summary>
/// <param name="output">The real output.</param>
internal sealed class AsyncOutputBuffer(Stream output) : Stream
{
private readonly MemoryStream _pending = new();
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
/// <summary>Sends the bytes written synchronously to the output.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DrainAsync(CancellationToken cancellationToken = default)
{
if (_pending.Length > 0)
{
await output.WriteAsync(_pending.GetBuffer().AsMemory(0, (int)_pending.Length), cancellationToken).ConfigureAwait(false);
_pending.SetLength(0);
}
}
public override void Write(byte[] buffer, int offset, int count) => _pending.Write(buffer, offset, count);
public override void Write(ReadOnlySpan<byte> buffer) => _pending.Write(buffer);
public override void WriteByte(byte value) => _pending.WriteByte(value);
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
await DrainAsync(cancellationToken).ConfigureAwait(false);
await output.WriteAsync(buffer, cancellationToken).ConfigureAwait(false);
}
/// <summary>Does nothing: synchronous flushes would reach the output synchronously.</summary>
public override void Flush()
{
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
await DrainAsync(cancellationToken).ConfigureAwait(false);
await output.FlushAsync(cancellationToken).ConfigureAwait(false);
}
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
protected override void Dispose(bool disposing)
{
if (disposing)
{
_pending.Dispose();
}
base.Dispose(disposing);
}
}
@@ -0,0 +1,310 @@
using System.Globalization;
using System.Text;
namespace Khaemhat.Infrastructure.Files;
/// <summary>How numbers and dates are written in a CSV file.</summary>
public enum CsvNumberFormat
{
/// <summary>Italian Excel: decimal comma (<c>1234,5</c>), dates <c>dd/MM/yyyy</c>, booleans <c>VERO</c>/<c>FALSO</c>.</summary>
Italian = 0,
/// <summary>Machine readable: decimal point (<c>1234.5</c>), ISO 8601 dates, booleans <c>true</c>/<c>false</c>.</summary>
Invariant = 1,
}
/// <summary>The options of a <see cref="CsvWriter"/>. The defaults suit Excel in Italian (ADR 0021).</summary>
public sealed record CsvOptions
{
/// <summary>The field separator: <c>;</c> by default, because Italian Excel uses the comma for decimals.</summary>
public char Separator { get; init; } = ';';
/// <summary>Whether the file starts with the UTF-8 byte order mark, which Excel needs to read accented letters.</summary>
public bool WriteByteOrderMark { get; init; } = true;
/// <summary>How numbers, dates and booleans are formatted.</summary>
public CsvNumberFormat NumberFormat { get; init; } = CsvNumberFormat.Italian;
/// <summary>
/// Whether text cells that a spreadsheet would read as a formula (starting with <c>=</c>, <c>+</c>, <c>-</c>,
/// <c>@</c>, tab or carriage return) get a leading apostrophe (CSV injection, OWASP). Numbers are never changed.
/// </summary>
public bool ProtectFormulas { get; init; } = true;
/// <summary>The line terminator: CRLF as RFC 4180 says.</summary>
public string NewLine { get; init; } = "\r\n";
/// <summary>The Italian Excel defaults.</summary>
public static CsvOptions Italian { get; } = new();
/// <summary>Comma separator, invariant numbers, no byte order mark: for other programs.</summary>
public static CsvOptions Invariant { get; } = new() { Separator = ',', NumberFormat = CsvNumberFormat.Invariant, WriteByteOrderMark = false };
}
/// <summary>
/// Writes CSV files (RFC 4180) row by row (SPEC §2, §9.4). Fields with separator, quotes or line breaks are quoted and
/// quotes doubled. Rows are buffered in memory and written to the stream when the buffer grows past a few KB: use the
/// <c>Async</c> methods when the stream is an HTTP response, where synchronous writes are not allowed.
/// </summary>
/// <example>
/// <code>
/// await using var csv = new CsvWriter(response.Body);
/// await csv.WriteRowAsync(["Codice", "Descrizione", "Importo"]);
/// await csv.WriteRowAsync(["A1", "Vite M4", 12.5m]);
/// </code>
/// </example>
public sealed class CsvWriter : IDisposable, IAsyncDisposable
{
private const int FlushThreshold = 16 * 1024;
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
private static readonly UTF8Encoding Utf8 = new(encoderShouldEmitUTF8Identifier: false);
private readonly Stream _output;
private readonly bool _leaveOpen;
private readonly StringBuilder _buffer = new();
private bool _rowHasFields;
private bool _preambleWritten;
private bool _disposed;
/// <summary>Creates a writer.</summary>
/// <param name="output">The stream that receives the file.</param>
/// <param name="options">The options; <see langword="null"/> for <see cref="CsvOptions.Italian"/>.</param>
/// <param name="leaveOpen">Whether to leave <paramref name="output"/> open on dispose.</param>
public CsvWriter(Stream output, CsvOptions? options = null, bool leaveOpen = false)
{
ArgumentNullException.ThrowIfNull(output);
_output = output;
_leaveOpen = leaveOpen;
Options = options ?? CsvOptions.Italian;
if (Options.Separator is '"' or '\r' or '\n')
{
throw new ArgumentException("The separator cannot be a quote or a line break.", nameof(options));
}
}
/// <summary>The options.</summary>
public CsvOptions Options { get; }
/// <summary>The number of rows completed.</summary>
public long RowCount { get; private set; }
/// <summary>Formats a text field: formula protection, then quoting when needed.</summary>
/// <param name="value">The text.</param>
/// <param name="options">The options.</param>
/// <returns>The field as written in the file.</returns>
public static string EscapeText(string? value, CsvOptions options)
{
ArgumentNullException.ThrowIfNull(options);
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
if (options.ProtectFormulas && value[0] is '=' or '+' or '-' or '@' or '\t' or '\r')
{
value = "'" + value;
}
return Quote(value, options.Separator);
}
/// <summary>Formats a value as it would be written (numbers and dates by <see cref="CsvOptions.NumberFormat"/>).</summary>
/// <param name="value">The value.</param>
/// <param name="options">The options.</param>
/// <returns>The field as written in the file.</returns>
public static string FormatValue(object? value, CsvOptions options)
{
ArgumentNullException.ThrowIfNull(options);
var culture = options.NumberFormat == CsvNumberFormat.Italian ? Italian : CultureInfo.InvariantCulture;
var italian = options.NumberFormat == CsvNumberFormat.Italian;
var text = value switch
{
null => null,
string s => s,
bool b => italian ? (b ? "VERO" : "FALSO") : (b ? "true" : "false"),
DateOnly d => d.ToString(italian ? "dd/MM/yyyy" : "yyyy-MM-dd", CultureInfo.InvariantCulture),
DateTime d when d.TimeOfDay == TimeSpan.Zero => d.ToString(italian ? "dd/MM/yyyy" : "yyyy-MM-dd", CultureInfo.InvariantCulture),
DateTime d => d.ToString(italian ? "dd/MM/yyyy HH:mm:ss" : "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture),
DateTimeOffset d => d.ToString(italian ? "dd/MM/yyyy HH:mm:ss" : "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture),
decimal m => m.ToString("0.############################", culture),
double x when double.IsFinite(x) => x.ToString("0.###############", culture),
float x when float.IsFinite(x) => x.ToString("0.#######", culture),
double or float => string.Empty,
IFormattable f => f.ToString(null, culture),
_ => value.ToString(),
};
// Only text can carry a formula: numbers, dates and booleans are written as they are.
return value is string or char or Enum || value is not IFormattable and not bool
? EscapeText(text, options)
: Quote(text ?? string.Empty, options.Separator);
}
/// <summary>Adds a field to the current row.</summary>
/// <param name="value">Text, number, date, boolean or <see langword="null"/> (empty field).</param>
/// <returns>This writer.</returns>
public CsvWriter WriteField(object? value)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_rowHasFields)
{
_buffer.Append(Options.Separator);
}
_buffer.Append(FormatValue(value, Options));
_rowHasFields = true;
return this;
}
/// <summary>Ends the current row; writes to the stream synchronously when the buffer is large.</summary>
public void EndRow()
{
CompleteRow();
if (_buffer.Length >= FlushThreshold)
{
Flush();
}
}
/// <summary>Ends the current row; writes to the stream when the buffer is large.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async ValueTask EndRowAsync(CancellationToken cancellationToken = default)
{
CompleteRow();
if (_buffer.Length >= FlushThreshold)
{
await FlushAsync(cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Writes a whole row (synchronous stream).</summary>
/// <param name="values">The fields.</param>
public void WriteRow(params IEnumerable<object?> values)
{
ArgumentNullException.ThrowIfNull(values);
foreach (var value in values)
{
WriteField(value);
}
EndRow();
}
/// <summary>Writes a whole row.</summary>
/// <param name="values">The fields.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public ValueTask WriteRowAsync(IEnumerable<object?> values, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(values);
foreach (var value in values)
{
WriteField(value);
}
return EndRowAsync(cancellationToken);
}
/// <summary>Writes the buffered rows to the stream synchronously.</summary>
public void Flush()
{
var bytes = TakeBytes();
if (bytes.Length > 0)
{
_output.Write(bytes);
}
_output.Flush();
}
/// <summary>Writes the buffered rows to the stream.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task FlushAsync(CancellationToken cancellationToken = default)
{
var bytes = TakeBytes();
if (bytes.Length > 0)
{
await _output.WriteAsync(bytes, cancellationToken).ConfigureAwait(false);
}
await _output.FlushAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Ends a pending row, writes the buffer synchronously and closes the stream unless left open.</summary>
public void Dispose()
{
if (_disposed)
{
return;
}
if (_rowHasFields)
{
CompleteRow();
}
Flush();
_disposed = true;
if (!_leaveOpen)
{
_output.Dispose();
}
}
/// <summary>Ends a pending row, writes the buffer and closes the stream unless left open.</summary>
/// <returns>A task.</returns>
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
if (_rowHasFields)
{
CompleteRow();
}
await FlushAsync().ConfigureAwait(false);
_disposed = true;
if (!_leaveOpen)
{
await _output.DisposeAsync().ConfigureAwait(false);
}
}
private static string Quote(string value, char separator)
{
var needsQuotes = value.Length > 0
&& (value.Contains(separator, StringComparison.Ordinal) || value.AsSpan().IndexOfAny("\"\r\n") >= 0
|| char.IsWhiteSpace(value[0]) || char.IsWhiteSpace(value[^1]));
return needsQuotes ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value;
}
private void CompleteRow()
{
ObjectDisposedException.ThrowIf(_disposed, this);
_buffer.Append(Options.NewLine);
_rowHasFields = false;
RowCount++;
}
private byte[] TakeBytes()
{
var preamble = !_preambleWritten && Options.WriteByteOrderMark ? Encoding.UTF8.Preamble.ToArray() : [];
_preambleWritten = true;
if (_buffer.Length == 0 && preamble.Length == 0)
{
return [];
}
var text = _buffer.ToString();
_buffer.Clear();
var bytes = new byte[preamble.Length + Utf8.GetByteCount(text)];
preamble.CopyTo(bytes, 0);
Utf8.GetBytes(text, 0, text.Length, bytes, preamble.Length);
return bytes;
}
}
@@ -0,0 +1,317 @@
using System.Text;
namespace Khaemhat.Infrastructure.Files;
/// <summary>
/// The standard Type1 fonts every PDF reader has (PDF 1.7 §9.6.2.2), with <c>WinAnsiEncoding</c> so that Italian
/// letters and the euro sign print. Symbol and ZapfDingbats are not offered: they have no Latin encoding.
/// </summary>
public enum PdfFont
{
/// <summary>Helvetica.</summary>
Helvetica = 0,
/// <summary>Helvetica bold.</summary>
HelveticaBold = 1,
/// <summary>Helvetica oblique.</summary>
HelveticaOblique = 2,
/// <summary>Helvetica bold oblique.</summary>
HelveticaBoldOblique = 3,
/// <summary>Times roman.</summary>
TimesRoman = 4,
/// <summary>Times bold (measured with the Times roman widths).</summary>
TimesBold = 5,
/// <summary>Times italic (measured with the Times roman widths).</summary>
TimesItalic = 6,
/// <summary>Times bold italic (measured with the Times roman widths).</summary>
TimesBoldItalic = 7,
/// <summary>Courier: every character is 600/1000 em wide.</summary>
Courier = 8,
/// <summary>Courier bold.</summary>
CourierBold = 9,
/// <summary>Courier oblique.</summary>
CourierOblique = 10,
/// <summary>Courier bold oblique.</summary>
CourierBoldOblique = 11,
}
/// <summary>
/// Text measuring and line breaking for the standard fonts, from the Adobe font metrics (AFM) widths in thousandths of
/// an em, and the <c>WinAnsiEncoding</c> (Windows-1252) used to write text. Helvetica, Helvetica bold and Times roman
/// widths are exact; the Times bold and italic faces reuse the roman widths (a close approximation); Courier is fixed
/// width.
/// </summary>
public static class PdfTextLayout
{
// Widths for codes 32..126.
private static readonly int[] HelveticaAscii =
[
278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278,
556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556,
1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778,
667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556,
333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556,
556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584,
];
private static readonly int[] HelveticaBoldAscii =
[
278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278,
556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611,
975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778,
667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556,
333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611,
611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584,
];
private static readonly int[] TimesAscii =
[
250, 333, 408, 500, 500, 833, 778, 180, 333, 333, 500, 564, 250, 333, 250, 278,
500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 564, 564, 564, 444,
921, 722, 667, 667, 722, 611, 556, 722, 722, 333, 389, 722, 611, 889, 722, 722,
556, 722, 667, 556, 611, 722, 722, 944, 722, 722, 611, 333, 278, 333, 469, 500,
333, 444, 500, 444, 500, 444, 333, 500, 500, 278, 278, 500, 278, 778, 500, 500,
500, 500, 333, 389, 278, 500, 500, 722, 500, 500, 444, 480, 200, 480, 541,
];
// Widths for codes 128..159 (0 = not defined in WinAnsiEncoding).
private static readonly int[] HelveticaWin =
[
556, 0, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0,
0, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 0, 500, 667,
];
private static readonly int[] HelveticaBoldWin =
[
556, 0, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0,
0, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 0, 500, 667,
];
private static readonly int[] TimesWin =
[
500, 0, 333, 500, 444, 1000, 500, 500, 333, 1000, 556, 333, 889, 0, 611, 0,
0, 333, 333, 444, 444, 350, 500, 1000, 333, 980, 389, 333, 722, 0, 444, 722,
];
// Widths for codes 160..255.
private static readonly int[] HelveticaLatin =
[
278, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 333, 737, 333,
400, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611,
667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278,
722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611,
556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278,
556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500,
];
private static readonly int[] HelveticaBoldLatin =
[
278, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 333, 737, 333,
400, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611,
722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278,
722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611,
556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278,
611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556, 611, 556,
];
private static readonly int[] TimesLatin =
[
250, 333, 500, 500, 500, 500, 200, 500, 333, 760, 276, 500, 564, 333, 760, 333,
400, 564, 300, 300, 333, 500, 453, 250, 333, 300, 310, 500, 750, 750, 750, 444,
722, 722, 722, 722, 722, 722, 889, 667, 611, 611, 611, 611, 333, 333, 333, 333,
722, 722, 722, 722, 722, 722, 722, 564, 722, 722, 722, 722, 722, 722, 556, 500,
444, 444, 444, 444, 444, 444, 667, 444, 444, 444, 444, 444, 278, 278, 278, 278,
500, 500, 500, 500, 500, 500, 500, 564, 500, 500, 500, 500, 500, 500, 500, 500,
];
// Full tables for codes 0..255.
private static readonly int[] Helvetica = Table(HelveticaAscii, HelveticaWin, HelveticaLatin);
private static readonly int[] HelveticaBold = Table(HelveticaBoldAscii, HelveticaBoldWin, HelveticaBoldLatin);
private static readonly int[] Times = Table(TimesAscii, TimesWin, TimesLatin);
// Unicode to WinAnsiEncoding for the codes 128..159 that differ from Latin-1.
private static readonly Dictionary<char, byte> WinAnsiSpecials = new()
{
['€'] = 0x80, ['‚'] = 0x82, ['ƒ'] = 0x83, ['„'] = 0x84, ['…'] = 0x85, ['†'] = 0x86, ['‡'] = 0x87, ['ˆ'] = 0x88,
['‰'] = 0x89, ['Š'] = 0x8A, ['‹'] = 0x8B, ['Œ'] = 0x8C, ['Ž'] = 0x8E, ['‘'] = 0x91, ['’'] = 0x92, ['“'] = 0x93,
['”'] = 0x94, ['•'] = 0x95, ['–'] = 0x96, ['—'] = 0x97, ['˜'] = 0x98, ['™'] = 0x99, ['š'] = 0x9A, ['›'] = 0x9B,
['œ'] = 0x9C, ['ž'] = 0x9E, ['Ÿ'] = 0x9F,
};
/// <summary>The PostScript name of a font, as written in <c>/BaseFont</c>.</summary>
/// <param name="font">The font.</param>
/// <returns>The name, for example <c>Helvetica-Bold</c>.</returns>
public static string BaseFontName(PdfFont font) => font switch
{
PdfFont.Helvetica => "Helvetica",
PdfFont.HelveticaBold => "Helvetica-Bold",
PdfFont.HelveticaOblique => "Helvetica-Oblique",
PdfFont.HelveticaBoldOblique => "Helvetica-BoldOblique",
PdfFont.TimesRoman => "Times-Roman",
PdfFont.TimesBold => "Times-Bold",
PdfFont.TimesItalic => "Times-Italic",
PdfFont.TimesBoldItalic => "Times-BoldItalic",
PdfFont.Courier => "Courier",
PdfFont.CourierBold => "Courier-Bold",
PdfFont.CourierOblique => "Courier-Oblique",
PdfFont.CourierBoldOblique => "Courier-BoldOblique",
_ => throw new ArgumentOutOfRangeException(nameof(font), font, "Unknown font."),
};
/// <summary>
/// Encodes text in <c>WinAnsiEncoding</c>: ASCII, Latin-1 letters (àèéìòù...), the euro sign and the typographic
/// quotes and dashes. Line breaks and tabs become spaces; characters the encoding lacks become <c>?</c>.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>One byte per character.</returns>
public static byte[] EncodeWinAnsi(string? text)
{
if (string.IsNullOrEmpty(text))
{
return [];
}
var bytes = new byte[text.Length];
for (var i = 0; i < text.Length; i++)
{
bytes[i] = ToWinAnsi(text[i]);
}
return bytes;
}
/// <summary>The width of a character code in thousandths of an em.</summary>
/// <param name="code">The <c>WinAnsiEncoding</c> code.</param>
/// <param name="font">The font.</param>
/// <returns>The width.</returns>
public static int GlyphWidth(byte code, PdfFont font) => font switch
{
PdfFont.Helvetica or PdfFont.HelveticaOblique => Helvetica[code],
PdfFont.HelveticaBold or PdfFont.HelveticaBoldOblique => HelveticaBold[code],
PdfFont.TimesRoman or PdfFont.TimesBold or PdfFont.TimesItalic or PdfFont.TimesBoldItalic => Times[code],
_ => code >= 32 ? 600 : 0,
};
/// <summary>The width of a text in points.</summary>
/// <param name="text">The text.</param>
/// <param name="font">The font.</param>
/// <param name="size">The font size in points.</param>
/// <returns>The width.</returns>
public static double Measure(string? text, PdfFont font, double size)
{
var total = 0;
foreach (var code in EncodeWinAnsi(text))
{
total += GlyphWidth(code, font);
}
return total * size / 1000.0;
}
/// <summary>
/// Breaks a text into lines no wider than <paramref name="maxWidth"/>: at line breaks, then between words; a word
/// longer than a line is cut.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="font">The font.</param>
/// <param name="size">The font size.</param>
/// <param name="maxWidth">The line width in points.</param>
/// <returns>The lines (one empty line for an empty text).</returns>
public static IReadOnlyList<string> Wrap(string? text, PdfFont font, double size, double maxWidth)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxWidth);
var lines = new List<string>();
foreach (var paragraph in (text ?? string.Empty).Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n'))
{
var line = new StringBuilder();
foreach (var word in paragraph.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
var candidate = line.Length == 0 ? word : line + " " + word;
if (Measure(candidate, font, size) <= maxWidth)
{
line.Clear().Append(candidate);
continue;
}
if (line.Length > 0)
{
lines.Add(line.ToString());
line.Clear();
}
// A word wider than the line is cut where it no longer fits.
var rest = word;
while (Measure(rest, font, size) > maxWidth && rest.Length > 1)
{
var cut = rest.Length - 1;
while (cut > 1 && Measure(rest[..cut], font, size) > maxWidth)
{
cut--;
}
lines.Add(rest[..cut]);
rest = rest[cut..];
}
line.Append(rest);
}
lines.Add(line.ToString());
}
return lines;
}
/// <summary>Shortens a text with an ellipsis so that it fits a width (table cells).</summary>
/// <param name="text">The text.</param>
/// <param name="font">The font.</param>
/// <param name="size">The font size.</param>
/// <param name="maxWidth">The width in points.</param>
/// <returns>The text, shortened if needed.</returns>
public static string Fit(string? text, PdfFont font, double size, double maxWidth)
{
text ??= string.Empty;
if (Measure(text, font, size) <= maxWidth)
{
return text;
}
for (var length = text.Length - 1; length > 0; length--)
{
var candidate = text[..length].TrimEnd() + "…";
if (Measure(candidate, font, size) <= maxWidth)
{
return candidate;
}
}
return string.Empty;
}
private static byte ToWinAnsi(char c) => c switch
{
'\t' or '\r' or '\n' => (byte)' ',
>= ' ' and <= '~' => (byte)c,
>= ' ' and <= 'ÿ' => (byte)c,
_ => WinAnsiSpecials.TryGetValue(c, out var code) ? code : (byte)'?',
};
private static int[] Table(int[] ascii, int[] win, int[] latin)
{
var table = new int[256];
ascii.CopyTo(table, 32);
win.CopyTo(table, 128);
latin.CopyTo(table, 160);
return table;
}
}
@@ -0,0 +1,679 @@
using System.Globalization;
using System.IO.Compression;
using System.Text;
namespace Khaemhat.Infrastructure.Files;
/// <summary>An RGB colour.</summary>
/// <param name="R">Red, 0-255.</param>
/// <param name="G">Green, 0-255.</param>
/// <param name="B">Blue, 0-255.</param>
public readonly record struct PdfColor(byte R, byte G, byte B)
{
/// <summary>Black.</summary>
public static PdfColor Black { get; } = new(0, 0, 0);
/// <summary>White.</summary>
public static PdfColor White { get; } = new(255, 255, 255);
/// <summary>A grey.</summary>
/// <param name="level">0 (black) to 255 (white).</param>
/// <returns>The colour.</returns>
public static PdfColor Gray(byte level) => new(level, level, level);
/// <summary>A colour from <c>#RRGGBB</c>.</summary>
/// <param name="hex">The colour, with or without <c>#</c>.</param>
/// <returns>The colour.</returns>
public static PdfColor FromHex(string hex)
{
ArgumentNullException.ThrowIfNull(hex);
var value = hex.TrimStart('#');
if (value.Length != 6 || !int.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var rgb))
{
throw new FormatException("A colour is written #RRGGBB.");
}
return new PdfColor((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb);
}
}
/// <summary>The document information dictionary.</summary>
public sealed record PdfDocumentInfo
{
/// <summary>The title.</summary>
public string? Title { get; init; }
/// <summary>The author (the company or the user).</summary>
public string? Author { get; init; }
/// <summary>The subject.</summary>
public string? Subject { get; init; }
/// <summary>Keywords.</summary>
public string? Keywords { get; init; }
/// <summary>The program that created the content.</summary>
public string Creator { get; init; } = "Khaemhat";
/// <summary>When the document was created; now when omitted.</summary>
public DateTimeOffset? CreationDate { get; init; }
}
/// <summary>What the header of a JPEG file says.</summary>
/// <param name="Width">Width in pixels.</param>
/// <param name="Height">Height in pixels.</param>
/// <param name="Components">1 (grey), 3 (RGB/YCbCr) or 4 (CMYK).</param>
/// <param name="BitsPerComponent">Bits per component, normally 8.</param>
/// <param name="AdobeInverted">An Adobe CMYK JPEG, whose components are stored inverted.</param>
public sealed record JpegInfo(int Width, int Height, int Components, int BitsPerComponent, bool AdobeInverted)
{
/// <summary>
/// Reads the size and components from the start-of-frame marker of a JPEG file, walking the marker segments from
/// the start-of-image marker.
/// </summary>
/// <param name="jpeg">The file.</param>
/// <returns>The header.</returns>
/// <exception cref="InvalidDataException">The data is not a JPEG file the PDF can embed.</exception>
public static JpegInfo Read(ReadOnlySpan<byte> jpeg)
{
if (jpeg.Length < 4 || jpeg[0] != 0xFF || jpeg[1] != 0xD8)
{
throw new InvalidDataException("Not a JPEG file (no SOI marker).");
}
var adobe = false;
var i = 2;
while (i < jpeg.Length)
{
if (jpeg[i] != 0xFF)
{
throw new InvalidDataException("Corrupt JPEG file (marker expected).");
}
while (i < jpeg.Length && jpeg[i] == 0xFF)
{
i++;
}
if (i >= jpeg.Length)
{
break;
}
var marker = jpeg[i++];
if (marker is 0x01 or 0xD8 or (>= 0xD0 and <= 0xD7))
{
continue;
}
if (marker is 0xD9 or 0xDA)
{
break;
}
if (i + 2 > jpeg.Length)
{
break;
}
var length = (jpeg[i] << 8) | jpeg[i + 1];
if (length < 2 || i + length > jpeg.Length)
{
throw new InvalidDataException("Corrupt JPEG file (segment length).");
}
if (marker is >= 0xC0 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC)
{
if (length < 8)
{
throw new InvalidDataException("Corrupt JPEG file (frame header).");
}
var bits = jpeg[i + 2];
var height = (jpeg[i + 3] << 8) | jpeg[i + 4];
var width = (jpeg[i + 5] << 8) | jpeg[i + 6];
var components = jpeg[i + 7];
if (width == 0 || height == 0 || components is not (1 or 3 or 4))
{
throw new InvalidDataException("Unsupported JPEG file (size or components).");
}
return new JpegInfo(width, height, components, bits, adobe && components == 4);
}
if (marker == 0xEE && length >= 7 && jpeg.Slice(i + 2, 5).SequenceEqual("Adobe"u8))
{
adobe = true;
}
i += length;
}
throw new InvalidDataException("Not a JPEG file the PDF can embed (no frame header).");
}
}
/// <summary>An image added to a document; draw it on any page with <see cref="PdfPage.DrawImage"/>.</summary>
public sealed class PdfImage
{
internal PdfImage(int objectNumber, string name, JpegInfo info)
{
ObjectNumber = objectNumber;
Name = name;
Info = info;
}
/// <summary>Width in pixels.</summary>
public int Width => Info.Width;
/// <summary>Height in pixels.</summary>
public int Height => Info.Height;
/// <summary>The JPEG header.</summary>
public JpegInfo Info { get; }
internal int ObjectNumber { get; }
internal string Name { get; }
}
/// <summary>
/// A page being drawn. Coordinates are PDF points (1/72 inch) from the <b>bottom-left</b> corner; text is placed by
/// its baseline. Use <see cref="PdfTextLayout"/> to measure and wrap text.
/// </summary>
public sealed class PdfPage
{
private readonly StringBuilder _content = new();
internal PdfPage(int number, double width, double height)
{
Number = number;
Width = width;
Height = height;
}
/// <summary>The page number, from 1.</summary>
public int Number { get; }
/// <summary>The width in points.</summary>
public double Width { get; }
/// <summary>The height in points.</summary>
public double Height { get; }
internal SortedSet<PdfFont> Fonts { get; } = [];
internal SortedDictionary<string, int> Images { get; } = new(StringComparer.Ordinal);
internal bool IsClosed { get; set; }
/// <summary>Writes a line of text.</summary>
/// <param name="text">The text (one line; see <see cref="PdfTextLayout.Wrap"/>).</param>
/// <param name="x">The left edge.</param>
/// <param name="y">The baseline.</param>
/// <param name="font">The font.</param>
/// <param name="size">The size in points.</param>
/// <param name="color">The colour; black when omitted.</param>
public void DrawText(string? text, double x, double y, PdfFont font, double size, PdfColor? color = null)
{
Check();
var bytes = PdfTextLayout.EncodeWinAnsi(text);
if (bytes.Length == 0)
{
return;
}
Fonts.Add(font);
var c = color ?? PdfColor.Black;
_content.Append("q ").Append(Color(c)).Append(" rg BT /").Append(PdfWriter.FontResource(font)).Append(' ').Append(Num(size))
.Append(" Tf 1 0 0 1 ").Append(Num(x)).Append(' ').Append(Num(y)).Append(" Tm (");
foreach (var b in bytes)
{
switch (b)
{
case (byte)'(' or (byte)')' or (byte)'\\':
_content.Append('\\').Append((char)b);
break;
case < 0x20 or >= 0x7F:
_content.Append('\\').Append(Convert.ToString(b, 8).PadLeft(3, '0'));
break;
default:
_content.Append((char)b);
break;
}
}
_content.Append(") Tj ET Q\n");
}
/// <summary>Writes a line of text ending at <paramref name="right"/> (amounts in a column).</summary>
/// <param name="text">The text.</param>
/// <param name="right">The right edge.</param>
/// <param name="y">The baseline.</param>
/// <param name="font">The font.</param>
/// <param name="size">The size.</param>
/// <param name="color">The colour.</param>
public void DrawTextRight(string? text, double right, double y, PdfFont font, double size, PdfColor? color = null) =>
DrawText(text, right - PdfTextLayout.Measure(text, font, size), y, font, size, color);
/// <summary>Writes a line of text centred on <paramref name="center"/>.</summary>
/// <param name="text">The text.</param>
/// <param name="center">The centre.</param>
/// <param name="y">The baseline.</param>
/// <param name="font">The font.</param>
/// <param name="size">The size.</param>
/// <param name="color">The colour.</param>
public void DrawTextCentered(string? text, double center, double y, PdfFont font, double size, PdfColor? color = null) =>
DrawText(text, center - (PdfTextLayout.Measure(text, font, size) / 2), y, font, size, color);
/// <summary>Writes a paragraph wrapped to a width, from a first baseline downwards.</summary>
/// <param name="text">The text.</param>
/// <param name="x">The left edge.</param>
/// <param name="y">The first baseline.</param>
/// <param name="width">The width.</param>
/// <param name="font">The font.</param>
/// <param name="size">The size.</param>
/// <param name="lineHeight">The distance between baselines; 1.2 times the size when omitted.</param>
/// <param name="color">The colour.</param>
/// <returns>The baseline after the last line.</returns>
public double DrawParagraph(string? text, double x, double y, double width, PdfFont font, double size, double? lineHeight = null, PdfColor? color = null)
{
var step = lineHeight ?? size * 1.2;
foreach (var line in PdfTextLayout.Wrap(text, font, size, width))
{
DrawText(line, x, y, font, size, color);
y -= step;
}
return y;
}
/// <summary>Draws a line.</summary>
/// <param name="x1">Start x.</param>
/// <param name="y1">Start y.</param>
/// <param name="x2">End x.</param>
/// <param name="y2">End y.</param>
/// <param name="lineWidth">The width in points.</param>
/// <param name="color">The colour; black when omitted.</param>
public void DrawLine(double x1, double y1, double x2, double y2, double lineWidth = 0.5, PdfColor? color = null)
{
Check();
_content.Append("q ").Append(Num(lineWidth)).Append(" w ").Append(Color(color ?? PdfColor.Black)).Append(" RG ")
.Append(Num(x1)).Append(' ').Append(Num(y1)).Append(" m ").Append(Num(x2)).Append(' ').Append(Num(y2)).Append(" l S Q\n");
}
/// <summary>Draws a rectangle, filled and/or outlined.</summary>
/// <param name="x">The left edge.</param>
/// <param name="y">The bottom edge.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="stroke">The outline colour, or <see langword="null"/> for none.</param>
/// <param name="fill">The fill colour, or <see langword="null"/> for none.</param>
/// <param name="lineWidth">The outline width.</param>
public void DrawRectangle(double x, double y, double width, double height, PdfColor? stroke = null, PdfColor? fill = null, double lineWidth = 0.5)
{
Check();
if (stroke is null && fill is null)
{
return;
}
_content.Append("q ");
if (stroke is { } s)
{
_content.Append(Num(lineWidth)).Append(" w ").Append(Color(s)).Append(" RG ");
}
if (fill is { } f)
{
_content.Append(Color(f)).Append(" rg ");
}
var paint = (stroke, fill) switch
{
(not null, not null) => "B",
(not null, null) => "S",
_ => "f",
};
_content.Append(Num(x)).Append(' ').Append(Num(y)).Append(' ').Append(Num(width)).Append(' ').Append(Num(height)).Append(" re ").Append(paint).Append(" Q\n");
}
/// <summary>Draws an image scaled to a box.</summary>
/// <param name="image">The image, from <see cref="PdfWriter.AddJpeg"/>.</param>
/// <param name="x">The left edge.</param>
/// <param name="y">The bottom edge.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public void DrawImage(PdfImage image, double x, double y, double width, double height)
{
ArgumentNullException.ThrowIfNull(image);
Check();
Images[image.Name] = image.ObjectNumber;
_content.Append("q ").Append(Num(width)).Append(" 0 0 ").Append(Num(height)).Append(' ').Append(Num(x)).Append(' ').Append(Num(y))
.Append(" cm /").Append(image.Name).Append(" Do Q\n");
}
internal byte[] ContentBytes() => Encoding.ASCII.GetBytes(_content.ToString());
internal static string Num(double value)
{
if (!double.IsFinite(value))
{
throw new ArgumentOutOfRangeException(nameof(value), value, "Coordinates must be finite numbers.");
}
var text = Math.Round(value, 3).ToString("0.###", CultureInfo.InvariantCulture);
return text == "-0" ? "0" : text;
}
private static string Color(PdfColor c) => Num(c.R / 255.0) + " " + Num(c.G / 255.0) + " " + Num(c.B / 255.0);
private void Check()
{
if (IsClosed)
{
throw new InvalidOperationException($"Page {Number} is finished: draw on the current page.");
}
}
}
/// <summary>
/// Writes PDF 1.7 documents (SPEC §2 "PDF e file"), written in house: the 12 standard Latin Type1 fonts with
/// <c>WinAnsiEncoding</c>, text, lines, rectangles, RGB colours, JPEG images, several pages, the information
/// dictionary, Flate-compressed content streams and a correct cross-reference table. Pages are written to the
/// output as soon as the next page starts, so long documents do not stay in memory; only asynchronous writes reach
/// the output, which can therefore be an HTTP response.
/// </summary>
/// <remarks>
/// TODO (FatturaPA courtesy copies, SPEC §2): PDF/A-3 with embedded XML attachments (<c>PdfA3Embedder</c>) needs
/// embedded fonts, an XMP metadata stream and an output intent; this first version does not produce PDF/A.
/// </remarks>
/// <example>
/// <code>
/// await using var pdf = new PdfWriter(stream, new PdfDocumentInfo { Title = "Prova" });
/// var page = await pdf.AddPageAsync();
/// page.DrawText("Totale € 1.234,50", 40, page.Height - 60, PdfFont.HelveticaBold, 14);
/// await pdf.CloseAsync();
/// </code>
/// </example>
public sealed class PdfWriter : IAsyncDisposable
{
/// <summary>The media type of a PDF file.</summary>
public const string MediaType = "application/pdf";
/// <summary>The width of an A4 page in points.</summary>
public const double A4Width = 595.28;
/// <summary>The height of an A4 page in points.</summary>
public const double A4Height = 841.89;
private const int CatalogObject = 1;
private const int PagesObject = 2;
private const int InfoObject = 3;
private readonly Stream _output;
private readonly bool _leaveOpen;
private readonly PdfDocumentInfo _info;
private readonly MemoryStream _buffer = new();
private readonly List<long> _offsets = [0, -1, -1, -1];
private readonly List<int> _pageObjects = [];
private readonly Dictionary<PdfFont, int> _fontObjects = [];
private long _flushed;
private int _images;
private PdfPage? _page;
private bool _closed;
/// <summary>Starts a document.</summary>
/// <param name="output">The stream that receives the file; it need not be seekable.</param>
/// <param name="info">The document information; <see langword="null"/> for none but the creator.</param>
/// <param name="leaveOpen">Whether to leave <paramref name="output"/> open on dispose.</param>
public PdfWriter(Stream output, PdfDocumentInfo? info = null, bool leaveOpen = false)
{
ArgumentNullException.ThrowIfNull(output);
_output = output;
_leaveOpen = leaveOpen;
_info = info ?? new PdfDocumentInfo();
Ascii("%PDF-1.7\n%");
_buffer.Write([0xE2, 0xE3, 0xCF, 0xD3, (byte)'\n']);
}
/// <summary>Whether content streams are Flate-compressed (turn it off only to inspect the output).</summary>
public bool CompressContent { get; init; } = true;
/// <summary>The number of pages started.</summary>
public int PageCount => _pageObjects.Count + (_page is null ? 0 : 1);
/// <summary>The current page, or <see langword="null"/> before the first.</summary>
public PdfPage? CurrentPage => _page;
/// <summary>Finishes the current page (writing it to the output) and starts a new one.</summary>
/// <param name="width">The width in points; A4 when omitted.</param>
/// <param name="height">The height in points; A4 when omitted.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new page.</returns>
public async Task<PdfPage> AddPageAsync(double width = A4Width, double height = A4Height, CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_closed, this);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
FinishPage();
await FlushAsync(cancellationToken).ConfigureAwait(false);
_page = new PdfPage(_pageObjects.Count + 1, width, height);
return _page;
}
/// <summary>Adds a JPEG image to the document (embedded as is, <c>DCTDecode</c>).</summary>
/// <param name="jpeg">The JPEG file.</param>
/// <returns>The image, to draw on any page.</returns>
/// <exception cref="InvalidDataException">The data is not a JPEG file the PDF can embed.</exception>
public PdfImage AddJpeg(ReadOnlySpan<byte> jpeg)
{
ObjectDisposedException.ThrowIf(_closed, this);
var info = JpegInfo.Read(jpeg);
var number = Allocate();
var colorSpace = info.Components switch { 1 => "/DeviceGray", 4 => "/DeviceCMYK", _ => "/DeviceRGB" };
var decode = info.AdobeInverted ? " /Decode [1 0 1 0 1 0 1 0]" : string.Empty;
BeginObject(number);
Ascii(string.Create(
CultureInfo.InvariantCulture,
$"<< /Type /XObject /Subtype /Image /Width {info.Width} /Height {info.Height} /ColorSpace {colorSpace} /BitsPerComponent {info.BitsPerComponent}{decode} /Filter /DCTDecode /Length {jpeg.Length} >>\nstream\n"));
_buffer.Write(jpeg);
Ascii("\nendstream\nendobj\n");
_images++;
return new PdfImage(number, "Im" + _images.ToString(CultureInfo.InvariantCulture), info);
}
/// <summary>Writes what is buffered to the output.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task FlushAsync(CancellationToken cancellationToken = default)
{
if (_buffer.Length == 0)
{
return;
}
await _output.WriteAsync(_buffer.GetBuffer().AsMemory(0, (int)_buffer.Length), cancellationToken).ConfigureAwait(false);
_flushed += _buffer.Length;
_buffer.SetLength(0);
}
/// <summary>
/// Finishes the document: the last page, fonts, page tree, catalogue, information, cross-reference table and
/// trailer. A document without pages gets one blank page.
/// </summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task CloseAsync(CancellationToken cancellationToken = default)
{
if (_closed)
{
return;
}
if (_page is null && _pageObjects.Count == 0)
{
_page = new PdfPage(1, A4Width, A4Height);
}
FinishPage();
foreach (var (font, number) in _fontObjects.OrderBy(f => f.Value))
{
BeginObject(number);
Ascii($"<< /Type /Font /Subtype /Type1 /BaseFont /{PdfTextLayout.BaseFontName(font)} /Encoding /WinAnsiEncoding >>\nendobj\n");
}
BeginObject(PagesObject);
Ascii("<< /Type /Pages /Kids [" + string.Join(' ', _pageObjects.Select(p => Ref(p))) + "] /Count "
+ _pageObjects.Count.ToString(CultureInfo.InvariantCulture) + " >>\nendobj\n");
BeginObject(CatalogObject);
Ascii("<< /Type /Catalog /Pages " + Ref(PagesObject) + " >>\nendobj\n");
BeginObject(InfoObject);
Ascii("<< " + InfoEntries() + ">>\nendobj\n");
var xref = Position;
var size = _offsets.Count.ToString(CultureInfo.InvariantCulture);
var table = new StringBuilder();
table.Append("xref\n0 ").Append(size).Append('\n').Append("0000000000 65535 f\r\n");
for (var i = 1; i < _offsets.Count; i++)
{
if (_offsets[i] < 0)
{
throw new InvalidOperationException($"Object {i} was allocated but never written.");
}
table.Append(_offsets[i].ToString("D10", CultureInfo.InvariantCulture)).Append(" 00000 n\r\n");
}
var id = Convert.ToHexString(Guid.NewGuid().ToByteArray());
table.Append("trailer\n<< /Size ").Append(size).Append(" /Root ").Append(Ref(CatalogObject)).Append(" /Info ").Append(Ref(InfoObject))
.Append(" /ID [<").Append(id).Append("> <").Append(id).Append(">] >>\nstartxref\n")
.Append(xref.ToString(CultureInfo.InvariantCulture)).Append("\n%%EOF\n");
Ascii(table.ToString());
_closed = true;
await FlushAsync(cancellationToken).ConfigureAwait(false);
await _output.FlushAsync(cancellationToken).ConfigureAwait(false);
if (!_leaveOpen)
{
await _output.DisposeAsync().ConfigureAwait(false);
}
}
/// <summary>Closes the document if it is still open.</summary>
/// <returns>A task.</returns>
public async ValueTask DisposeAsync()
{
await CloseAsync().ConfigureAwait(false);
await _buffer.DisposeAsync().ConfigureAwait(false);
}
internal static string FontResource(PdfFont font) => "F" + ((int)font + 1).ToString(CultureInfo.InvariantCulture);
private long Position => _flushed + _buffer.Length;
private static string Ref(int number) => number.ToString(CultureInfo.InvariantCulture) + " 0 R";
private static string PdfDate(DateTimeOffset value) =>
"D:" + value.UtcDateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) + "Z";
/// <summary>A text string: ASCII as a literal, anything else as UTF-16BE with byte order mark.</summary>
private static string TextString(string value)
{
if (value.All(c => c is >= ' ' and <= '~'))
{
return "(" + value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("(", "\\(", StringComparison.Ordinal).Replace(")", "\\)", StringComparison.Ordinal) + ")";
}
return "<FEFF" + Convert.ToHexString(Encoding.BigEndianUnicode.GetBytes(value)) + ">";
}
private string InfoEntries()
{
var entries = new StringBuilder();
void Add(string key, string? value)
{
if (!string.IsNullOrEmpty(value))
{
entries.Append('/').Append(key).Append(' ').Append(TextString(value)).Append(' ');
}
}
Add("Title", _info.Title);
Add("Author", _info.Author);
Add("Subject", _info.Subject);
Add("Keywords", _info.Keywords);
Add("Creator", _info.Creator);
Add("Producer", "Khaemhat PdfWriter");
var created = PdfDate(_info.CreationDate ?? DateTimeOffset.UtcNow);
entries.Append("/CreationDate (").Append(created).Append(") /ModDate (").Append(created).Append(") ");
return entries.ToString();
}
private int Allocate()
{
_offsets.Add(-1);
return _offsets.Count - 1;
}
private void BeginObject(int number)
{
_offsets[number] = Position;
Ascii(number.ToString(CultureInfo.InvariantCulture) + " 0 obj\n");
}
private void Ascii(string text) => _buffer.Write(Encoding.ASCII.GetBytes(text));
private void FinishPage()
{
if (_page is not { } page)
{
return;
}
page.IsClosed = true;
_page = null;
var content = page.ContentBytes();
var filter = string.Empty;
if (CompressContent)
{
using var compressed = new MemoryStream();
using (var zlib = new ZLibStream(compressed, CompressionLevel.Optimal, leaveOpen: true))
{
zlib.Write(content);
}
content = compressed.ToArray();
filter = " /Filter /FlateDecode";
}
var contentObject = Allocate();
BeginObject(contentObject);
Ascii("<< /Length " + content.Length.ToString(CultureInfo.InvariantCulture) + filter + " >>\nstream\n");
_buffer.Write(content);
Ascii("\nendstream\nendobj\n");
var fonts = new StringBuilder();
foreach (var font in page.Fonts)
{
if (!_fontObjects.TryGetValue(font, out var number))
{
number = Allocate();
_fontObjects[font] = number;
}
fonts.Append('/').Append(FontResource(font)).Append(' ').Append(Ref(number)).Append(' ');
}
var images = string.Concat(page.Images.Select(i => "/" + i.Key + " " + Ref(i.Value) + " "));
var resources = "/ProcSet [/PDF /Text /ImageB /ImageC]"
+ (fonts.Length > 0 ? " /Font << " + fonts + ">>" : string.Empty)
+ (images.Length > 0 ? " /XObject << " + images + ">>" : string.Empty);
var pageObject = Allocate();
BeginObject(pageObject);
Ascii("<< /Type /Page /Parent " + Ref(PagesObject) + " /MediaBox [0 0 " + PdfPage.Num(page.Width) + " " + PdfPage.Num(page.Height)
+ "] /Resources << " + resources + " >> /Contents " + Ref(contentObject) + " >>\nendobj\n");
_pageObjects.Add(pageObject);
}
}
@@ -0,0 +1,348 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using Khaemhat.Core.Files;
using Khaemhat.Data;
namespace Khaemhat.Infrastructure.Files;
/// <summary>Where the store keeps files and the default limits.</summary>
/// <param name="RootDirectory">The root folder, <c>&lt;KHAEMHAT_DATA_DIR&gt;/files</c>.</param>
public sealed record FileStoreOptions(string RootDirectory)
{
/// <summary>The largest file accepted when the caller gives no limit (25 MB).</summary>
public long MaxFileBytes { get; init; } = FileLimits.DefaultMaxBytes;
/// <summary>The space each company may use when the caller gives no quota; 0 means no quota.</summary>
public long CompanyQuotaBytes { get; init; }
/// <summary>The options for a data folder: files in <c>&lt;dataDir&gt;/files</c>.</summary>
/// <param name="dataDirectory">The value of <c>KHAEMHAT_DATA_DIR</c>.</param>
/// <returns>The options.</returns>
public static FileStoreOptions ForDataDirectory(string dataDirectory)
{
ArgumentException.ThrowIfNullOrWhiteSpace(dataDirectory);
return new FileStoreOptions(Path.Combine(dataDirectory, "files"));
}
/// <summary>The limits used when the caller gives none.</summary>
public FileLimits DefaultLimits => new(MaxFileBytes, CompanyQuotaBytes);
}
/// <summary>The scanner used when no antivirus is plugged in: every file is accepted.</summary>
public sealed class NoOpFileScanner : IFileScanner
{
/// <inheritdoc />
public ValueTask<FileScanResult> ScanAsync(string companyCode, Stream content, CancellationToken cancellationToken = default) =>
ValueTask.FromResult(FileScanResult.Ok);
}
/// <summary>
/// The file store on the data volume (SPEC §9.4): <c>&lt;root&gt;/&lt;COMPANY&gt;/&lt;yyyy&gt;/&lt;guid&gt;</c>. A file is
/// written to <c>&lt;guid&gt;.part</c> in the same folder while its size is checked and its SHA-256 computed, then
/// renamed: nothing is ever written outside the data folder and a partial file never appears under a key.
/// </summary>
public sealed partial class VolumeFileStore : IFileStore
{
private const string PartExtension = ".part";
private const int BufferSize = 81920;
private readonly FileStoreOptions _options;
private readonly IFileScanner _scanner;
private readonly TimeProvider _clock;
/// <summary>Creates the store.</summary>
/// <param name="options">The root folder and the default limits.</param>
/// <param name="scanner">The antivirus hook.</param>
/// <param name="clock">The clock (the year folder).</param>
public VolumeFileStore(FileStoreOptions options, IFileScanner scanner, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(scanner);
ArgumentNullException.ThrowIfNull(clock);
if (!Path.IsPathFullyQualified(options.RootDirectory))
{
throw new ArgumentException("The root of the file store must be an absolute path.", nameof(options));
}
_options = options;
_scanner = scanner;
_clock = clock;
}
/// <summary>The root folder.</summary>
public string RootDirectory => _options.RootDirectory;
/// <summary>Whether a key has the form the store produces (<c>yyyy/guid</c>).</summary>
/// <param name="key">The key.</param>
/// <returns><see langword="true"/> if valid.</returns>
public static bool IsValidKey(string? key) => key is not null && KeyPattern().IsMatch(key);
/// <inheritdoc />
public async Task<StoredFile> SaveAsync(string companyCode, Stream content, FileLimits? limits = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(content);
await using var writer = await CreateAsync(companyCode, limits, cancellationToken).ConfigureAwait(false);
await content.CopyToAsync(writer.Content, BufferSize, cancellationToken).ConfigureAwait(false);
return await writer.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public Task<IFileStoreWriter> CreateAsync(string companyCode, FileLimits? limits = null, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var company = CompanyFolder(companyCode);
var year = _clock.GetUtcNow().Year.ToString("D4", CultureInfo.InvariantCulture);
var folder = Path.Combine(company, year);
Directory.CreateDirectory(folder);
var name = Guid.NewGuid().ToString("N");
var writer = new Writer(this, CompanyCodes.Normalize(companyCode), year + "/" + name, Path.Combine(folder, name), limits ?? _options.DefaultLimits);
return Task.FromResult<IFileStoreWriter>(writer);
}
/// <inheritdoc />
public Stream OpenRead(string companyCode, string key)
{
var path = PathOf(companyCode, key);
try
{
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
}
catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
{
throw new FileStoreException(FileStoreException.NotFound, $"The file {key} does not exist in the store of {companyCode}.");
}
}
/// <inheritdoc />
public bool Exists(string companyCode, string key) => File.Exists(PathOf(companyCode, key));
/// <inheritdoc />
public bool Delete(string companyCode, string key)
{
var path = PathOf(companyCode, key);
if (!File.Exists(path))
{
return false;
}
File.Delete(path);
return true;
}
/// <inheritdoc />
public Task<FileUsage> GetUsageAsync(string companyCode, long? quotaBytes = null, CancellationToken cancellationToken = default)
{
var quota = quotaBytes ?? _options.CompanyQuotaBytes;
var folder = CompanyFolder(companyCode);
long files = 0, bytes = 0;
if (Directory.Exists(folder))
{
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories))
{
cancellationToken.ThrowIfCancellationRequested();
if (!file.Name.EndsWith(PartExtension, StringComparison.Ordinal))
{
files++;
bytes += file.Length;
}
}
}
return Task.FromResult(new FileUsage(files, bytes, quota));
}
/// <inheritdoc />
public int DeleteAbandonedParts(string companyCode, TimeSpan olderThan)
{
var folder = CompanyFolder(companyCode);
if (!Directory.Exists(folder))
{
return 0;
}
var limit = _clock.GetUtcNow().UtcDateTime - olderThan;
var deleted = 0;
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*" + PartExtension, SearchOption.AllDirectories))
{
if (file.LastWriteTimeUtc < limit)
{
try
{
file.Delete();
deleted++;
}
catch (IOException)
{
// Still being written by another process: it will be removed next time.
}
}
}
return deleted;
}
private string CompanyFolder(string companyCode) => Path.Combine(_options.RootDirectory, CompanyCodes.Normalize(companyCode));
private string PathOf(string companyCode, string key)
{
if (!IsValidKey(key))
{
throw new ArgumentException("Not a key of the file store.", nameof(key));
}
return Path.Combine(CompanyFolder(companyCode), key.Replace('/', Path.DirectorySeparatorChar));
}
[GeneratedRegex("^[0-9]{4}/[0-9a-f]{32}$", RegexOptions.CultureInvariant)]
private static partial Regex KeyPattern();
/// <summary>A file being written: the <c>.part</c> file and the counting stream over it.</summary>
private sealed class Writer : IFileStoreWriter
{
private readonly VolumeFileStore _store;
private readonly string _company;
private readonly string _key;
private readonly string _finalPath;
private readonly string _partPath;
private readonly FileLimits _limits;
private readonly FileStream _file;
private readonly HashingStream _content;
private bool _committed;
private bool _disposed;
public Writer(VolumeFileStore store, string company, string key, string finalPath, FileLimits limits)
{
_store = store;
_company = company;
_key = key;
_finalPath = finalPath;
_partPath = finalPath + PartExtension;
_limits = limits;
_file = new FileStream(_partPath, FileMode.CreateNew, FileAccess.Write, FileShare.Read, BufferSize, FileOptions.Asynchronous);
_content = new HashingStream(_file, limits.MaxBytes);
}
public Stream Content => _content;
public async Task<StoredFile> CommitAsync(CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_committed)
{
throw new InvalidOperationException("The file is already committed.");
}
await _file.FlushAsync(cancellationToken).ConfigureAwait(false);
var size = _content.Length;
if (_limits.QuotaBytes > 0)
{
var usage = await _store.GetUsageAsync(_company, _limits.QuotaBytes, cancellationToken).ConfigureAwait(false);
if (usage.Bytes + size > _limits.QuotaBytes)
{
throw new FileStoreException(FileStoreException.QuotaExceeded, $"The company {_company} has no space left for {size} bytes.");
}
}
await using (var scan = new FileStream(_partPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, BufferSize, FileOptions.Asynchronous))
{
var verdict = await _store._scanner.ScanAsync(_company, scan, cancellationToken).ConfigureAwait(false);
if (!verdict.Clean)
{
throw new FileStoreException(FileStoreException.Rejected, "The file was rejected by the scanner: " + (verdict.Reason ?? "no reason given") + ".");
}
}
var hash = _content.HashHex();
await _file.DisposeAsync().ConfigureAwait(false);
File.Move(_partPath, _finalPath);
_committed = true;
return new StoredFile(_key, size, hash);
}
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
_disposed = true;
_content.ReleaseHash();
await _file.DisposeAsync().ConfigureAwait(false);
if (!_committed && File.Exists(_partPath))
{
File.Delete(_partPath);
}
}
}
/// <summary>A write-only stream that enforces the size limit and computes SHA-256 on the way.</summary>
private sealed class HashingStream(Stream inner, long maxBytes) : Stream
{
private readonly IncrementalHash _hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
private long _length;
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => _length;
public override long Position
{
get => _length;
set => throw new NotSupportedException();
}
public string HashHex() => Convert.ToHexStringLower(_hash.GetCurrentHash());
public void ReleaseHash() => _hash.Dispose();
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
public override void Write(ReadOnlySpan<byte> buffer)
{
Account(buffer);
inner.Write(buffer);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
Account(buffer.Span);
return inner.WriteAsync(buffer, cancellationToken);
}
public override void Flush() => inner.Flush();
public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken);
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
protected override void Dispose(bool disposing)
{
// The writer owns the file stream and the hash.
base.Dispose(disposing);
}
private void Account(ReadOnlySpan<byte> buffer)
{
if (maxBytes > 0 && _length + buffer.Length > maxBytes)
{
throw new FileStoreException(FileStoreException.TooLarge, $"The file is larger than {maxBytes} bytes.");
}
_length += buffer.Length;
_hash.AppendData(buffer);
}
}
}
@@ -0,0 +1,753 @@
using System.Globalization;
using System.IO.Compression;
using System.Text;
using System.Xml;
namespace Khaemhat.Infrastructure.Files;
/// <summary>The number format of a spreadsheet column.</summary>
public enum XlsxFormat
{
/// <summary>By value: dates get a date format, everything else the general one.</summary>
General = 0,
/// <summary>Whole numbers with thousands separator (<c>#,##0</c>).</summary>
WholeNumber = 1,
/// <summary>Two decimals with thousands separator (<c>#,##0.00</c>).</summary>
TwoDecimals = 2,
/// <summary>Euro amounts (<c>#,##0.00 €</c>).</summary>
Euro = 3,
/// <summary>Percentages with two decimals; the value 0.22 shows as 22,00%.</summary>
Percent = 4,
/// <summary>Dates.</summary>
Date = 5,
/// <summary>Dates with time.</summary>
DateTime = 6,
/// <summary>Text: numbers typed later in the cell stay text.</summary>
Text = 7,
}
/// <summary>A column of a sheet.</summary>
/// <param name="Header">The header, written in bold in the first row; <see langword="null"/> for no header.</param>
/// <param name="Width">The width in characters; <see langword="null"/> for the spreadsheet default.</param>
/// <param name="Format">The number format of the cells.</param>
public sealed record XlsxColumn(string? Header, double? Width = null, XlsxFormat Format = XlsxFormat.General);
/// <summary>The options of an <see cref="XlsxWriter"/>.</summary>
public sealed record XlsxOptions
{
/// <summary>
/// Whether text goes to the shared strings table (smaller files with repeated text, but every distinct string is
/// kept in memory until the end) instead of inline in each cell (the default, fully streaming).
/// </summary>
public bool UseSharedStrings { get; init; }
/// <summary>Whether the header row stays visible while scrolling.</summary>
public bool FreezeHeaderRow { get; init; } = true;
}
/// <summary>
/// Writes Office Open XML spreadsheets (<c>.xlsx</c>, SPEC §2, §9.4) with <see cref="ZipArchive"/> and
/// <see cref="XmlWriter"/>, row by row, without holding the sheet in memory: text (inline or shared strings), numbers,
/// dates as serial numbers with a date format, booleans, a bold header row, column widths and a frozen header.
/// Only asynchronous writes reach the output, so it can be an HTTP response.
/// </summary>
/// <example>
/// <code>
/// await using var xlsx = await XlsxWriter.CreateAsync(stream);
/// await xlsx.StartSheetAsync("Righe", [new("Codice", 12), new("Importo", 14, XlsxFormat.Euro)]);
/// await xlsx.WriteRowAsync(["A1", 12.5m]);
/// await xlsx.CompleteAsync();
/// </code>
/// </example>
public sealed class XlsxWriter : IAsyncDisposable
{
/// <summary>The media type of an <c>.xlsx</c> file.</summary>
public const string MediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/// <summary>The longest sheet name Excel accepts.</summary>
public const int MaxSheetNameLength = 31;
/// <summary>The longest text a cell holds.</summary>
public const int MaxCellTextLength = 32767;
private const string MainNs = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
private const string RelNs = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
private const string PackageRelNs = "http://schemas.openxmlformats.org/package/2006/relationships";
private const string ContentTypesNs = "http://schemas.openxmlformats.org/package/2006/content-types";
private const string WorksheetType = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml";
// Indexes in cellXfs of styles.xml.
private const int StyleGeneral = 0;
private const int StyleHeader = 1;
private const int StyleDate = 2;
private const int StyleDateTime = 3;
private const int StyleInteger = 4;
private const int StyleDecimal = 5;
private const int StyleEuro = 6;
private const int StylePercent = 7;
private const int StyleText = 8;
private static readonly DateTime Epoch = new(1899, 12, 30, 0, 0, 0, DateTimeKind.Unspecified);
private readonly ZipArchive _archive;
private readonly AsyncOutputBuffer _buffer;
private readonly Stream _output;
private readonly bool _leaveOpen;
private readonly XlsxOptions _options;
private readonly List<string> _sheetNames = [];
private readonly Dictionary<string, int> _sharedIndex = new(StringComparer.Ordinal);
private readonly List<string> _shared = [];
private Stream? _sheetStream;
private XmlWriter? _sheet;
private IReadOnlyList<XlsxColumn> _columns = [];
private int _row;
private bool _completed;
private XlsxWriter(ZipArchive archive, AsyncOutputBuffer buffer, Stream output, bool leaveOpen, XlsxOptions options)
{
_archive = archive;
_buffer = buffer;
_output = output;
_leaveOpen = leaveOpen;
_options = options;
}
/// <summary>The names of the sheets started so far (after cleaning).</summary>
public IReadOnlyList<string> SheetNames => _sheetNames;
/// <summary>Starts a workbook.</summary>
/// <param name="output">The stream that receives the file; it need not be seekable.</param>
/// <param name="options">The options.</param>
/// <param name="leaveOpen">Whether to leave <paramref name="output"/> open on dispose.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The writer; complete or dispose it.</returns>
public static async Task<XlsxWriter> CreateAsync(Stream output, XlsxOptions? options = null, bool leaveOpen = false, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(output);
var buffer = new AsyncOutputBuffer(output);
var archive = await ZipArchive.CreateAsync(buffer, ZipArchiveMode.Create, leaveOpen: true, Encoding.UTF8, cancellationToken).ConfigureAwait(false);
return new XlsxWriter(archive, buffer, output, leaveOpen, options ?? new XlsxOptions());
}
/// <summary>
/// Makes a valid sheet name: without <c>[ ] : * ? / \</c>, without apostrophes at the ends, at most 31 characters,
/// different (ignoring case) from the names already used.
/// </summary>
/// <param name="name">The wanted name.</param>
/// <param name="used">The names already in the workbook.</param>
/// <returns>The name.</returns>
public static string CleanSheetName(string? name, IReadOnlyCollection<string> used)
{
ArgumentNullException.ThrowIfNull(used);
var builder = new StringBuilder();
foreach (var c in name ?? string.Empty)
{
if (c is not ('[' or ']' or ':' or '*' or '?' or '/' or '\\') && !char.IsControl(c))
{
builder.Append(c);
}
}
var clean = builder.ToString().Trim().Trim('\'').Trim();
if (clean.Length == 0)
{
clean = "Foglio" + (used.Count + 1).ToString(CultureInfo.InvariantCulture);
}
clean = clean.Length > MaxSheetNameLength ? clean[..MaxSheetNameLength] : clean;
var candidate = clean;
for (var i = 2; used.Contains(candidate, StringComparer.OrdinalIgnoreCase); i++)
{
var suffix = " (" + i.ToString(CultureInfo.InvariantCulture) + ")";
candidate = clean[..Math.Min(clean.Length, MaxSheetNameLength - suffix.Length)] + suffix;
}
return candidate;
}
/// <summary>The spreadsheet serial number of a date (days since 1899-12-30, time as fraction).</summary>
/// <param name="value">The date.</param>
/// <returns>The serial number.</returns>
public static double ToSerialDate(DateTime value) => (value - Epoch).TotalDays;
/// <summary>The letters of a column: 0 is <c>A</c>, 26 is <c>AA</c>.</summary>
/// <param name="index">The zero-based column.</param>
/// <returns>The letters.</returns>
public static string ColumnName(int index)
{
ArgumentOutOfRangeException.ThrowIfNegative(index);
var name = string.Empty;
for (var n = index + 1; n > 0; n = (n - 1) / 26)
{
name = (char)('A' + ((n - 1) % 26)) + name;
}
return name;
}
/// <summary>Starts a sheet (ending the previous one); with column headers the first row is the bold header.</summary>
/// <param name="name">The sheet name, cleaned by <see cref="CleanSheetName"/>.</param>
/// <param name="columns">The columns, or <see langword="null"/>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task StartSheetAsync(string name, IReadOnlyList<XlsxColumn>? columns = null, CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_completed, this);
await EndSheetAsync(cancellationToken).ConfigureAwait(false);
var clean = CleanSheetName(name, _sheetNames);
_sheetNames.Add(clean);
_columns = columns ?? [];
_row = 0;
var entry = _archive.CreateEntry($"xl/worksheets/sheet{_sheetNames.Count.ToString(CultureInfo.InvariantCulture)}.xml", CompressionLevel.Optimal);
_sheetStream = await entry.OpenAsync(cancellationToken).ConfigureAwait(false);
_sheet = XmlWriter.Create(_sheetStream, XmlSettings());
var w = _sheet;
await w.WriteStartDocumentAsync(true).ConfigureAwait(false);
await w.WriteStartElementAsync(null, "worksheet", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync("xmlns", "r", null, RelNs).ConfigureAwait(false);
var hasHeader = _columns.Any(c => c.Header is not null);
await w.WriteStartElementAsync(null, "sheetViews", MainNs).ConfigureAwait(false);
await w.WriteStartElementAsync(null, "sheetView", MainNs).ConfigureAwait(false);
if (_sheetNames.Count == 1)
{
await w.WriteAttributeStringAsync(null, "tabSelected", null, "1").ConfigureAwait(false);
}
await w.WriteAttributeStringAsync(null, "workbookViewId", null, "0").ConfigureAwait(false);
if (hasHeader && _options.FreezeHeaderRow)
{
await w.WriteStartElementAsync(null, "pane", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "ySplit", null, "1").ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "topLeftCell", null, "A2").ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "activePane", null, "bottomLeft").ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "state", null, "frozen").ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteStartElementAsync(null, "selection", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "pane", null, "bottomLeft").ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteStartElementAsync(null, "sheetFormatPr", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "defaultRowHeight", null, "15").ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
if (_columns.Any(c => c.Width is not null))
{
await w.WriteStartElementAsync(null, "cols", MainNs).ConfigureAwait(false);
for (var i = 0; i < _columns.Count; i++)
{
if (_columns[i].Width is { } width)
{
var index = (i + 1).ToString(CultureInfo.InvariantCulture);
await w.WriteStartElementAsync(null, "col", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "min", null, index).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "max", null, index).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "width", null, Math.Clamp(width, 1, 255).ToString("0.##", CultureInfo.InvariantCulture)).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "customWidth", null, "1").ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
}
await w.WriteEndElementAsync().ConfigureAwait(false);
}
await w.WriteStartElementAsync(null, "sheetData", MainNs).ConfigureAwait(false);
if (hasHeader)
{
await WriteRowCoreAsync(_columns.Select(c => (object?)c.Header), header: true).ConfigureAwait(false);
}
}
/// <summary>Writes a row in the current sheet (a sheet <c>Foglio1</c> is started if none is).</summary>
/// <param name="values">
/// The cells: <see cref="string"/>, numbers, <see cref="DateTime"/>, <see cref="DateOnly"/>, <see cref="bool"/>;
/// <see langword="null"/> leaves the cell empty; anything else is written as text.
/// </param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task WriteRowAsync(IEnumerable<object?> values, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(values);
ObjectDisposedException.ThrowIf(_completed, this);
if (_sheet is null)
{
await StartSheetAsync("Foglio1", null, cancellationToken).ConfigureAwait(false);
}
await WriteRowCoreAsync(values, header: false).ConfigureAwait(false);
}
/// <summary>Ends the last sheet and writes workbook, styles, shared strings, relationships and content types.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task CompleteAsync(CancellationToken cancellationToken = default)
{
if (_completed)
{
return;
}
if (_sheetNames.Count == 0)
{
await StartSheetAsync("Foglio1", null, cancellationToken).ConfigureAwait(false);
}
await EndSheetAsync(cancellationToken).ConfigureAwait(false);
await WritePartAsync("xl/workbook.xml", WriteWorkbookAsync, cancellationToken).ConfigureAwait(false);
await WritePartAsync("xl/styles.xml", WriteStylesAsync, cancellationToken).ConfigureAwait(false);
if (_options.UseSharedStrings)
{
await WritePartAsync("xl/sharedStrings.xml", WriteSharedStringsAsync, cancellationToken).ConfigureAwait(false);
}
await WritePartAsync("xl/_rels/workbook.xml.rels", WriteWorkbookRelationshipsAsync, cancellationToken).ConfigureAwait(false);
await WritePartAsync("_rels/.rels", WritePackageRelationshipsAsync, cancellationToken).ConfigureAwait(false);
await WritePartAsync("[Content_Types].xml", WriteContentTypesAsync, cancellationToken).ConfigureAwait(false);
_completed = true;
await _archive.DisposeAsync().ConfigureAwait(false);
await _buffer.FlushAsync(cancellationToken).ConfigureAwait(false);
await _buffer.DisposeAsync().ConfigureAwait(false);
if (!_leaveOpen)
{
await _output.DisposeAsync().ConfigureAwait(false);
}
}
/// <summary>Completes the workbook if needed and closes the stream unless left open.</summary>
/// <returns>A task.</returns>
public async ValueTask DisposeAsync()
{
if (!_completed)
{
await CompleteAsync().ConfigureAwait(false);
}
}
private static XmlWriterSettings XmlSettings() => new()
{
Async = true,
Encoding = new UTF8Encoding(false),
Indent = false,
CloseOutput = false,
};
private static string CleanText(string value)
{
var builder = new StringBuilder(Math.Min(value.Length, MaxCellTextLength));
for (var i = 0; i < value.Length && builder.Length < MaxCellTextLength; i++)
{
var c = value[i];
if (char.IsHighSurrogate(c) && i + 1 < value.Length && char.IsLowSurrogate(value[i + 1]))
{
if (builder.Length + 2 > MaxCellTextLength)
{
break;
}
builder.Append(c).Append(value[i + 1]);
i++;
}
else if (XmlConvert.IsXmlChar(c))
{
builder.Append(c);
}
}
return builder.ToString();
}
private static int StyleOf(XlsxFormat format) => format switch
{
XlsxFormat.WholeNumber => StyleInteger,
XlsxFormat.TwoDecimals => StyleDecimal,
XlsxFormat.Euro => StyleEuro,
XlsxFormat.Percent => StylePercent,
XlsxFormat.Date => StyleDate,
XlsxFormat.DateTime => StyleDateTime,
XlsxFormat.Text => StyleText,
_ => StyleGeneral,
};
private static string? NumberText(object value) => value switch
{
byte or sbyte or short or ushort or int or uint or long or ulong => Convert.ToString(value, CultureInfo.InvariantCulture),
decimal m => m.ToString(CultureInfo.InvariantCulture),
double d when double.IsFinite(d) => d.ToString("R", CultureInfo.InvariantCulture),
float f when float.IsFinite(f) => ((double)f).ToString("R", CultureInfo.InvariantCulture),
_ => null,
};
private async Task WriteRowCoreAsync(IEnumerable<object?> values, bool header)
{
var w = _sheet!;
_row++;
var rowNumber = _row.ToString(CultureInfo.InvariantCulture);
await w.WriteStartElementAsync(null, "row", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "r", null, rowNumber).ConfigureAwait(false);
var column = 0;
foreach (var value in values)
{
if (value is not null)
{
var format = !header && column < _columns.Count ? _columns[column].Format : XlsxFormat.General;
await WriteCellAsync(w, ColumnName(column) + rowNumber, value, header ? StyleHeader : StyleOf(format), format).ConfigureAwait(false);
}
column++;
}
await w.WriteEndElementAsync().ConfigureAwait(false);
}
private async Task WriteCellAsync(XmlWriter w, string reference, object value, int style, XlsxFormat format)
{
switch (value)
{
case bool b:
await StartCellAsync(w, reference, style, "b").ConfigureAwait(false);
await w.WriteElementStringAsync(null, "v", MainNs, b ? "1" : "0").ConfigureAwait(false);
break;
case DateTime date:
var dateStyle = style == StyleGeneral ? (date.TimeOfDay == TimeSpan.Zero ? StyleDate : StyleDateTime) : style;
await StartCellAsync(w, reference, dateStyle, null).ConfigureAwait(false);
await w.WriteElementStringAsync(null, "v", MainNs, ToSerialDate(date).ToString("R", CultureInfo.InvariantCulture)).ConfigureAwait(false);
break;
case DateOnly day:
await StartCellAsync(w, reference, style == StyleGeneral ? StyleDate : style, null).ConfigureAwait(false);
await w.WriteElementStringAsync(null, "v", MainNs, ToSerialDate(day.ToDateTime(TimeOnly.MinValue)).ToString("R", CultureInfo.InvariantCulture)).ConfigureAwait(false);
break;
default:
if (format != XlsxFormat.Text && NumberText(value) is { } number)
{
await StartCellAsync(w, reference, style, null).ConfigureAwait(false);
await w.WriteElementStringAsync(null, "v", MainNs, number).ConfigureAwait(false);
break;
}
if (value is double or float)
{
// NaN and infinity have no spreadsheet value: the cell stays empty.
return;
}
var text = CleanText(Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty);
if (_options.UseSharedStrings)
{
if (!_sharedIndex.TryGetValue(text, out var index))
{
index = _shared.Count;
_shared.Add(text);
_sharedIndex[text] = index;
}
await StartCellAsync(w, reference, style, "s").ConfigureAwait(false);
await w.WriteElementStringAsync(null, "v", MainNs, index.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
}
else
{
await StartCellAsync(w, reference, style, "inlineStr").ConfigureAwait(false);
await w.WriteStartElementAsync(null, "is", MainNs).ConfigureAwait(false);
await WriteTextElementAsync(w, text).ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
break;
}
await w.WriteEndElementAsync().ConfigureAwait(false);
}
private static async Task StartCellAsync(XmlWriter w, string reference, int style, string? type)
{
await w.WriteStartElementAsync(null, "c", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "r", null, reference).ConfigureAwait(false);
if (style != StyleGeneral)
{
await w.WriteAttributeStringAsync(null, "s", null, style.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
}
if (type is not null)
{
await w.WriteAttributeStringAsync(null, "t", null, type).ConfigureAwait(false);
}
}
private static async Task WriteTextElementAsync(XmlWriter w, string text)
{
await w.WriteStartElementAsync(null, "t", MainNs).ConfigureAwait(false);
if (text.Length > 0 && (char.IsWhiteSpace(text[0]) || char.IsWhiteSpace(text[^1])))
{
await w.WriteAttributeStringAsync("xml", "space", null, "preserve").ConfigureAwait(false);
}
await w.WriteStringAsync(text).ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
private async Task EndSheetAsync(CancellationToken cancellationToken)
{
if (_sheet is null)
{
return;
}
await _sheet.WriteEndElementAsync().ConfigureAwait(false);
await _sheet.WriteEndElementAsync().ConfigureAwait(false);
await _sheet.WriteEndDocumentAsync().ConfigureAwait(false);
await _sheet.FlushAsync().ConfigureAwait(false);
await _sheet.DisposeAsync().ConfigureAwait(false);
_sheet = null;
cancellationToken.ThrowIfCancellationRequested();
await _sheetStream!.DisposeAsync().ConfigureAwait(false);
_sheetStream = null;
await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false);
}
private async Task WritePartAsync(string name, Func<XmlWriter, Task> write, CancellationToken cancellationToken)
{
var entry = _archive.CreateEntry(name, CompressionLevel.Optimal);
var stream = await entry.OpenAsync(cancellationToken).ConfigureAwait(false);
await using (stream.ConfigureAwait(false))
{
var w = XmlWriter.Create(stream, XmlSettings());
await using var writerScope = w.ConfigureAwait(false);
await w.WriteStartDocumentAsync(true).ConfigureAwait(false);
await write(w).ConfigureAwait(false);
await w.WriteEndDocumentAsync().ConfigureAwait(false);
await w.FlushAsync().ConfigureAwait(false);
}
await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false);
}
private async Task WriteWorkbookAsync(XmlWriter w)
{
await w.WriteStartElementAsync(null, "workbook", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync("xmlns", "r", null, RelNs).ConfigureAwait(false);
await w.WriteStartElementAsync(null, "sheets", MainNs).ConfigureAwait(false);
for (var i = 0; i < _sheetNames.Count; i++)
{
var id = (i + 1).ToString(CultureInfo.InvariantCulture);
await w.WriteStartElementAsync(null, "sheet", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "name", null, _sheetNames[i]).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "sheetId", null, id).ConfigureAwait(false);
await w.WriteAttributeStringAsync("r", "id", RelNs, "rId" + id).ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
private async Task WriteSharedStringsAsync(XmlWriter w)
{
var count = _shared.Count.ToString(CultureInfo.InvariantCulture);
await w.WriteStartElementAsync(null, "sst", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "count", null, count).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "uniqueCount", null, count).ConfigureAwait(false);
foreach (var text in _shared)
{
await w.WriteStartElementAsync(null, "si", MainNs).ConfigureAwait(false);
await WriteTextElementAsync(w, text).ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
await w.WriteEndElementAsync().ConfigureAwait(false);
}
private static async Task WriteStylesAsync(XmlWriter w)
{
await w.WriteStartElementAsync(null, "styleSheet", MainNs).ConfigureAwait(false);
await w.WriteStartElementAsync(null, "numFmts", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "count", null, "1").ConfigureAwait(false);
await w.WriteStartElementAsync(null, "numFmt", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "numFmtId", null, "164").ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "formatCode", null, "#,##0.00\\ \"€\"").ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteStartElementAsync(null, "fonts", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "count", null, "2").ConfigureAwait(false);
foreach (var bold in new[] { false, true })
{
await w.WriteStartElementAsync(null, "font", MainNs).ConfigureAwait(false);
if (bold)
{
await w.WriteElementStringAsync(null, "b", MainNs, string.Empty).ConfigureAwait(false);
}
await WriteValElementAsync(w, "sz", "11").ConfigureAwait(false);
await WriteValElementAsync(w, "name", "Calibri").ConfigureAwait(false);
await WriteValElementAsync(w, "family", "2").ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteStartElementAsync(null, "fills", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "count", null, "2").ConfigureAwait(false);
foreach (var pattern in new[] { "none", "gray125" })
{
await w.WriteStartElementAsync(null, "fill", MainNs).ConfigureAwait(false);
await w.WriteStartElementAsync(null, "patternFill", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "patternType", null, pattern).ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteStartElementAsync(null, "borders", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "count", null, "1").ConfigureAwait(false);
await w.WriteStartElementAsync(null, "border", MainNs).ConfigureAwait(false);
foreach (var side in new[] { "left", "right", "top", "bottom", "diagonal" })
{
await w.WriteElementStringAsync(null, side, MainNs, string.Empty).ConfigureAwait(false);
}
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteStartElementAsync(null, "cellStyleXfs", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "count", null, "1").ConfigureAwait(false);
await WriteXfAsync(w, numberFormat: 0, font: 0, cellXf: false).ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
// The order matches the Style* constants.
(int NumberFormat, int Font)[] cellXfs = [(0, 0), (0, 1), (14, 0), (22, 0), (3, 0), (4, 0), (164, 0), (10, 0), (49, 0)];
await w.WriteStartElementAsync(null, "cellXfs", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "count", null, cellXfs.Length.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
foreach (var (numberFormat, font) in cellXfs)
{
await WriteXfAsync(w, numberFormat, font, cellXf: true).ConfigureAwait(false);
}
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteStartElementAsync(null, "cellStyles", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "count", null, "1").ConfigureAwait(false);
await w.WriteStartElementAsync(null, "cellStyle", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "name", null, "Normal").ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "xfId", null, "0").ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "builtinId", null, "0").ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
private static async Task WriteValElementAsync(XmlWriter w, string name, string value)
{
await w.WriteStartElementAsync(null, name, MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "val", null, value).ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
private static async Task WriteXfAsync(XmlWriter w, int numberFormat, int font, bool cellXf)
{
await w.WriteStartElementAsync(null, "xf", MainNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "numFmtId", null, numberFormat.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "fontId", null, font.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "fillId", null, "0").ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "borderId", null, "0").ConfigureAwait(false);
if (cellXf)
{
await w.WriteAttributeStringAsync(null, "xfId", null, "0").ConfigureAwait(false);
if (numberFormat != 0)
{
await w.WriteAttributeStringAsync(null, "applyNumberFormat", null, "1").ConfigureAwait(false);
}
if (font != 0)
{
await w.WriteAttributeStringAsync(null, "applyFont", null, "1").ConfigureAwait(false);
}
}
await w.WriteEndElementAsync().ConfigureAwait(false);
}
private async Task WriteWorkbookRelationshipsAsync(XmlWriter w)
{
await w.WriteStartElementAsync(null, "Relationships", PackageRelNs).ConfigureAwait(false);
for (var i = 1; i <= _sheetNames.Count; i++)
{
var id = i.ToString(CultureInfo.InvariantCulture);
await WriteRelationshipAsync(w, "rId" + id, RelNs + "/worksheet", "worksheets/sheet" + id + ".xml").ConfigureAwait(false);
}
var next = _sheetNames.Count + 1;
await WriteRelationshipAsync(w, "rId" + next.ToString(CultureInfo.InvariantCulture), RelNs + "/styles", "styles.xml").ConfigureAwait(false);
if (_options.UseSharedStrings)
{
await WriteRelationshipAsync(w, "rId" + (next + 1).ToString(CultureInfo.InvariantCulture), RelNs + "/sharedStrings", "sharedStrings.xml").ConfigureAwait(false);
}
await w.WriteEndElementAsync().ConfigureAwait(false);
}
private static async Task WritePackageRelationshipsAsync(XmlWriter w)
{
await w.WriteStartElementAsync(null, "Relationships", PackageRelNs).ConfigureAwait(false);
await WriteRelationshipAsync(w, "rId1", RelNs + "/officeDocument", "xl/workbook.xml").ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
private static async Task WriteRelationshipAsync(XmlWriter w, string id, string type, string target)
{
await w.WriteStartElementAsync(null, "Relationship", PackageRelNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "Id", null, id).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "Type", null, type).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "Target", null, target).ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
private async Task WriteContentTypesAsync(XmlWriter w)
{
await w.WriteStartElementAsync(null, "Types", ContentTypesNs).ConfigureAwait(false);
await WriteDefaultTypeAsync(w, "rels", "application/vnd.openxmlformats-package.relationships+xml").ConfigureAwait(false);
await WriteDefaultTypeAsync(w, "xml", "application/xml").ConfigureAwait(false);
await WriteOverrideAsync(w, "/xl/workbook.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml").ConfigureAwait(false);
for (var i = 1; i <= _sheetNames.Count; i++)
{
await WriteOverrideAsync(w, "/xl/worksheets/sheet" + i.ToString(CultureInfo.InvariantCulture) + ".xml", WorksheetType).ConfigureAwait(false);
}
await WriteOverrideAsync(w, "/xl/styles.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml").ConfigureAwait(false);
if (_options.UseSharedStrings)
{
await WriteOverrideAsync(w, "/xl/sharedStrings.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml").ConfigureAwait(false);
}
await w.WriteEndElementAsync().ConfigureAwait(false);
}
private static async Task WriteDefaultTypeAsync(XmlWriter w, string extension, string contentType)
{
await w.WriteStartElementAsync(null, "Default", ContentTypesNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "Extension", null, extension).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "ContentType", null, contentType).ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
private static async Task WriteOverrideAsync(XmlWriter w, string part, string contentType)
{
await w.WriteStartElementAsync(null, "Override", ContentTypesNs).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "PartName", null, part).ConfigureAwait(false);
await w.WriteAttributeStringAsync(null, "ContentType", null, contentType).ConfigureAwait(false);
await w.WriteEndElementAsync().ConfigureAwait(false);
}
}
@@ -0,0 +1,188 @@
using System.Globalization;
using System.IO.Compression;
using System.Text;
namespace Khaemhat.Infrastructure.Files;
/// <summary>
/// Writes a ZIP archive straight to a stream that need not be seekable, such as an HTTP response (SPEC §9.4: mass
/// prints and "Scarica tutto" are streamed, never staged in temporary files). A thin wrapper over
/// <see cref="ZipArchive"/> in <see cref="ZipArchiveMode.Create"/> mode that only uses its asynchronous API, cleans
/// entry names and makes duplicates unique (<c>fattura.pdf</c>, <c>fattura (2).pdf</c>).
/// </summary>
/// <example>
/// <code>
/// await using var zip = await ZipStreamWriter.CreateAsync(response.Body, leaveOpen: true, cancellationToken);
/// await zip.AddAsync("fattura.pdf", pdfStream, cancellationToken: cancellationToken);
/// await zip.AddAsync("fattura.xml", xmlBytes, cancellationToken: cancellationToken);
/// </code>
/// </example>
public sealed class ZipStreamWriter : IAsyncDisposable
{
private const int MaxNameLength = 200;
private readonly ZipArchive _archive;
private readonly AsyncOutputBuffer _buffer;
private readonly Stream _output;
private readonly bool _leaveOpen;
private readonly HashSet<string> _names = new(StringComparer.OrdinalIgnoreCase);
private bool _disposed;
private ZipStreamWriter(ZipArchive archive, AsyncOutputBuffer buffer, Stream output, bool leaveOpen)
{
_archive = archive;
_buffer = buffer;
_output = output;
_leaveOpen = leaveOpen;
}
/// <summary>The number of entries written.</summary>
public int Count => _names.Count;
/// <summary>Starts an archive.</summary>
/// <param name="output">The stream that receives the archive.</param>
/// <param name="leaveOpen">Whether to leave <paramref name="output"/> open on dispose.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The writer; dispose it to write the central directory.</returns>
public static async Task<ZipStreamWriter> CreateAsync(Stream output, bool leaveOpen = false, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(output);
var buffer = new AsyncOutputBuffer(output);
var archive = await ZipArchive.CreateAsync(buffer, ZipArchiveMode.Create, leaveOpen: true, Encoding.UTF8, cancellationToken).ConfigureAwait(false);
return new ZipStreamWriter(archive, buffer, output, leaveOpen);
}
/// <summary>
/// Cleans an entry name: forward slashes for folders, no drive, no <c>..</c>, no leading slash, no characters that
/// Windows refuses, at most 200 characters.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>The clean name (<c>file</c> when nothing is left).</returns>
public static string CleanEntryName(string name)
{
ArgumentNullException.ThrowIfNull(name);
var parts = name.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries)
.Select(CleanSegment)
.Where(p => p.Length > 0 && p != "." && p != "..")
.ToArray();
var clean = string.Join('/', parts);
if (clean.Length > MaxNameLength)
{
var extension = Path.GetExtension(clean);
clean = clean[..(MaxNameLength - extension.Length)] + extension;
}
return clean.Length == 0 ? "file" : clean;
}
/// <summary>Adds an entry with the content of a stream, read to the end.</summary>
/// <param name="entryName">The entry name.</param>
/// <param name="content">The content.</param>
/// <param name="lastWrite">The date shown for the entry; now when omitted.</param>
/// <param name="level">The compression: <see cref="CompressionLevel.NoCompression"/> suits files already compressed (JPEG, ZIP, P7M).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The name actually used (made unique).</returns>
public async Task<string> AddAsync(
string entryName, Stream content, DateTimeOffset? lastWrite = null, CompressionLevel level = CompressionLevel.Optimal, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(content);
var (name, target) = await OpenEntryAsync(entryName, lastWrite, level, cancellationToken).ConfigureAwait(false);
await using (target.ConfigureAwait(false))
{
await content.CopyToAsync(target, cancellationToken).ConfigureAwait(false);
}
await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false);
return name;
}
/// <summary>Adds an entry with the given bytes.</summary>
/// <param name="entryName">The entry name.</param>
/// <param name="content">The content.</param>
/// <param name="lastWrite">The date shown for the entry; now when omitted.</param>
/// <param name="level">The compression.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The name actually used (made unique).</returns>
public async Task<string> AddAsync(
string entryName, ReadOnlyMemory<byte> content, DateTimeOffset? lastWrite = null, CompressionLevel level = CompressionLevel.Optimal, CancellationToken cancellationToken = default)
{
var (name, target) = await OpenEntryAsync(entryName, lastWrite, level, cancellationToken).ConfigureAwait(false);
await using (target.ConfigureAwait(false))
{
await target.WriteAsync(content, cancellationToken).ConfigureAwait(false);
}
await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false);
return name;
}
/// <summary>
/// Opens an entry for the caller to write (for example a generator writing a PDF directly into the archive). Write
/// to the stream with asynchronous calls and dispose it before adding the next entry (the few bytes written when it
/// is disposed are sent with the next call).
/// </summary>
/// <param name="entryName">The entry name.</param>
/// <param name="lastWrite">The date shown for the entry; now when omitted.</param>
/// <param name="level">The compression.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The name actually used and the entry stream.</returns>
public async Task<(string Name, Stream Content)> OpenEntryAsync(
string entryName, DateTimeOffset? lastWrite = null, CompressionLevel level = CompressionLevel.Optimal, CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_disposed, this);
await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false);
var name = Unique(CleanEntryName(entryName));
var entry = _archive.CreateEntry(name, level);
entry.LastWriteTime = lastWrite ?? DateTimeOffset.Now;
var stream = await entry.OpenAsync(cancellationToken).ConfigureAwait(false);
return (name, stream);
}
/// <summary>Writes the central directory and closes the stream unless left open.</summary>
/// <returns>A task.</returns>
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
_disposed = true;
await _archive.DisposeAsync().ConfigureAwait(false);
await _buffer.FlushAsync().ConfigureAwait(false);
await _buffer.DisposeAsync().ConfigureAwait(false);
if (!_leaveOpen)
{
await _output.DisposeAsync().ConfigureAwait(false);
}
}
private static string CleanSegment(string segment)
{
var builder = new StringBuilder(segment.Length);
foreach (var c in segment)
{
builder.Append(char.IsControl(c) || c is ':' or '*' or '?' or '"' or '<' or '>' or '|' ? '_' : c);
}
return builder.ToString().Trim().TrimEnd('.');
}
private string Unique(string name)
{
if (_names.Add(name))
{
return name;
}
var extension = Path.GetExtension(name);
var stem = name[..^extension.Length];
for (var i = 2; ; i++)
{
var candidate = string.Create(CultureInfo.InvariantCulture, $"{stem} ({i}){extension}");
if (_names.Add(candidate))
{
return candidate;
}
}
}
}