Word控件Spire.Doc 【图像形状】教程(7): 如何使用 C# 在 Word 中替换图像
创始人
2024-03-01 21:44:21

Spire.Doc for .NET是一款专门对 Word 文档进行操作的 .NET 类库。在于帮助开发人员无需安装 Microsoft Word情况下,轻松快捷高效地创建、编辑、转换和打印 Microsoft Word 文档。拥有近10年专业开发经验Spire系列办公文档开发工具,专注于创建、编辑、转换和打印Word/PDF/Excel等格式文件处理,小巧便捷。在 C#、VB.NET 中从 Word 中提取图像。

Spire.Doc for.NET 最新下载(qun:767755948)icon-default.png?t=M85Bhttps://www.evget.com/product/3368/download

在 Spire.Doc 中可以用 Word 文档中的文本或图像替换图像,在本教程中,我们将向您展示如何使用 Spire.Doc 和 C# 将指定的图像替换为另一个图像。

下面是替换图片之前的原始Word文档:

代码片段:

第 1 步:加载 Word 文档。

Document document = new Document("Input.docx");

第 2 步:用新图像替换标题为“图1”的图像。

//Loop through the paragraphs of the section
foreach (Paragraph paragraph in document.Sections[0].Paragraphs)
{
//Loop through the child elements of paragraph
foreach (DocumentObject docObj in paragraph.ChildObjects)
{
if (docObj.DocumentObjectType == DocumentObjectType.Picture)
{
DocPicture picture = docObj as DocPicture;
if (picture.Title == "Figure 1")
{
//Replace the image
picture.LoadImage(Image.FromFile("PinkRoses.jpg"));
}
}
}
}

第 3 步:保存并关闭文档。

document.SaveToFile("ReplaceImage.docx");
document.Close();

生成的文档如下所示:

完整代码

using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;namespace Replace_Image
{
class Program
{
static void Main(string[] args)
{
//Load the Word document
Document document = new Document("Input.docx");//Loop through the paragraphs of the section
foreach (Paragraph paragraph in document.Sections[0].Paragraphs)
{
//Loop through the child elements of paragraph
foreach (DocumentObject docObj in paragraph.ChildObjects)
{
if (docObj.DocumentObjectType == DocumentObjectType.Picture)
{
DocPicture picture = docObj as DocPicture;
if (picture.Title == "Figure 1")
{
//Replace the image
picture.LoadImage(Image.FromFile("PinkRoses.jpg"));
}
}
}
}//Save and close the document
document.SaveToFile("ReplaceImage.docx");
document.Close();
}
}
}

以上便是如何使用 C# 在 Word 中替换图像,如果您有其他问题也可以继续浏览本系列文章,获取相关教程,你还可以给我留言或者加入我们的官方技术交流群。

相关内容

热门资讯

金融监管总局发布金融机构产品适... 为进一步规范金融机构适当性管理,加强金融消费者权益保护,金融监管总局11日对外发布《金融机构产品适当...
秋天的水库小学作文(最新3篇... 秋天的水库小学作文 篇一秋天的水库小学秋天是一个美丽的季节,水库小学更是一个美丽的地方。我喜欢在这个...
家务劳动小学作文【通用6篇】 篇一:家务劳动小学作文家务劳动是每个家庭中必不可少的一部分,它不仅可以帮助家人分担家务负担,还能培养...
春天小学一年级作文300字(... 春天小学一年级作文300字 篇一春天的小动物春天是一个充满生机和活力的季节。在春天里,大自然开始苏醒...
父爱是爱的港湾小学作文【推荐... 父爱是爱的港湾小学作文 篇一父爱是爱的港湾父爱是一种伟大而无私的情感,是给予我们温暖和力量的港湾。在...