This project has moved and is read-only. For the latest updates, please go here.

Adding image as inline in word document

Jan 23, 2014 at 12:11 PM
Dear All

I need an urgent information. I am trying to add the image in document using this tool. I'm using the same example on documentation by using .NET framwork 3.5.

I am unable to view the image; as there is only text.

Please help me.

Below is the code.

#region Open file and add Data
                            using (WordprocessingDocument doc = WordprocessingDocument.Open(mem, true))
                            {
                                MainDocumentPart mainPart = doc.MainDocumentPart;
                                if (mainPart == null)
                                {
                                    mainPart = doc.AddMainDocumentPart();
                                    new Document(new Body()).Save(mainPart);
                                }

                                HtmlConverter converter = new HtmlConverter(mainPart);


                                Body body = mainPart.Document.Body;


                                StringWriter sw = new StringWriter();

                                HtmlTextWriter hw = new HtmlTextWriter(sw);

                                //DivExport.RenderControl(hw);

                                string strHTML = string.Empty;
                                strHTML = strHTML + string.Format("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0 Transitional//EN'>");
                                strHTML = strHTML + string.Format("<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><title></title></head><body>");

                                //strHTML = strHTML + sw.ToString();
                                strHTML = strHTML + string.Format("Looks how cool is <font size='x-large'><b>Open Xml</b></font>.");
                                strHTML = strHTML + string.Format(@"<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' alt='Red dot' />");
                                strHTML = strHTML + string.Format(@"<img src='data:image/JPG;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjI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feNPk1XU0lZUtw2ehPSly1U+geziVdRtXuPD0cflyH6DmsGO31Kw0zzlRkKvhR3YV0baxrKJk2iM27oPSnQ6rezO6XlomzGYz70o06kI9GvUcopu5z13a6uJbfYJHDjc3HAzVZ7DU4YZ0iil3k5PFdZPqmpi3j2JFHJnnd0xSPq2ox20beWjSk8gdDTUallsDpo45rTVZIxmObAHHy02Kz1FXIeCVgR3Wuul1vWBKPLsk2nsetamk3l5ds4u4kTHTbUVY1FBt2sOMEncpWMUkGhwpKu1t3T8KK0tS+4v+9/SiuBmpPZ/wCqH+6Ks1Ws/wDVD/dFWaa2AKKKKYCUUtFAESxYlZ85yOlZF3oMlxdPKl0UVuwrcorSFSUHeIrI5s+GZvMLJfuM+9H/AAjEoiZVvnDHoc9K6SitfrdXuHKjn5/DstzFGJLxhIgxuXvTJPDUrxqn26Qbe4NdHRSWKqrZhyowotBniZj9tYhl2kGkl8PPLCkbXTYQ5BzW9RS+s1L3uHKjnh4aY2ywS3TuqsSDnmnv4fc26wpclQnQ963qKf1qr3DlRzMnheaRw51CQMPQ1p6XpR05mJnaTcO5rTopTxNSceVvQLIz9S+4v+9/SijUvuL/AL39KK5mMns/9UP90VZqtZ/6of7oqzTWwBRRRTAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAM7U/uL/vf0oo1P7i/wC9/Sipe4Fi0x5Y5/hFWMj1rmtSu7iGWMRyFRsHSqX9o3n/AD3ancDssj1oyPWuN/tG8/57tR/aN5/z3ai4HZZHrRketcb/AGjef892o/tG8/57tRcDssj1oyPWuN/tG8/57tR/aN5/z3ai4HZZHrRketcb/aN5/wA92o/tG8/57tRcDssj1oyPWuN/tG8/57tR/aN5/wA92ouB2WR60ZHrXG/2jef892o/tG8/57tRcDssj1oyPWuN/tG8/wCe7Uf2jef892ouB2WR60ZHrXG/2jef892o/tG8/wCe7UXA6LUuUXB/i/pRWdYzy3Fqxlcv83f6UUgP/9k=' alt='Red dot' ></img>");
                                strHTML = strHTML + string.Format("Now with <font color='red'><u>HtmlToOpenXml</u></font>, it nevers been so easy to convert html.");
                                //strHTML = strHTML + string.Format("<p>If you like it, add me a rating on <a href='http://notesforhtml2openxml.codeplex.com'>codeplex</a>");
                               // strHTML = strHTML + string.Format("</p>");
                                strHTML = strHTML + string.Format("</body></html>");


                                var paragraphs = converter.Parse(strHTML);
                                for (int i = 0; i < paragraphs.Count; i++)
                                {
                                    body.Append(paragraphs[i]);
                                }


                                Debug.Assert(IsDocumentValid(doc), "Invalid File!");
                                mainPart.Document.Save();





                                /*Allow File to Download*/
                                Response.Clear();

                                Response.Buffer = true;



                                Response.AddHeader("content-disposition", "attachment;filename=" + docName);

                                Response.Charset = "";

                               Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                                Response.ContentType = "application/ms-word";
                               byte[] mArray = mem.ToArray();
                                Response.BinaryWrite(mArray);

                                Response.Flush();

                                Response.End();

                            }
                            #endregion
