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

@@ -34,42 +34,21 @@ internal static partial class PresentationWriter
private const uint FIRST_SLIDE_ID = 256;
/// <summary>
/// The picture formats PowerPoint shows everywhere. WebP, for instance, only newer versions do.
/// </summary>
private static readonly HashSet<string> SUPPORTED_PICTURE_TYPES = new(StringComparer.OrdinalIgnoreCase)
{
"image/png",
"image/jpeg",
"image/gif",
"image/bmp",
"image/tiff",
};
/// <summary>
/// Writes the presentation into a copy of the template, which it edits in place.
/// Writes the presentation into the skeleton of the template, which it edits in place.
/// </summary>
/// <remarks>
/// The caller copies the template, e.g., into a temporary file as PresentationFile does, so that the
/// template stays untouched and no further copy of the file is held in memory. The Open XML SDK
/// still holds the compressed parts of the whole file in memory while it saves: measured with a
/// template of 150 MB, editing a copy on disk allocated about 150 MB, while copying the file into
/// memory streams, as this writer did before, allocated about 810 MB.
/// The caller hands over a PackageSkeleton of the template, as PresentationFile does, which holds only its XML.
/// The Open XML SDK saves it in the update mode of ZipArchive, which loads every entry behind the first changed
/// one into memory; with a skeleton, that is XML only, never the pictures and videos of the template. A new picture
/// leaves its image part empty as well, and the skeleton takes it from its file later, see StagedPictures.Place.
/// </remarks>
/// <param name="presentationFile">A copy of the template, a .pptx or a .potx, positioned at its start; readable, writable, and seekable.</param>
/// <param name="presentationFile">The skeleton of the template, a .pptx or a .potx, see PackageSkeleton.OpenForEditing; readable, writable, and seekable.</param>
/// <param name="template">The template as read from the same file.</param>
/// <param name="deck">The slide deck, already checked against the template.</param>
/// <param name="options">What the user chose for the presentation as a whole.</param>
/// <param name="pictures">Where the pictures the deck refers to come from.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>What happened beyond writing.</returns>
public static async Task<PresentationWriteResult> WriteAsync(Stream presentationFile, PresentationTemplate template, SlideDeckSpec deck, PresentationWriteOptions options, IPictureSource pictures, CancellationToken token)
/// <param name="pictures">The pictures the deck refers to, as far as they could be loaded.</param>
public static void Write(Stream presentationFile, PresentationTemplate template, SlideDeckSpec deck, PresentationWriteOptions options, StagedPictures pictures)
{
//
// Loading the pictures is the only part which waits. The document is edited in one go
// afterwards, since the Open XML SDK works synchronously:
//
var (loadedPictures, skippedPictures) = await LoadPicturesAsync(deck, pictures, token);
using (var document = PresentationDocument.Open(presentationFile, true))
{
// A template (.potx) becomes a presentation; everything else about it stays:
@@ -103,7 +82,7 @@ internal static partial class PresentationWriter
if (layout is null)
throw new InvalidOperationException($"The slide deck writes content into template slide {number}, whose layout has no slots for it. Check the deck before writing it.");
EditTemplateSlide(slidePart, templateSlide, new SlideContent(slide, layout, slidePart.SlideLayoutPart?.SlideLayout, loadedPictures, tableStyleId, options.FooterText, slideArea, options.KeepEmptyPicturePlaceholders));
EditTemplateSlide(slidePart, templateSlide, new SlideContent(slide, layout, slidePart.SlideLayoutPart?.SlideLayout, pictures, tableStyleId, options.FooterText, slideArea, options.KeepEmptyPicturePlaceholders));
}
}
else
@@ -113,7 +92,7 @@ internal static partial class PresentationWriter
var layoutPart = LayoutPartOf(layoutParts, layout);
slidePart = presentationPart.AddNewPart<SlidePart>();
slidePart.AddPart(layoutPart);
var content = new SlideContent(slide, layout, layoutPart.SlideLayout, loadedPictures, tableStyleId, options.FooterText, slideArea, options.KeepEmptyPicturePlaceholders);
var content = new SlideContent(slide, layout, layoutPart.SlideLayout, pictures, tableStyleId, options.FooterText, slideArea, options.KeepEmptyPicturePlaceholders);
slidePart.Slide = new P.Slide(
new P.CommonSlideData(ShapeTreeOf(slidePart, content)),
new P.ColorMapOverride(new A.MasterColorMapping()));
@@ -126,30 +105,12 @@ internal static partial class PresentationWriter
WriteSections(presentation, template, deck.Title, slides, slideIds);
}
return new PresentationWriteResult(skippedPictures);
}
private static SlideLayoutPart LayoutPartOf(Dictionary<Uri, SlideLayoutPart> layoutParts, TemplateLayout layout) => layoutParts.TryGetValue(layout.PartUri, out var layoutPart)
? layoutPart
: throw new InvalidOperationException($"The template has no layout at '{layout.PartUri}'. The template was read from another file than the one being written.");
private static async Task<LoadedPictures> LoadPicturesAsync(SlideDeckSpec deck, IPictureSource pictures, CancellationToken token)
{
var loaded = new Dictionary<int, SlidePicture>();
var skipped = new List<int>();
foreach (var number in deck.Slides.SelectMany(slide => slide.Pictures).Distinct())
{
var picture = await pictures.LoadAsync(number, token);
if (picture is { Width: > 0, Height: > 0 } && SUPPORTED_PICTURE_TYPES.Contains(picture.ContentType))
loaded[number] = picture;
else
skipped.Add(number);
}
return new LoadedPictures(loaded, skipped);
}
/// <summary>
/// Removes the slides of the template, which are samples or hints for the user, except those the deck keeps.
/// </summary>
@@ -157,7 +118,7 @@ internal static partial class PresentationWriter
/// Whatever lists slides by their IDs has to go with them, or PowerPoint finds references to
/// nothing and offers to repair the file: custom shows and sections. Sections are written anew
/// for the new slides. The kept slides lose their place in the list as well, and get it back in
/// the order of the deck.
/// the order of the deck. So do the links of the kept slides to the removed ones, see UnlinkRemovedSlides.
/// </remarks>
/// <param name="presentationPart">The presentation part, which holds the slides.</param>
/// <param name="presentation">The presentation, which lists the slides.</param>
@@ -166,6 +127,7 @@ internal static partial class PresentationWriter
private static Dictionary<Uri, SlidePart> RemoveSlides(PresentationPart presentationPart, P.Presentation presentation, IReadOnlySet<Uri> keptSlides)
{
var keptSlideParts = new Dictionary<Uri, SlidePart>();
var removedSlideParts = new HashSet<OpenXmlPart>();
foreach (var slideId in presentation.SlideIdList?.Elements<P.SlideId>().ToList() ?? [])
{
if (slideId.RelationshipId?.Value is { } relationshipId && presentationPart.TryGetPartById(relationshipId, out var slidePart))
@@ -173,17 +135,58 @@ internal static partial class PresentationWriter
if (slidePart is SlidePart keptSlidePart && keptSlides.Contains(keptSlidePart.Uri))
keptSlideParts.TryAdd(keptSlidePart.Uri, keptSlidePart);
else
{
presentationPart.DeletePart(slidePart);
removedSlideParts.Add(slidePart);
}
}
slideId.Remove();
}
UnlinkRemovedSlides(presentationPart, removedSlideParts);
presentation.CustomShowList = null;
RemoveSections(presentation);
return keptSlideParts;
}
/// <summary>
/// Removes the links from what stays in the file to the removed slides, e.g., those of a kept slide with a table of contents.
/// </summary>
/// <remarks>
/// A link to another slide is a relationship of the part which shows it. As long as one leads to a removed slide, the
/// Open XML SDK keeps that slide in the file, outside the list of slides, together with its pictures and videos:
/// nobody sees it, yet a kept table of contents easily keeps every other slide of the template. Once the last link is
/// gone, the SDK drops the slide. The text or shape of a link stays, without the link. A reference other than a link
/// keeps its slide rather than pointing into nothing, which would make PowerPoint offer to repair the file.
/// </remarks>
/// <param name="presentationPart">The presentation part, from which everything which stays can be reached.</param>
/// <param name="removedSlideParts">The slides which were removed from the presentation.</param>
private static void UnlinkRemovedSlides(PresentationPart presentationPart, IReadOnlySet<OpenXmlPart> removedSlideParts)
{
var visitedParts = new HashSet<OpenXmlPart>();
var pendingParts = new Stack<OpenXmlPart>([presentationPart]);
while (pendingParts.TryPop(out var part))
{
if (!visitedParts.Add(part))
continue;
foreach (var child in part.Parts.ToList())
{
if (!removedSlideParts.Contains(child.OpenXmlPart))
pendingParts.Push(child.OpenXmlPart);
else if (part.RootElement is { } root)
{
foreach (var link in root.Descendants<A.HyperlinkType>().Where(link => link.Id?.Value == child.RelationshipId).ToList())
link.Remove();
if (!RelationshipIdsOf(root).Contains(child.RelationshipId))
part.DeletePart(child.RelationshipId);
}
}
}
}
/// <summary>
/// The title of a slide of the deck: its own, or that of the template slide it keeps.
/// </summary>
@@ -207,17 +210,10 @@ internal static partial class PresentationWriter
/// <param name="Slide">What goes on the slide.</param>
/// <param name="Layout">The layout the slide is based on, as read from the template.</param>
/// <param name="LayoutElement">The same layout in the document being written, whose placeholders the slide refers to.</param>
/// <param name="Pictures">The loaded pictures, by their numbers.</param>
/// <param name="Pictures">The pictures the deck refers to, as far as they could be loaded.</param>
/// <param name="TableStyleId">The default table style of the template, if it states one.</param>
/// <param name="FooterText">The footer text; empty for no footer.</param>
/// <param name="SlideArea">The area of a slide, in square EMU.</param>
/// <param name="KeepEmptyPicturePlaceholders">Whether a new slide keeps the picture placeholders which no picture fills.</param>
private sealed record SlideContent(SlideSpec Slide, TemplateLayout Layout, P.SlideLayout? LayoutElement, IReadOnlyDictionary<int, SlidePicture> Pictures, string? TableStyleId, string FooterText, double SlideArea, bool KeepEmptyPicturePlaceholders);
/// <summary>
/// The pictures a slide deck refers to, as far as they could be loaded.
/// </summary>
/// <param name="Pictures">The loaded pictures, by their numbers.</param>
/// <param name="Skipped">The numbers of the pictures which cannot be read, or which come in a format PowerPoint does not show.</param>
private sealed record LoadedPictures(IReadOnlyDictionary<int, SlidePicture> Pictures, IReadOnlyList<int> Skipped);
private sealed record SlideContent(SlideSpec Slide, TemplateLayout Layout, P.SlideLayout? LayoutElement, StagedPictures Pictures, string? TableStyleId, string FooterText, double SlideArea, bool KeepEmptyPicturePlaceholders);
}