无法使用open xml将图像添加到powerpoint演示文稿

时间:2014-03-06 10:07:38

标签: image powerpoint openxml

我使用以下代码将新幻灯片添加到ppt文件并添加图像。我正在使用Open XML 2.5 SDK。

添加了新幻灯片,但未添加图片。这段代码有什么问题吗?

int position = 1;
using (PresentationDocument presentationDocument = PresentationDocument.Open("c.pptx", true))
{

  PresentationPart presentationPart = presentationDocument.PresentationPart;

  Slide slide = new Slide(new CommonSlideData(new ShapeTree()));

  NonVisualGroupShapeProperties nonVisualProperties = slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties());
  nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = 1, Name = "" };
  nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties();
  nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();

  // Specify the group shape properties of the new slide.
  slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties());

  // Create the slide part for the new slide.
  SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();


  // Save the new slide part.
  slide.Save(slidePart);
  string imgId = "rId" + new Random().Next(2000).ToString();
  ImagePart imagePart = slidePart.AddImagePart(ImagePartType.Png, imgId); 

  using (FileStream stream = new FileStream("a.png", FileMode.Open))
  {
    stream.Position = 0;
    imagePart.FeedData(stream);
  }

  slide.Save(slidePart);

  // Modify the slide ID list in the presentation part.
  // The slide ID list should not be null.
  SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;

  // Find the highest slide ID in the current list.
  uint maxSlideId = 1;
  SlideId prevSlideId = null;

  foreach (SlideId slideId in slideIdList.ChildElements)
  {
    if (slideId.Id > maxSlideId)
    {
      maxSlideId = slideId.Id;
    }

    position--;
    if (position == 0)
    {
      prevSlideId = slideId;
    }

  }

  maxSlideId++;

  // Get the ID of the previous slide.
  SlidePart lastSlidePart;

  if (prevSlideId != null)
  {
    lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId);
  }
  else
  {
    lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
  }


  // Use the same slide layout as that of the previous slide.
  if (null != lastSlidePart.SlideLayoutPart)
  {
    slidePart.AddPart(lastSlidePart.SlideLayoutPart);
  }

  // Insert the new slide into the slide list after the previous slide.
  SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
  newSlideId.Id = maxSlideId;
  newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);

  // Save the modified prsentation.
  presentationPart.Presentation.Save();

提前致谢。

0 个答案:

没有答案