Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions src/EPPlus.Export.Pdf.Tests/PdfParallelExportTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*************************************************************************************************
Required Notice: Copyright (C) EPPlus Software AB.
This software is licensed under PolyForm Noncommercial License 1.0.0
and may only be used for noncommercial purposes
https://polyformproject.org/licenses/noncommercial/1.0.0/

A commercial license to use this software can be purchased at https://epplussoftware.com
*************************************************************************************************
Date Author Change
*************************************************************************************************
12/04/2026 EPPlus Software AB EPPlus 9
*************************************************************************************************/
using EPPlus.Export.Pdf.Tests;
using OfficeOpenXml;
using OfficeOpenXml.Export.PdfExport;
using OfficeOpenXml.Export.PdfExport.Settings;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EPPlusTest.PDF
{
/// <summary>
/// Concurrent exports must not share shaping state: every export of the same workbook
/// should produce the same bytes.
/// </summary>
[TestClass]
public class PdfParallelExportTests : PdfTestBase
{
private const int ExportCount = 8;
private const int Rounds = 3;

// PDFTest.xlsx has &D and &T in a header, and the document info has creation and
// modification dates. Pinning the export time keeps the output independent of the clock.
internal static readonly DateTime FixedExportTime = new DateTime(2026, 1, 2, 3, 4, 5);

[TestMethod]
public void ParallelExportsOfSameWorkbookProduceIdenticalPdfTest()
{
var reference = Export();

for (int round = 0; round < Rounds; round++)
{
var results = new byte[ExportCount][];
using (var start = new Barrier(ExportCount))
{
var tasks = new Task[ExportCount];
for (int i = 0; i < ExportCount; i++)
{
int index = i;
tasks[i] = Task.Factory.StartNew(() =>
{
start.SignalAndWait();
results[index] = Export();
}, TaskCreationOptions.LongRunning);
}
Task.WaitAll(tasks);
}

for (int i = 0; i < ExportCount; i++)
{
var actual = results[i];
if (reference.AsSpan().SequenceEqual(actual)) continue;
Assert.Fail($"Round {round}, export {i}: PDF differs from the sequential export " +
$"(length {actual.Length} vs {reference.Length}). {DescribeFirstDifference(reference, actual)}");
}
}
}

private static byte[] Export()
{
// Each export uses its own package: a package is not meant to be shared between threads.
using var p = OpenTemplatePackage("PDFTest.xlsx");
var wb = p.Workbook;
using var ms = new MemoryStream();
// Same settings ExcelWorkbook.SaveAsPdf builds, with the export time pinned.
var settings = GetPdfSettings.BuildBase(wb, wb.Worksheets[wb.View.ActiveTab].PrinterSettings, null);
settings.ExportTime = FixedExportTime;
new EPPlusToPdfWriter(settings, wb).Save(ms);
return ms.ToArray();
}

private static string DescribeFirstDifference(byte[] expected, byte[] actual)
{
int n = Math.Min(expected.Length, actual.Length);
int at = 0;
while (at < n && expected[at] == actual[at]) at++;
int from = Math.Max(0, at - 40);
var latin1 = Encoding.GetEncoding("ISO-8859-1");
string Excerpt(byte[] b) => latin1.GetString(b, from, Math.Min(120, b.Length - from)).Replace("\n", "\\n");
return $"First difference at offset {at}. Expected: '{Excerpt(expected)}' Actual: '{Excerpt(actual)}'";
}
}
}
13 changes: 11 additions & 2 deletions src/EPPlus.Export.Pdf.Tests/PdfTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -364,10 +364,19 @@ public void FileAndStreamProduceSamePdfLengthTest()
string tempFile = Path.GetTempFileName();
try
{
wb.SaveAsPdf(tempFile);
// Builds the same settings as ExcelWorkbook.SaveAsPdf, with the export time pinned:
// PDFTest.xlsx has &D and &T in a header, so two exports in different minutes
// produce different content and can differ in length.
PdfRenderSettings Settings()
{
var s = GetPdfSettings.BuildBase(wb, wb.Worksheets[wb.View.ActiveTab].PrinterSettings, null);
s.ExportTime = PdfParallelExportTests.FixedExportTime;
return s;
}
new EPPlusToPdfWriter(Settings(), wb).Save(tempFile);
long fileLength = new FileInfo(tempFile).Length;
using var ms = new MemoryStream();
wb.SaveAsPdf(ms);
new EPPlusToPdfWriter(Settings(), wb).Save(ms);
Assert.AreEqual(fileLength, ms.Length, "Stream output length differs from file output length.");
}
finally
Expand Down
4 changes: 3 additions & 1 deletion src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,20 @@ internal class PdfInfoObject : PdfObject
internal string LicenseType;
internal string LicenseHolder;
internal string Author;
internal DateTime ExportTime;

