none
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==" 
    
    /></body></html>
    

     

     I have tried to solve it as bellow:

     

    	class Program {
    		static void Main(string[] args) {
    
    			XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
    			XNamespace r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
    
    			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))
    					stringStream.Write(html);
    				XElement altChunk = new XElement(w + "altChunk", new XAttribute(r + "id", altChunkId));
    				XDocument mainDocumentXDoc = GetXDocument(myDoc);
    				mainDocumentXDoc.Root
    					.Element(w + "body")
    					.Elements(w + "p")
    					.Last()
    					.AddAfterSelf(altChunk);
    				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)) {
    					mainDocumentXDoc.Save(xw);
    				}
    			}
    		}
    
    		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.

    Regards,

    Leszek

    Friday, September 9, 2011 8:54 AM