using System.IO.Compression; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; namespace AIStudio.Tools.OpenXml; /// /// Writes a copy of an Office document in which some parts have a changed DOM, without holding the rest of the /// document in memory. /// /// /// /// The Open XML SDK saves a package in the update mode of ZipArchive, which loads every entry behind the first changed /// one into memory, e.g., all pictures and videos behind the first slide, often hundreds of megabytes. So the source /// stays open for reading only, and a new archive comes about entry by entry: each entry of the source is streamed /// through in its order, and each changed part is written from its DOM instead. /// /// /// This serves only changes within the XML of existing parts. Whoever adds or removes parts or relationships, as the /// Slide Assistant does, needs the SDK to save the package. /// /// internal static class PackageRewrite { /// /// Writes a copy of the source with the DOM of the changed parts. /// /// The source, which stays as it is. /// The parts of the source, opened by the SDK, whose DOM changed. /// The new document, which must not exist yet. /// The cancellation token, checked between entries. /// A changed part has no entry in the source, e.g., because the source changed. public static void Write(string sourcePath, IReadOnlyCollection changedParts, string documentPath, CancellationToken token) { var partsByEntry = changedParts.ToDictionary(EntryNameOf, StringComparer.OrdinalIgnoreCase); using var sourceFile = TemplateFile.OpenRead(sourcePath); using var source = new ZipArchive(sourceFile, ZipArchiveMode.Read); using var documentFile = new FileStream(documentPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None); using var document = new ZipArchive(documentFile, ZipArchiveMode.Create); var written = 0; foreach (var entry in source.Entries) { token.ThrowIfCancellationRequested(); if (partsByEntry.TryGetValue(entry.FullName, out var part)) { var newEntry = CreateEntryLike(document, entry, CompressionLevel.Optimal); using var stream = newEntry.Open(); RootElementOf(part).Save(stream); written++; continue; } // A stored entry, such as a video, stays stored; deflating it once more would take time and gain nothing: var copy = CreateEntryLike(document, entry, entry.CompressedLength >= entry.Length ? CompressionLevel.NoCompression : CompressionLevel.Optimal); using var from = entry.Open(); using var to = copy.Open(); from.CopyTo(to); } if (written != partsByEntry.Count) throw new InvalidOperationException($"{partsByEntry.Count - written} changed part(s) have no entry in the document '{sourcePath}'."); } /// /// The name of the entry which holds a part, e.g., "ppt/slides/slide1.xml" for the part "/ppt/slides/slide1.xml". /// private static string EntryNameOf(OpenXmlPart part) => Uri.UnescapeDataString(part.Uri.OriginalString).TrimStart('/'); private static OpenXmlPartRootElement RootElementOf(OpenXmlPart part) => part.RootElement ?? throw new InvalidOperationException($"The changed part '{part.Uri}' has no XML."); private static ZipArchiveEntry CreateEntryLike(ZipArchive archive, ZipArchiveEntry entry, CompressionLevel compressionLevel) { var newEntry = archive.CreateEntry(entry.FullName, compressionLevel); newEntry.LastWriteTime = entry.LastWriteTime; newEntry.ExternalAttributes = entry.ExternalAttributes; return newEntry; } }