0
我想用位于我的Word文档的标题中的图片内容控件填充此代码:(我已经通过内容控件标记和图像流通过文件参数,此功能)使用OpenXML将图片内容控件填充到word文档的标题中
它发现Word文档中的内容控制,但在这一行:
ImagePart ip = (ImagePart)idpp.OpenXmlPart;
我得到这个错误:
你能指导我吗?
我想用位于我的Word文档的标题中的图片内容控件填充此代码:(我已经通过内容控件标记和图像流通过文件参数,此功能)使用OpenXML将图片内容控件填充到word文档的标题中
它发现Word文档中的内容控制,但在这一行:
ImagePart ip = (ImagePart)idpp.OpenXmlPart;
我得到这个错误:
你能指导我吗?
我试图找到一种方法,这里是答案:
public void FillDocument(Stream stream, XDocument document)
{
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Open(stream, true))
{
List<SdtElement> descendants = wordDocument.MainDocumentPart.Document.Descendants<SdtElement>().ToList();
foreach (HeaderPart headerPart in wordDocument.MainDocumentPart.HeaderParts)
{
descendants.AddRange(headerPart.Header.Descendants<SdtElement>().ToList());
}
foreach (var footerPart in wordDocument.MainDocumentPart.FooterParts)
{
descendants.AddRange(footerPart.Footer.Descendants<SdtElement>().ToList());
}
XDocument doc = document;
foreach (SdtElement item in descendants)
{
SdtAlias alias = item.Descendants<SdtAlias>().FirstOrDefault();
if (alias != null)
{
string sdtTitle = alias.Val.Value;
//if Sdt Content Control is Picture
string imageContent = (from xElement in doc.Descendants("Picture") where xElement.Attribute("Id").Value == sdtTitle select xElement.Value).FirstOrDefault();
if (imageContent != null)
{
MemoryStream result = (MemoryStream)StringToStream(imageContent);
D.Blip blipElement = item.Descendants<D.Blip>().FirstOrDefault();
string imageId = "default value";
if (blipElement != null)
{
imageId = blipElement.Embed.Value;
ImagePartType imagePartType = ImagePartType.Png;
//Add image and change embeded id.
ImagePart imagePart = null;
Type p = item.Parent.GetType();
switch (p.Name)
{
case "Header":
HeaderPart headerPart = ((Header)(item.Parent)).HeaderPart;
imagePart = headerPart.AddImagePart(imagePartType);
imagePart.FeedData(result);
blipElement.Embed = headerPart.GetIdOfPart(imagePart);
break;
case "Body":
MainDocumentPart mainDocumentPart = wordDocument.MainDocumentPart;
imagePart = mainDocumentPart.AddImagePart(imagePartType);
imagePart.FeedData(result);
blipElement.Embed = mainDocumentPart.GetIdOfPart(imagePart);
break;
case "Footer":
FooterPart footerPart = ((Footer)(item.Parent)).FooterPart;
imagePart = footerPart.AddImagePart(imagePartType);
imagePart.FeedData(result);
blipElement.Embed = footerPart.GetIdOfPart(imagePart);
break;
default:
break;
}
}
continue;
}
}
}
}}
它工作正常,并且可以在页眉或页脚或身体占满画面内容的控制!