2026-10-25 18:52:39 +01:00
using DocumentFormat.OpenXml ;
using DocumentFormat.OpenXml.Packaging ;
using A = DocumentFormat . OpenXml . Drawing ;
using P = DocumentFormat . OpenXml . Presentation ;
namespace AIStudio.Tools.PowerPoint ;
/// <summary>
/// Writes a presentation from a template and a checked slide deck.
/// </summary>
/// <remarks>
/// The presentation is the template itself, with its slides replaced: masters, layouts, theme, fonts
/// and table styles stay exactly as their author made them. Every new slide is based on a layout of
/// the template and fills that layout's placeholders, without any formatting of its own, so the
/// corporate design applies to everything written here. Slots without content get no placeholder
/// at all, which leaves no prompt text such as "Click to add text" behind. Picture slots are the
/// exception when the user asks for it: an empty one keeps its placeholder, which shows the prompt
/// text of the layout while editing and nothing in the slide show, so that the user can insert a
/// picture of their own.
///
/// The template slides the deck refers to stay, with their pictures and notes. They take the color
/// variant and the footer of the presentation, so that they look like the slides around them. A
/// slide the model edited takes its new content into its slots, and keeps the rest.
///
/// The deck has to pass the SlideDeckSpecValidator first; what fits the template is not
/// checked again here.
/// </remarks>
internal static partial class PresentationWriter
{
/// <summary>
/// The smallest slide ID PowerPoint accepts.
/// </summary>
private const uint FIRST_SLIDE_ID = 256 ;
/// <summary>
2026-11-28 23:03:30 +01:00
/// Writes the presentation into the skeleton of the template, which it edits in place.
2026-10-25 18:52:39 +01:00
/// </summary>
/// <remarks>
2026-11-28 23:03:30 +01:00
/// 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.
2026-10-25 18:52:39 +01:00
/// </remarks>
2026-11-28 23:03:30 +01:00
/// <param name="presentationFile">The skeleton of the template, a .pptx or a .potx, see PackageSkeleton.OpenForEditing; readable, writable, and seekable.</param>
2026-10-25 18:52:39 +01:00
/// <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>
2026-11-28 23:03:30 +01:00
/// <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 )
2026-10-25 18:52:39 +01:00
{
using ( var document = PresentationDocument . Open ( presentationFile , true ))
{
// A template (.potx) becomes a presentation; everything else about it stays:
if ( document . DocumentType != PresentationDocumentType . Presentation )
document . ChangeDocumentType ( PresentationDocumentType . Presentation );
var presentationPart = document . PresentationPart ?? throw new InvalidDataException ( "The file contains no presentation." );
var presentation = presentationPart . Presentation ?? throw new InvalidDataException ( "The file contains no presentation." );
var slides = deck . Slides ;
var keptSlideParts = RemoveSlides ( presentationPart , presentation , TemplateSlidePartUrisOf ( template , slides ));
var layoutParts = presentationPart . SlideMasterParts . SelectMany ( master => master . SlideLayoutParts ). ToDictionary ( part => part . Uri );
var tableStyleId = presentationPart . TableStylesPart ?. TableStyleList ?. Default ?. Value ;
var slideIdList = presentation . SlideIdList ??= new P . SlideIdList ();
var variantLabel = VariantLabelOf ( template , options );
var slideIds = new List < uint >( slides . Count );
var usedTemplateSlides = new HashSet < Uri >();
var slideArea = ( double ) template . SlideWidth * template . SlideHeight ;
for ( var index = 0 ; index < slides . Count ; index ++)
{
var slide = slides [ index ];
SlidePart slidePart ;
if ( slide . TemplateSlide is { } number )
{
var templateSlide = template . FindSlide ( number ) ?? throw new InvalidOperationException ( $"The slide deck uses template slide {number}, which the template does not have. Check the deck before writing it." );
slidePart = TemplateSlidePartOf ( keptSlideParts , usedTemplateSlides , templateSlide );
var layout = AdaptTemplateSlide ( slidePart , templateSlide , template , layoutParts , variantLabel , options . FooterText );
if ( slide . HasContent )
{
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." );
2026-11-28 23:03:30 +01:00
EditTemplateSlide ( slidePart , templateSlide , new SlideContent ( slide , layout , slidePart . SlideLayoutPart ?. SlideLayout , pictures , tableStyleId , options . FooterText , slideArea , options . KeepEmptyPicturePlaceholders ));
2026-10-25 18:52:39 +01:00
}
}
else
{
var family = template . FindFamily ( slide . Layout ) ?? throw new InvalidOperationException ( $"The slide deck uses the layout '{slide.Layout}', which the template does not have. Check the deck before writing it." );
var layout = family . GetLayout ( variantLabel );
var layoutPart = LayoutPartOf ( layoutParts , layout );
slidePart = presentationPart . AddNewPart < SlidePart >();
slidePart . AddPart ( layoutPart );
2026-11-28 23:03:30 +01:00
var content = new SlideContent ( slide , layout , layoutPart . SlideLayout , pictures , tableStyleId , options . FooterText , slideArea , options . KeepEmptyPicturePlaceholders );
2026-10-25 18:52:39 +01:00
slidePart . Slide = new P . Slide (
new P . CommonSlideData ( ShapeTreeOf ( slidePart , content )),
new P . ColorMapOverride ( new A . MasterColorMapping ()));
}
var slideId = FIRST_SLIDE_ID + ( uint ) index ;
slideIdList . Append ( new P . SlideId { Id = slideId , RelationshipId = presentationPart . GetIdOfPart ( slidePart ) });
slideIds . Add ( slideId );
}
WriteSections ( presentation , template , deck . Title , slides , slideIds );
}
}
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." );
/// <summary>
/// Removes the slides of the template, which are samples or hints for the user, except those the deck keeps.
/// </summary>
/// <remarks>
/// 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
2026-11-28 23:03:30 +01:00
/// the order of the deck. So do the links of the kept slides to the removed ones, see UnlinkRemovedSlides.
2026-10-25 18:52:39 +01:00
/// </remarks>
/// <param name="presentationPart">The presentation part, which holds the slides.</param>
/// <param name="presentation">The presentation, which lists the slides.</param>
/// <param name="keptSlides">Where the slides the deck keeps are stored inside the file.</param>
/// <returns>The slides the deck keeps, by where they are stored.</returns>
private static Dictionary < Uri , SlidePart > RemoveSlides ( PresentationPart presentationPart , P . Presentation presentation , IReadOnlySet < Uri > keptSlides )
{
var keptSlideParts = new Dictionary < Uri , SlidePart >();
2026-11-28 23:03:30 +01:00
var removedSlideParts = new HashSet < OpenXmlPart >();
2026-10-25 18:52:39 +01:00
foreach ( var slideId in presentation . SlideIdList ?. Elements < P . SlideId >(). ToList () ?? [])
{
if ( slideId . RelationshipId ?. Value is { } relationshipId && presentationPart . TryGetPartById ( relationshipId , out var slidePart ))
{
if ( slidePart is SlidePart keptSlidePart && keptSlides . Contains ( keptSlidePart . Uri ))
keptSlideParts . TryAdd ( keptSlidePart . Uri , keptSlidePart );
else
2026-11-28 23:03:30 +01:00
{
2026-10-25 18:52:39 +01:00
presentationPart . DeletePart ( slidePart );
2026-11-28 23:03:30 +01:00
removedSlideParts . Add ( slidePart );
}
2026-10-25 18:52:39 +01:00
}
slideId . Remove ();
}
2026-11-28 23:03:30 +01:00
UnlinkRemovedSlides ( presentationPart , removedSlideParts );
2026-10-25 18:52:39 +01:00
presentation . CustomShowList = null ;
RemoveSections ( presentation );
return keptSlideParts ;
}
2026-11-28 23:03:30 +01:00
/// <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 );
}
}
}
}
2026-10-25 18:52:39 +01:00
/// <summary>
/// The title of a slide of the deck: its own, or that of the template slide it keeps.
/// </summary>
private static string TitleOf ( SlideSpec slide , PresentationTemplate template ) => slide . Title . Length > 0
? slide . Title
: slide . TemplateSlide is { } number ? template . FindSlide ( number )?. Title ?? string . Empty : string . Empty ;
/// <summary>
/// Says which variant all slides are written in: the one the user chose, or the first one of
/// the template when it has no such variant.
/// </summary>
/// <returns>The label of the variant; null when the template carries every layout once.</returns>
private static string? VariantLabelOf ( PresentationTemplate template , PresentationWriteOptions options ) =>
options . VariantLabel is { } label && template . VariantLabels . Contains ( label )
? label
: template . VariantLabels . FirstOrDefault ();
/// <summary>
/// Everything needed to fill the shape tree of one slide.
/// </summary>
/// <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>
2026-11-28 23:03:30 +01:00
/// <param name="Pictures">The pictures the deck refers to, as far as they could be loaded.</param>
2026-10-25 18:52:39 +01:00
/// <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>
2026-11-28 23:03:30 +01:00
private sealed record SlideContent ( SlideSpec Slide , TemplateLayout Layout , P . SlideLayout ? LayoutElement , StagedPictures Pictures , string? TableStyleId , string FooterText , double SlideArea , bool KeepEmptyPicturePlaceholders );
2026-10-25 18:52:39 +01:00
}