C#:从 .docx 中删除图片内容控件
C# : Remove a Picture Content Control fro .docx
我使用下面的代码找到一个图片内容控件,使用这个控件的标记名,然后我使用 Remove 函数在 Word 文档中将其删除:
System.IO.File.Copy(templatePath, outputPath, true);
using (WordprocessingDocument doc = WordprocessingDocument.Open(outputPath, true))
{
tagName = "portrait";
controlBlock = doc.MainDocumentPart.Document.Body.Descendants<SdtElement>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == tagName).SingleOrDefault();
if (controlBlock != null)
{
controlBlock.Remove();
}
doc.Close();
}
但是当我用Word打开创建的文件时,文档需要用Word修复,否则打不开。 Word 还会在错误的详细信息中给我这条消息:
<p> elements are required before every </tc>
修复前后用OpenXml查看word文档,没发现有什么区别
那么删除 Word 文档中的图片内容控件的最佳方法是什么?
我很轻松地解决了我的问题,事实上Word提供的错误信息很清楚。所以我得到了我的优化校准内容的父元素并添加了一个新的空段落,在我尝试删除优化校准内容之后这足以解决我的问题。
这是代码:
controlBlock.Parent.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
controlBlock.Remove();
我使用下面的代码找到一个图片内容控件,使用这个控件的标记名,然后我使用 Remove 函数在 Word 文档中将其删除:
System.IO.File.Copy(templatePath, outputPath, true);
using (WordprocessingDocument doc = WordprocessingDocument.Open(outputPath, true))
{
tagName = "portrait";
controlBlock = doc.MainDocumentPart.Document.Body.Descendants<SdtElement>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == tagName).SingleOrDefault();
if (controlBlock != null)
{
controlBlock.Remove();
}
doc.Close();
}
但是当我用Word打开创建的文件时,文档需要用Word修复,否则打不开。 Word 还会在错误的详细信息中给我这条消息:
<p> elements are required before every </tc>
修复前后用OpenXml查看word文档,没发现有什么区别
那么删除 Word 文档中的图片内容控件的最佳方法是什么?
我很轻松地解决了我的问题,事实上Word提供的错误信息很清楚。所以我得到了我的优化校准内容的父元素并添加了一个新的空段落,在我尝试删除优化校准内容之后这足以解决我的问题。
这是代码:
controlBlock.Parent.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
controlBlock.Remove();