以编程方式 change/add pptx powerpoint 的缩略图。使用 Openxml SDK?

Programmatically change/add thumbnail of pptx powerpoint. With Openxml sdk?

我将 openxml sdk 2.5 与 Eric White 的强大工具结合使用。我已经设法使用模板文件创建动态 pptx 演示文稿。 (在 C# 中) 不幸的是,缩略图在此过程中丢失了。
有没有办法使用 openxml 或电动工具(重新)创建 pptx 文件的缩略图?
我成功地编写了一些代码来更改带有图像的现有缩略图。但是当没有缩略图时,它会给我一个 System.NullReferenceException。这是代码:

using OpenXmlPowerTools;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Packaging;

namespace ConsoleApplication1
{
    class AddThumbnail_
    {
        public static void ReplaceThumbnail(ThumbnailPart thumbnailPart, string newThumbnail)
        {
            using (
                FileStream imgStream = new FileStream(newThumbnail, FileMode.Open, FileAccess.Read))
            {
                thumbnailPart.FeedData(imgStream);
            }
        }

        static void Main(string[] args)
        {
            var templatePresentation = "Modified.pptx";
            var outputPresentation = "Modified.pptx";
            var baPresentation = File.ReadAllBytes(templatePresentation);
            var pmlMainPresentation = new PmlDocument("Main.pptx", baPresentation);
            OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(pmlMainPresentation);
            PresentationDocument document = streamDoc.GetPresentationDocument();
            var thumbNailPart = document.ThumbnailPart;
            ReplaceThumbnail(thumbNailPart, @"C:\Path\to\image\image.jpg");
            document.SaveAs(outputPresentation);
        }
    }
}

编辑: 我意识到之前有人问过这个问题 (How to generate thumbnail image for a PPTX file in C#?),答案是 "enable preview screenshot when saving the presentation",但这意味着我必须打开每个 pptx 并手动设置此标志。我将不胜感激 C# 解决方案。

提前致谢!

如果缩略图从未存在过,则 ThumbnailPart 不一定存在于文档中,因此代码中的 thumbNailPart 变量将为空。在这种情况下,除了为 ThumbnailPart 设置图像外,您还需要添加部件本身。

通常 在使用 OpenXml SDK 时,您会调用 AddPart 方法传入 new ThumbnailPart 但由于某种原因 ThumbnailPart constructor is protected internal and thus not accessible to you. Instead, there is an AddThumbnailPart method on the PresentationDocument which will create a new ThumbnailPart. The AddThumbnailPart method takes either a string for the content type or a ThumbnailPartType 枚举成员.

将以下内容添加到您的代码应该可以解决您的问题:

if (document.ThumbnailPart == null)
    document.AddThumbnailPart(ThumbnailPartType.Jpeg);

var thumbNailPart = document.ThumbnailPart;