Coordinator
Jan 23, 2014 at 12:56 PM
Hello,


I notice 2 things on your code:
1) the first image contains a break-line in your inline data. Perhaps it's due to Codeplex forum but as-is, it does not work.
2) image/jpg is not a standardized content type. It should be image/jp__e__g.

I just have committed a change to include also image/jpg (it doesn't hurt to be supported...) and fix an optimisation I found while debugging your code.
You can download the latest source code and compile the lib.

Thank you,

Olivier
Jan 23, 2014 at 12:59 PM

Olivier,

On another matter, have you been able to try google viewer with any document produced by the library? As I have noted, even the simplest document fails to be displayed until saved within word.

Chris

ps. êtes-vous français? A+

Jan 23, 2014 at 1:11 PM
Edited Jan 23, 2014 at 1:12 PM
I have check with image/jp_e_g. Its looking still the same.

Do you have any other solution?

BTW thanks both of you for replying fast :-)
Coordinator
Jan 23, 2014 at 1:40 PM
Hi Chris,

Yes I speak French ; I'm Belgian :-)


It's hard to explain why Google Viewer failed to load the docx.
Even when modifying an existing one (not creating from scratch) fails.

Do you dare asking the event log to Google? :-)
Coordinator
Jan 23, 2014 at 1:54 PM
Edited Jan 23, 2014 at 1:54 PM
sorry but it's "image/jpeg"

codeplex "BOLD" button replace the e with e but it's seem to not working...

edit: and now it works.. Damn!
Jan 23, 2014 at 2:01 PM

Excellent. Je suis canadien.

Ce qui est intéressant, c'est si le document est sauvegarde par Word après, tout fonctionne à merveille.

Auriez-vous essaye le 'validateur' d'openXml sur les fichiers crées par la librairie? Il me semble que le probleme est la.

De plus, crocodocs, un produit semblable à Google (mais qui n'est pas gratuit!), parvient à présenter les documents. Sans doute la validation y est différente .

Chris

Coordinator
Jan 23, 2014 at 3:43 PM
Oui j'ai ajouté l'étape de validation dans mon process de testing.
Tout n'est pas 100% parfait sur tout mais j'y travaille...

J'ai pris la validation Office 2010. Peut-être Google utilise la version 2013 ?
De version en version, cela devient plus restrictif.

J'ai ajouté ce bloc de code-ci:
static void AssertThatOpenXmlDocumentIsValid(WordprocessingDocument wpDoc)
{
       var validator = new OpenXmlValidator(FileFormatVersions.Office2010);
       var errors = validator.Validate(wpDoc);

       if (!errors.GetEnumerator().MoveNext())
              return;

       Console.ForegroundColor = ConsoleColor.Red;
       Console.WriteLine("The document doesn't look 100% compatible with Office 2010.\n");

       Console.ForegroundColor = ConsoleColor.Gray;
       foreach (ValidationErrorInfo error in errors)
       {
              Console.Write("{0}\n\t{1}", error.Path.XPath, error.Description);
              Console.WriteLine();
       }

       Console.ReadLine();
}