编辑:为了利用开放的xml代码和互操作性,更改了此问题的文本。
我正在尝试通过功能区将base64编码的图像插入Word文档。以下代码仅供复制:
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void InsertPicture_Click(object sender, RibbonControlEventArgs e)
{
Word.Application wordApp = null;
Word.Document currentDocument = null;
Word.ContentControls controls = null;
try
{
wordApp = (Word.Application) Marshal.GetActiveObject("Word.Application");
currentDocument = wordApp.ActiveDocument;
controls = currentDocument.ContentControls;
currentDocument.Range().InsertXML(@"<pkg:package xmlns:pkg=""http://schemas.microsoft.com/office/2006/xmlPackage"">
<pkg:part pkg:name=""/word/media/image1.png"" pkg:contentType=""image/png"" pkg:compression=""store"">
<pkg:binaryData>iVBORw0KGgoAAAANSUhEUgAAABEAAAAKCAIA
AADdHiL1AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAVSURBVChTY3gro0IqGtUz3PTIqAAAlO/H4+qBWxcAAAAASUVORK5CYII=</pkg:binaryData>
</pkg:part></pkg:package>");
object tr = true;
object fa = false;
}
catch(Exception ex)
{
wordApp.ActiveDocument.Range().InsertAfter(ex.Message);
}
finally
{
if (controls != null) Marshal.ReleaseComObject(controls); controls = null;
if (currentDocument != null) Marshal.ReleaseComObject(currentDocument); currentDocument = null;
if (wordApp != null) Marshal.ReleaseComObject(wordApp); wordApp = null;
}
}
}
然而每当我执行这段代码时,它都会触发异常并显示错误信息:
"无法在指定位置插入XML标记。"
我知道这个错误信息有误导性,因为如果我将xml更改为
<Test>Test</Text>
,我会在文档中看到"Test"
。 有人能解释一下吗?请注意,所使用的图像只是一个大约为10px x 10px的红色正方形。