html embededimges into open xml word RRS feed

  • Question

  • Hi,

    I have stuck with embeded images in html which I am attaching into document.

    Here is html:


    <html><head/><body><h1>Html Heading</h1><p>This is an html document in a string literal.</p><img alt="Embedded Image" 
    src="data:image/png;base64,R0lGODlhCgAKAJEAAAAAAP///81Wv81WvyH5BAEAAAMALAAAAAAKAAoAAAIUjIViq+x7QpunwXoZ lXFu/mjIUgAAOw==" 


     I have tried to solve it as bellow:


    	class Program {
    		static void Main(string[] args) {
    			XNamespace w = "";
    			XNamespace r = "";
    			using (WordprocessingDocument myDoc = WordprocessingDocument.Open(@"Test3.docx", true)) {
    				string html = "<html><head/><body><h1>Html Heading</h1><p>This is an html document in a string literal.</p><img alt=\"Embedded Image\" src=\"data:image/png;base64,R0lGODlhCgAKAJEAAAAAAP///81Wv81WvyH5BAEAAAMALAAAAAAKAAoAAAIUjIViq+x7QpunwXoZ lXFu/mjIUgAAOw==\" /></body></html>";
    				string altChunkId = "AltChunkId" + Guid.NewGuid().ToString().Replace("-","") ;
    				MainDocumentPart mainPart = myDoc.MainDocumentPart;
    				AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
    					"application/xhtml+xml", altChunkId);
    				using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
    				using (StreamWriter stringStream = new StreamWriter(chunkStream))
    				XElement altChunk = new XElement(w + "altChunk", new XAttribute(r + "id", altChunkId));
    				XDocument mainDocumentXDoc = GetXDocument(myDoc);
    					.Element(w + "body")
    					.Elements(w + "p")
    				SaveXDocument(myDoc, mainDocumentXDoc);
    		private static void SaveXDocument(WordprocessingDocument myDoc, XDocument mainDocumentXDoc) {
    			// Serialize the XDocument back into the part
    			using (Stream str = myDoc.MainDocumentPart.GetStream(FileMode.Create, FileAccess.Write)) {
    				using (XmlWriter xw = XmlWriter.Create(str)) {
    		private static XDocument GetXDocument(WordprocessingDocument myDoc) {
    			// Load the main document part into an XDocument
    			XDocument mainDocumentXDoc;
    			using (Stream str = myDoc.MainDocumentPart.GetStream()) {
    				using (XmlReader xr = XmlReader.Create(str)) {
    					mainDocumentXDoc = XDocument.Load(xr);
    			return mainDocumentXDoc;


    using info I have found here.

    If someone know how to solve this issue I will be grateful.


    Thanks in advance.



    Friday, September 9, 2011 8:54 AM