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

6

我开始尝试使用 Microsoft Office Open XML SDK 2.0进行实验。

目前,我能够完成某些操作,例如检索每张幻灯片中的所有文本,并获取演示文稿的大小。例如,我通过以下方式完成后者:

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());
}

现在我想获取给定幻灯片中嵌入的图像。有人知道如何做这个或者可以指向一些相关文档吗?

我很好奇 - 为什么要使用“/9525.0”?EMU到点的标准除数是“/12700”。 - Todd Main
2个回答

4

首先,您需要获取要从中获取图像的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));

如何将SlidePart转换为实际图像,以便可以放入imageList中? - petko_stankoski
1
这段代码似乎假定你知道图像的文件名 - 对吗?如果我只想检索PPTX文件中的第一张图片或所有图片怎么办? - Corey Burnett
有没有办法将所有幻灯片转换为图像或SVG? - sridharnetha

-2

从Openxml格式获取图像的最简单方法:

使用任何zip存档库从pptx文件的媒体文件夹中提取图像。这将包含文档中的图像。同样,您可以手动将扩展名.pptx替换为.zip并提取以从媒体文件夹获取图像。

希望这有所帮助。


问题是“如何使用MS Open XML SDK从.pptx文件中检索图像?”,您提供手动解决方案吗? - Hassan Rahman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接