如何使用 C# 代码在 Word 文档中添加图像

本教程将逐步指导您如何使用 C# 在 Word 文档中添加图像。我们将使用 C# 中的命令行应用程序将图像添加到 Word 文档。

使用 C# 在 Word 文档中添加图像的步骤

  1. 在解决方案中添加对 System.Drawing 程序集的引用
  2. 接下来,需要添加 Aspose.Words for .NET NuGet 包引用
  3. 为 Aspose.Words 和 Aspose.Words.Drawing 命名空间添加 using 指令
  4. 调用 License.SetLicense 方法
  5. 创建 Document 对象以从文件系统或内存流加载 Word DOC
  6. 创建 DocumentBuilder 类对象来编写文本、图像、表格等。
  7. 将光标移动到页眉或页脚或 Word DOC 中的任何所需位置
  8. 使用 DocumentBuilder.InsertImage 从流或文件中添加图像
  9. 使用 Shape class 进一步设置图像的大小、位置、填充等
  10. 调用 Document.Save 方法将 Word DOC 保存到磁盘或流

您可以在 .NET 应用程序中使用以下代码示例使用 C# 将图像添加到 Word 文档。

使用 C# 在 Word 文档中添加图像的代码

using Aspose.Words;
using Aspose.Words.Drawing;
namespace HowtoAddImageinWordDocumentUsingCsharp
{
class AddImageToWordDOC
{
static void Main(string[] args)
{
// Set license prior to adding image in Word document using C#
License setupPriorAddingImages = new License();
setupPriorAddingImages.SetLicense("path to license.lic");
// Load Word DOC document that you want to add images to
Document AddImagesToWordDOC = new Document("input.doc");
// Instantiate DocumentBuilder class object to write text, images, tables etc.
DocumentBuilder imageWriter = new DocumentBuilder(AddImagesToWordDOC);
// Move cursor to Primary Header in Word DOC
imageWriter.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
// Insert image in word document header c#
Shape headerImage = imageWriter.InsertImage("C:\\Add Image in Word Header.jpg");
// Set Image Size in Header
headerImage.Width = 1 * 72; // equals to one inch
headerImage.Height = 1 * 72;
// Now, move cursor to last Paragraph in Word Document
imageWriter.MoveTo(AddImagesToWordDOC.LastSection.Body.LastParagraph);
// Add Image to Word Document and Link to File
Shape imageAsLinkToFile = imageWriter.InsertImage("C:\\Add Image as Link to File.jpg");
imageAsLinkToFile.ImageData.SourceFullName = "C:\\Add Image as Link to File.jpg";
// Save As DOCX
AddImagesToWordDOC.Save("C:\\Word with Embeded and Linked Images.docx");
}
}
}

因此,上面的 Visual Studio 应用程序将允许您将图像添加到 Word 文档 C#。它加载现有的 DOC 文件,但您甚至可以通过编程方式 在 C# 中创建 Word 文档。该代码提供了两种将图像添加到 Word DOC C# 的方法 - 它首先在 Word 文档标题 C# 中插入图像,然后将图像作为链接图像添加到单词,即在这种情况下,图像不是嵌入的,而是作为文件链接插入的。

 简体中文