c# - 如何使用 MS Open XML SDK 从 .pptx 文件中检索图像?

标签 c# .net powerpoint openxml openxml-sdk

我开始试验 Open XML SDK 2.0 for Microsoft Office .

我目前能够执行某些操作,例如检索每张幻灯片中的所有文本,以及获取演示文稿的大小。例如,我这样做后者:

using (var doc = PresentationDocument.Open(pptx_filename, false)) {
     var presentation = doc.PresentationPart.Presentation;

     Debug.Print("width: " + (presentation.SlideSize.Cx / 9525.0).ToString());
     Debug.Print("height: " + (presentation.SlideSize.Cy / 9525.0).ToString());
}

现在我想检索给定幻灯片中的嵌入图像。有谁知道如何执行此操作或可以向我指出有关该主题的一些文档?

最佳答案

首先,您需要获取要从中获取图像的 SlidePart:

public static SlidePart GetSlidePart(PresentationDocument presentationDocument, int slideIndex)
{
    if (presentationDocument == null)
    {
        throw new ArgumentNullException("presentationDocument", "GetSlidePart Method: parameter presentationDocument is null");
    }

    // Get the number of slides in the presentation
    int slidesCount = CountSlides(presentationDocument);

    if (slideIndex < 0 || slideIndex >= slidesCount)
    {
        throw new ArgumentOutOfRangeException("slideIndex", "GetSlidePart Method: parameter slideIndex is out of range");
    }

    PresentationPart presentationPart = presentationDocument.PresentationPart;

    // Verify that the presentation part and presentation exist.
    if (presentationPart != null && presentationPart.Presentation != null)
    {
        Presentation presentation = presentationPart.Presentation;

        if (presentation.SlideIdList != null)
        {
            // Get the collection of slide IDs from the slide ID list.
            var slideIds = presentation.SlideIdList.ChildElements;

            if (slideIndex < slideIds.Count)
            {
               // Get the relationship ID of the slide.
               string slidePartRelationshipId = (slideIds[slideIndex] as SlideId).RelationshipId;

                // Get the specified slide part from the relationship ID.
                SlidePart slidePart = (SlidePart)presentationPart.GetPartById(slidePartRelationshipId);

                 return slidePart;
             }
         }
     }

     // No slide found
     return null;
}

然后您需要根据图像的文件名搜索包含您要查找的图像的Picture 对象:

Picture imageToRemove = slidePart.Slide.Descendants<Picture>().SingleOrDefault(picture => picture.NonVisualPictureProperties.OuterXml.Contains(imageFileName));

关于c# - 如何使用 MS Open XML SDK 从 .pptx 文件中检索图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7070074/

相关文章:

c# - 在循环数据时创建列表列?

c# - .NET 4函数: Function argument question

c# - 没有 System.Web 的 HTML 解码

vba - 如何向 PowerPoint 2010 添加调用宏的选项卡

vba - 引用 powerpoint 演示文稿和幻灯片时出现错误 451

c# - 转换字符串得到错误的值

c# - 在 C# 中从 Bing Map API 解析 JSON 代码

c# - 如何生成退回电子邮件通知,其中包含一些额外信息

c# - Roslyn 创建自定义表达式

vba - 使用 VBA 更改 Powerpoint 2013 中幻灯片元素的颜色