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;
}
}
}
}}
它工作正常,並且可以在頁眉或頁腳或身體佔滿畫面內容的控制!