Improved reading and writing large Office files without copying them into memory (#1243)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-28 23:03:30 +01:00
1 parent 918572c158
commit dbe609a9a7
37 files changed
+1161 -471

No files matched your search

@@ -4,6 +4,8 @@ using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
using Microsoft.Extensions.Logging.Abstractions;
using A = DocumentFormat.OpenXml.Drawing;
using P = DocumentFormat.OpenXml.Presentation;
using P14 = DocumentFormat.OpenXml.Office2010.PowerPoint;
@@ -321,16 +323,8 @@ public sealed class PresentationWriterTests
new TestLayout("A Content", TestPlaceholder.Title(), TestPlaceholder.Text(1, TestTemplate.MASTER_BODY_BOUNDS), TestPlaceholder.Footer(10, FOOTER)),
new TestLayout("B Content", TestPlaceholder.Title(), TestPlaceholder.Text(2, TestTemplate.MASTER_BODY_BOUNDS), TestPlaceholder.Footer(12, FOOTER)));
var template = PresentationTemplate.Read(templateFile);
templateFile.Position = 0;
using var output = new MemoryStream();
await templateFile.CopyToAsync(output);
output.Position = 0;
await PresentationWriter.WriteAsync(output, template, new SlideDeckSpec("Weekly", [Keep(1)]), OPTIONS with { VariantLabel = "B" }, new FakePictureSource(), CancellationToken.None);
output.Position = 0;
using var document = PresentationDocument.Open(output, false);
var (file, _) = await WriteFromAsync(templateFile, new SlideDeckSpec("Weekly", [Keep(1)]), OPTIONS with { VariantLabel = "B" });
using var document = PresentationDocument.Open(file, false);
var slide = SlidesOf(document)[0];
using (Assert.EnterMultipleScope())
{
@@ -570,6 +564,61 @@ public sealed class PresentationWriterTests
}
}
[Test]
public async Task ARemovedVideoLeavesTheFile()
{
var templateOptions = new TestTemplateOptions(Slides: [new TestSlide(2, (TestPlaceholder.Title(), "Launch")) { Elements = [TestElement.Video(RIGHT_PICTURE, 4, 5, 6)] }]);
var deck = new SlideDeckSpec("Weekly", [Edit(1) with { Removals = ["element 1"] }]);
var (file, _) = await WriteAsync(deck, OPTIONS, templateOptions);
using var document = PresentationDocument.Open(file, false);
var slide = SlidesOf(document)[0];
using (Assert.EnterMultipleScope())
{
Assert.That(ValidationErrorsOf(document), Is.Empty);
Assert.That(slide.Slide!.Descendants<P.Picture>(), Is.Empty);
Assert.That(slide.ImageParts, Is.Empty, "The poster frame leaves the file along with its shape.");
Assert.That(slide.DataPartReferenceRelationships, Is.Empty, "The slide no longer refers to the video.");
Assert.That(document.DataParts, Is.Empty, "The video leaves the file along with its shape.");
}
}
[Test]
public async Task ALinkOfAKeptSlideKeepsNoRemovedSlideInTheFile()
{
var templateOptions = new TestTemplateOptions(Slides:
[
new TestSlide(2, (TestPlaceholder.Title(), "Agenda")) { Elements = [TestElement.TextBox(HEADING, "Launch"), TestElement.TextBox(LEFT_TEXT, "Budget")] },
new TestSlide(2, (TestPlaceholder.Title(), "Launch")) { Elements = [TestElement.Video(RIGHT_PICTURE, 4, 5, 6)] },
new TestSlide(2, (TestPlaceholder.Title(), "Budget"))
]);
using var templateFile = TestTemplate.Create(templateOptions, Layouts());
using (var templateDocument = PresentationDocument.Open(templateFile, true))
{
// The agenda leads to both other slides, as a table of contents does:
var templateSlides = SlidesOf(templateDocument);
LinkText(templateSlides[0], "Launch", templateSlides[1]);
LinkText(templateSlides[0], "Budget", templateSlides[2]);
}
var (file, _) = await WriteFromAsync(templateFile, new SlideDeckSpec("Weekly", [Keep(1), Keep(3)]), OPTIONS);
using var document = PresentationDocument.Open(file, false);
var slides = SlidesOf(document);
var links = slides[0].Slide!.Descendants<A.HyperlinkOnClick>().ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(ValidationErrorsOf(document), Is.Empty);
Assert.That(document.GetAllParts().OfType<SlidePart>().Count(), Is.EqualTo(2), "The removed slide leaves the file, although the agenda led to it.");
Assert.That(document.DataParts, Is.Empty, "The video of the removed slide leaves the file along with it.");
Assert.That(links, Has.Count.EqualTo(1), "Only the link to the slide which is gone is gone.");
Assert.That(links.Select(link => slides[0].GetPartById(link.Id!.Value!)), Has.All.SameAs(slides[1]), "The link to the kept slide still leads to it.");
Assert.That(slides[0].Slide!.InnerText, Does.Contain("Launch"), "The text of the link stays, as a plain text.");
}
}
[Test]
public async Task RemovingAnAnimatedShapeDropsTheAnimationsOfItsSlide()
{
@@ -676,6 +725,15 @@ public sealed class PresentationWriterTests
private static P.Shape ShapeWithIdOf(SlidePart slide, uint id) => slide.Slide!.Descendants<P.Shape>()
.Single(shape => shape.NonVisualShapeProperties?.NonVisualDrawingProperties?.Id?.Value == id);
/// <summary>
/// Turns a text of a slide into a link to another slide, as PowerPoint writes one.
/// </summary>
private static void LinkText(SlidePart slide, string text, SlidePart target)
{
var run = slide.Slide!.Descendants<A.Run>().Single(run => run.InnerText == text);
run.RunProperties = new A.RunProperties(new A.HyperlinkOnClick { Id = slide.GetIdOfPart(slide.AddPart(target)), Action = "ppaction://hlinksldjump" });
}
private static TestLayout[] Layouts() =>
[
new("A Title", TestPlaceholder.Title(), TestPlaceholder.Subtitle(SUBTITLE), TestPlaceholder.Footer(10, FOOTER), TestPlaceholder.SlideNumber(11, SLIDE_NUMBER)),
@@ -696,19 +754,29 @@ public sealed class PresentationWriterTests
/// <summary>
/// Writes a presentation from a template file of the test's own, e.g., from a presentation written before.
/// </summary>
/// <remarks>
/// The presentation comes about as in the Slide Assistant: from a template file into the file the user chose.
/// </remarks>
private static async Task<WrittenPresentation> WriteFromAsync(Stream templateFile, SlideDeckSpec deck, PresentationWriteOptions options, IPictureSource? pictures = null)
{
templateFile.Position = 0;
var template = PresentationTemplate.Read(templateFile);
templateFile.Position = 0;
var folder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName;
try
{
var templatePath = Path.Join(folder, "template.pptx");
var targetPath = Path.Join(folder, "presentation.pptx");
templateFile.Position = 0;
await using (var file = new FileStream(templatePath, FileMode.CreateNew, FileAccess.Write))
await templateFile.CopyToAsync(file);
// The writer edits a copy of the template, as the Slide Assistant does with one on disk:
var output = new MemoryStream();
await templateFile.CopyToAsync(output);
output.Position = 0;
var result = await PresentationWriter.WriteAsync(output, template, deck, options, pictures ?? new FakePictureSource(), CancellationToken.None);
output.Position = 0;
return new WrittenPresentation(output, result);
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
var result = await PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, options, pictures ?? new FakePictureSource(), NullLogger.Instance, CancellationToken.None);
Assert.That(result.IsWritten, Is.True, "The template stays as it is, so the deck still fits.");
return new WrittenPresentation(new MemoryStream(await File.ReadAllBytesAsync(targetPath)), result);
}
finally
{
Directory.Delete(folder, true);
}
}
private static List<string> ValidationErrorsOf(PresentationDocument document) => new OpenXmlValidator(FileFormatVersions.Office2019)
@@ -765,5 +833,5 @@ public sealed class PresentationWriterTests
/// </summary>
/// <param name="File">The presentation, positioned at its start.</param>
/// <param name="Result">What happened beyond writing.</param>
private sealed record WrittenPresentation(MemoryStream File, PresentationWriteResult Result);
private sealed record WrittenPresentation(MemoryStream File, PresentationFileResult Result);
}