如何从使用MS打开XML SDK一个.PPTX文件检索图像?图像、文件、XML、MS

2023-09-05 22:59:27 作者:在牛A和牛C之间徘徊

我开始与的Open XML SDK 2.0的Microsoft Office 尝试。

我目前能够做某些事情,如检索每张幻灯片的所有文本,并获得了presentation的大小。比如,我做的后者是这样的:

I'm currently able to do certain things such as retrieve all texts in each slide, and get the size of the presentation. For example, I do the latter this way:

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

现在,我想在一个给定的滑动检索嵌入图像。有谁知道如何做到这一点,也可以点我一些文件关于这个问题的?

Now I'd like to retrieve embedded images in a given slide. Does anyone know how to do this or can point me to some docs on the subject?

推荐答案

首先,你需要抓住 SlidePart 要在其中从获得的图像:

First you need to grab the SlidePart in which you want to get the images from:

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

然后,你需要搜索图片的对象将包含你正在寻找基于图像的文件名的图像:

Then you need to search for the Picture object which will contain the image you are looking for based on the file name of the image:

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