如何使用C#将代码添加到代码生成的MSWord

时间:2015-11-13 02:50:33

标签: c# image ms-word

我使用此代码生成一个word存档,这很好用:

public void AddParagraph(string text, string styleName = null)
{
  Paragraph paragraph = _document.Content.Paragraphs.Add();
  if (styleName != null)
  {
    paragraph.Range.set_Style(_document.Styles[styleName]);
  }
  paragraph.Range.Text = text;
  paragraph.Range.InsertParagraphAfter();
}

但我还需要在生成的段落旁边添加一个图像,该图像是文档路径中的文件,我该怎么想?

1 个答案:

答案 0 :(得分:1)

我知道你正在使用标准词库。这将限制您在未安装MS Office的计算机上运行的能力。我强烈建议您使用NovaCode DocX

它易于使用且非常可靠。您可以使用DocX.AddImage()来实现此目的。

// Create a .docx file
using (DocX document = DocX.Create(@"Example.docx"))
{
  // Add an Image to the docx file
   Novacode.Image img = document.AddImage(@"Donkey.jpg");

   // Insert an emptyParagraph into this document.
   Paragraph p = document.InsertParagraph("", false);

  #region pic1
  Picture pic1 = p.InsertPicture(img.Id, "Donkey", "Taken on Omey island");

   // Set the Picture pic1’s shape
   pic1.SetPictureShape(BasicShapes.cube);

   // Rotate the Picture pic1 clockwise by 30 degrees
   pic1.Rotation = 30;
    #endregion

   #region pic2
   // Create a Picture. A Picture is a customized view of an Image
   Picture pic2 = p.InsertPicture(img.Id, "Donkey", "Taken on Omey island");

   // Set the Picture pic2’s shape
   pic2.SetPictureShape(CalloutShapes.cloudCallout);

  // Flip the Picture pic2 horizontally
   pic2.FlipHorizontal = true;
   #endregion

   // Save the docx file
   document.Save();
}// Release this document from memory.

Source