public PdfInfoObject(int objectNumber, PdfDocumentSettings documentSettings, int version = 0) : base(objectNumber, version)
{
Title = documentSettings.Title;
Author = documentSettings.Author;
LicenseType = documentSettings.LicenseType;
LicenseHolder = documentSettings.LicenseHolder;
ExportTime = documentSettings.ExportTime == default(DateTime) ? DateTime.Now : documentSettings.ExportTime;
}

private string Body()
{
DateTime now = DateTime.Now;
DateTime now = ExportTime;
TimeSpan offset = TimeZoneInfo.Local.GetUtcOffset(now);
string sign = offset < TimeSpan.Zero ? "-" : "+";
offset = offset.Duration();
Expand Down
55 changes: 55 additions & 0 deletions src/EPPlus.Export.Pdf/Resources/PdfDictionaries.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ Date Author Change
27/11/2025 EPPlus Software AB EPPlus 9
08/17/2026 EPPlus Software AB Canonical FontKey + resolve cache
08/20/2026 EPPlus Software AB Document-wide subsetting via DocumentFontSubsetBuilder
12/04/2026 EPPlus Software AB One unsubset font provider per requested font and export
*************************************************************************************************/
using EPPlus.Export.Pdf.Settings;
using EPPlus.Fonts.OpenType;
using EPPlus.Fonts.OpenType.Integration;
using EPPlus.Fonts.OpenType.Subsetting;
using EPPlus.Fonts.OpenType.TextShaping;
using OfficeOpenXml.Interfaces.Fonts;
using System.Collections.Generic;
using System.Linq;
Expand All @@ -29,8 +31,13 @@ internal class PdfDictionaries
internal readonly Dictionary<string, PdfShadingResource> Shadings = new Dictionary<string, PdfShadingResource>();
internal readonly Dictionary<string, PdfImageResource> Images = new Dictionary<string, PdfImageResource>();
internal Dictionary<FontKey, IFontProvider> ShapedProviders = new Dictionary<FontKey, IFontProvider>();
// Shapers and layout engines are reused within one export only. TextShaper keeps
// per-call state and is not thread-safe, so it must not be shared between exports.
private readonly Dictionary<IFontProvider, TextShaper> _shapers = new Dictionary<IFontProvider, TextShaper>();
private readonly Dictionary<IFontProvider, TextLayoutEngine> _layoutEngines = new Dictionary<IFontProvider, TextLayoutEngine>();
private DocumentFontSubsetBuilder _subsetBuilder;
private readonly Dictionary<string, FontKey> _requestedToKey = new Dictionary<string, FontKey>();
private readonly Dictionary<string, IFontProvider> _unsubsetProviders = new Dictionary<string, IFontProvider>();

private static string BuildRequestCacheKey(string family, FontSubFamily subFamily)
{
Expand All @@ -52,6 +59,54 @@ internal FontKey ResolveFontKey(PdfRenderSettings pageSettings, string family, F
return key;
}

/// <summary>
/// Returns a provider for the full (not subset) font, for text shaped before the subsets
/// exist. One provider per requested font and export: the shaper and layout engine are
/// cached per provider, so a new provider per text fragment would build a new shaper, with
/// its kerning data, for every fragment.
/// </summary>
internal IFontProvider GetUnsubsetProvider(PdfRenderSettings pageSettings, string family, FontSubFamily subFamily)
{
var cacheKey = BuildRequestCacheKey(family, subFamily);
IFontProvider provider;
if (!_unsubsetProviders.TryGetValue(cacheKey, out provider))
{
var font = pageSettings.FontEngine.LoadFont(family, subFamily);
provider = new DefaultFontProvider(pageSettings.FontEngine, font);
_unsubsetProviders[cacheKey] = provider;
}
return provider;
}

/// <summary>
/// Returns the shaper for <paramref name="provider"/> in this export, creating it on first use.
/// </summary>
internal TextShaper GetShaper(IFontProvider provider)
{
TextShaper shaper;
if (!_shapers.TryGetValue(provider, out shaper))
{
shaper = new TextShaper(provider);
_shapers[provider] = shaper;
}
return shaper;
}

/// <summary>
/// Returns the layout engine for <paramref name="provider"/> in this export, built on the
/// export's shaper for that provider.
/// </summary>
internal TextLayoutEngine GetLayoutEngine(IFontProvider provider)
{
TextLayoutEngine layoutEngine;
if (!_layoutEngines.TryGetValue(provider, out layoutEngine))
{
layoutEngine = new TextLayoutEngine(GetShaper(provider));
_layoutEngines[provider] = layoutEngine;
}
return layoutEngine;
}

public void AddFont(PdfRenderSettings pageSettings, string fontName, FontSubFamily subFamily, string text)
{
EnsureBuilder(pageSettings);
Expand Down
3 changes: 3 additions & 0 deletions src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Date Author Change
27/11/2025 EPPlus Software AB EPPlus 9
*************************************************************************************************/
using EPPlus.Fonts.OpenType;
using System;
using System.Collections.Generic;

namespace EPPlus.Export.Pdf.Settings
Expand All @@ -33,6 +34,7 @@ internal class PdfDocumentSettings
internal string BookmarkNamePrefix;
internal bool SuppressFormFieldDetection;
internal PdfCompressionLevel CompressionLevel;
internal DateTime ExportTime;

internal static PdfDocumentSettings From(PdfRenderSettings s)
{
Expand All @@ -54,6 +56,7 @@ internal static PdfDocumentSettings From(PdfRenderSettings s)
BookmarkNamePrefix = s.BookmarkNamePrefix,
SuppressFormFieldDetection = s.SuppressFormFieldDetection,
CompressionLevel = s.CompressionLevel,
ExportTime = s.ExportTime,
};
}

Expand Down
8 changes: 8 additions & 0 deletions src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Date Author Change
using EPPlus.Export.Pdf.Settings.PdfPageSizes;
using EPPlus.Fonts.OpenType;
using OfficeOpenXml.Interfaces.Fonts;
using System;
using System.Collections.Generic;

namespace EPPlus.Export.Pdf.Settings
Expand All @@ -27,6 +28,13 @@ internal class PdfRenderSettings
internal string LicenseType { get; set; }
internal string LicenseHolder { get; set; }

/// <summary>
/// The time of this export, taken once when the settings are created. Used for the
/// header/footer date and time codes (&amp;D, &amp;T) and the document's creation and
/// modification dates, so every page and the metadata show the same time.
/// </summary>
internal DateTime ExportTime { get; set; } = DateTime.Now;

private OpenTypeFontEngine _fontEngine;
/// <summary>
/// Get the current font engine that is being used by EPPlus.
Expand Down
116 changes: 116 additions & 0 deletions src/EPPlus.Fonts.OpenType.Benchmarks/BenchmarkFonts.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*************************************************************************************************
Required Notice: Copyright (C) EPPlus Software AB.
This software is licensed under PolyForm Noncommercial License 1.0.0
and may only be used for noncommercial purposes
https://polyformproject.org/licenses/noncommercial/1.0.0/

A commercial license to use this software can be purchased at https://epplussoftware.com
*************************************************************************************************
Date Author Change
*************************************************************************************************
12/03/2026 EPPlus Software AB Shared font setup for the benchmarks
*************************************************************************************************/
using OfficeOpenXml.Interfaces.Fonts;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace EPPlus.Fonts.OpenType.Benchmarks
{
/// <summary>
/// Font files and sample texts shared by the benchmarks. Every font is read from the
/// benchmark's own Fonts folder, so the results do not depend on what is installed on the
/// machine running them.
/// </summary>
internal static class BenchmarkFonts
{
public const string Roboto = "Roboto-Regular.ttf";
public const string BizUdGothic = "BIZUDGothic-Regular.ttf";
public const string NotoSansArabic = "NotoSansArabic-Regular.ttf";
public const string Oi = "Oi-Regular.ttf";
public const string SourceSans3 = "SourceSans3-Regular.otf";
public const string EBGaramond = "EBGaramond-Regular.ttf";

public static string FontsPath
{
get
{
var path = Path.Combine(AppContext.BaseDirectory, "Fonts");
if (!Directory.Exists(path))
throw new DirectoryNotFoundException($"Fonts directory not found: {path}");
return path;
}
}

/// <summary>
/// An engine that only searches the given folder, or the benchmark's Fonts folder.
/// </summary>
public static OpenTypeFontEngine CreateEngine(string? folder = null, Action<IEpplusFontConfiguration>? configure = null)
{
var path = folder ?? FontsPath;
return new OpenTypeFontEngine(cfg =>
{
cfg.FontDirectories.Add(path);
cfg.SearchSystemDirectories = false;
configure?.Invoke(cfg);
});
}

/// <summary>
/// Loads a font file directly, bypassing name resolution.
/// </summary>
public static OpenTypeFont LoadFile(OpenTypeFontEngine engine, string fileName)
{
return engine.GetFromBytes(File.ReadAllBytes(Path.Combine(FontsPath, fileName)));
}

/// <summary>
/// The characters of the Basic Multilingual Plane that the font maps, in code point
/// order, optionally limited to the given ranges and count.
/// </summary>
public static string GetMappedChars(OpenTypeFont font, int maxCount = int.MaxValue, params (int First, int Last)[] ranges)
{
if (ranges.Length == 0)
ranges = new[] { (0x20, 0xFFFF) };

var sb = new StringBuilder();
foreach (var (first, last) in ranges)
{
for (int cp = first; cp <= last && sb.Length < maxCount; cp++)
{
if (cp >= 0xD800 && cp <= 0xDFFF)
continue;
if (font.CmapTable.TryGetGlyphId((uint)cp, out var glyphId) && glyphId != 0)
sb.Append((char)cp);
}
}
return sb.ToString();
}

public static string Repeat(string text, int minLength)
{
var sb = new StringBuilder(minLength + text.Length);
while (sb.Length < minLength)
sb.Append(text).Append(' ');
return sb.ToString();
}

public const string LatinSample =
"The quick brown fox jumps over the lazy dog. Office efficiency, AVAWAY Tolerance 2026.";

// Arabic with joining forms, lam-alef ligatures and vowel marks.
public const string ArabicSample =
"مرحبا بالعالم، هذا نص تجريبي لقياس أداء تشكيل النص العربي. " +
"اَلْكِتَابُ مُفِيدٌ جِدًّا وَالْمَكْتَبَةُ لَا تُغْلَقُ أَبَدًا.";

// Japanese with kanji, hiragana, katakana and full-width punctuation.
public const string JapaneseSample =
"東京都の天気は晴れです。今日は午後三時から会議があります。" +
"データベースのテキストをコンピューターで計測します。";

// One spreadsheet cell's worth of mixed scripts: Latin, Japanese, Arabic and emoji.
public const string MixedSample =
"Total 東京支店 1 234,50 € — الإجمالي ٣٤٥ ✅ 🚀 Q3 売上高 مبيعات 👍🏽";
}
}
Loading
Loading