Edit: This question's text has been changed to reflect utilizing open xml code and interop.
I'm trying to insert a base 64 encoded image to a Word document via a ribbon. The following code is for reproduction purposes:
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;
}
}
}
However whenever I execute this code I hit the catch and the error is:
"XML markup cannot be inserted in the specified location.".
I know this error is misleading because if I change the xml to <Test>Test</Text>
I see "Test"
in my document. Can anyone shed some light on this?
Note that the image used is just a red square about 10px x 10px