我希望克隆PowerPoint文档的一张幻灯片,并使用OpenXML插入到同一文档中。为此,我使用以下功能:
public static void AddNewSlide(PresentationPart parent, Slide _slideTemplate, string newId)
{
var newSlidePart = parent.AddNewPart<SlidePart>(newId);
newSlidePart.FeedData(_slideTemplate.SlidePart.GetStream(FileMode.Open));
newSlidePart.AddPart(_slideTemplate.SlidePart.SlideLayoutPart, _slideTemplate.SlidePart.GetIdOfPart(_slideTemplate.SlidePart.SlideLayoutPart));
newSlidePart.Slide.Save();
DocumentFormat.OpenXml.Presentation.SlideIdList slideIdList = parent.Presentation.SlideIdList;
uint maxSlideId = 1;
foreach (DocumentFormat.OpenXml.Presentation.SlideId slideId in slideIdList.ChildElements)
{
if (slideId.Id > maxSlideId) maxSlideId = slideId.Id;
}
DocumentFormat.OpenXml.Presentation.SlideId newSlideId = new DocumentFormat.OpenXml.Presentation.SlideId { Id = ++maxSlideId, RelationshipId = parent.GetIdOfPart(newSlidePart) };
slideIdList.Append(newSlideId);
}
如果orig幻灯片只包含文本,它可以正常工作,但当orig幻灯片也包含图像时,结果PowerPoint文档将损坏。新幻灯片上的图像不会显示,只显示一条消息:&#34;此图像当前无法显示。&#34;
请帮助克隆带有图像的幻灯片。 提前谢谢。
答案 0 :(得分:3)
此代码生成损坏的幻灯片,因为它只复制数据和布局,而不是幻灯片中的图像。
newSlidePart.FeedData(_slideTemplate.SlidePart.GetStream(FileMode.Open));
newSlidePart.AddPart(_slideTemplate.SlidePart.SlideLayoutPart, _slideTemplate.SlidePart.GetIdOfPart(_slideTemplate.SlidePart.SlideLayoutPart));
例如:上面两行会说新幻灯片是指图片,但新幻灯片中缺少该图片本身。因此,要解决此问题,您还需要编写将旧幻灯片中的图像复制到新幻灯片的代码。
//add all the image part from the source slide to the new one
List<ImagePart> imageParts = new List<ImagePart>();
sourceSlidePart.GetPartsOfType<ImagePart>(imageParts);
foreach (ImagePart img in imageParts)
{
var relID = sourceSlidePart.GetIdOfPart(img); // get relationship ID
ImagePart newImagePart = newSlidePart.AddImagePart(img.ContentType, relID);
newImagePart.FeedData(img.GetStream(FileMode.Open));
}