Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DocumentFormat.OpenXml Adding an Image to a word doc

I am creating a simple word doc, using the openXml SDK. It is working so far. Now how can I add an image from my file system to this doc? I don't care where it is in the doc just so it is there. Thanks! Here is what I have so far.

 string fileName = "proposal"+dealerId +Guid.NewGuid().ToString()+".doc";
       string filePath = @"C:\DWSApplicationFiles\Word\" + fileName;
       using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document, true))
       {
           MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();

           mainPart.Document = new Document();
           //create the body
           Body body = new Body();
           DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
           DocumentFormat.OpenXml.Wordprocessing.Run runParagraph = new DocumentFormat.OpenXml.Wordprocessing.Run();         

           DocumentFormat.OpenXml.Wordprocessing.Text text_paragraph = new DocumentFormat.OpenXml.Wordprocessing.Text("This is a test");
           runParagraph.Append(text_paragraph);
           p.Append(runParagraph);
           body.Append(p);
           mainPart.Document.Append(body);
           mainPart.Document.Save();              
       }
like image 414
twaldron Avatar asked Nov 14 '22 23:11

twaldron


1 Answers

Here is a method that can be simpler than the one described in the msdn page posted above, this code is in C++/CLI but of course you can write the equivalent in C#

WordprocessingDocument^ doc = WordprocessingDocument::Open(doc_name, true);
FileStream^ img_fs = gcnew FileStream(image_path, FileMode::Open);
ImagePart^ image_part = doc->MainDocumentPart->AddImagePart(ImagePartType::Jpeg);
image_part->FeedData(img_fs);
Run^ img_run = doc->MainDocumentPart->Document->Body->AppendChild(gcnew Paragraph())->AppendChild(gcnew Run());
Vml::ImageData^ img_data = img_run->AppendChild(gcnew Picture())->AppendChild(gcnew Vml::Shape())->AppendChild(gcnew Vml::ImageData());
img_data->RelationshipId = doc->MainDocumentPart->GetIdOfPart(image_part);
doc->Close();
like image 125
demon36 Avatar answered Dec 10 '22 10:12

demon36