Word控件Spire.Doc 【图像形状】教程(4) 用 C# 中的文本替换 Word 中的图像

本文主要介绍如何在 C#、VB.NET 中从 Word 中提取图像。

让我们看看 Spire.Doc 是如何帮助开发人员解决与 Office 技术编程相关的问题。根据描述,发帖人希望将Word文件中的每张图片对应替换为“Here was image {image index}”。但是,我们想提供一个带有以下示例代码的解决方案。

测试文件

用 C# 中的文本替换 Word 中的图像

用文本替换图像的代码片段;

第 1 步:创建一个新的 Word 文档并加载测试文件。

Document document = new Document(@"....test.docx");

第 2 步:获取Word文档中的所有图片并将它们替换为文本“Here was image {image index}”。

int j = 1;foreach (Section sec in document.Sections){foreach (Paragraph para in sec.Paragraphs){List pictures = new List();foreach (DocumentObject docObj in para.ChildObjects){if (docObj.DocumentObjectType == DocumentObjectType.Picture){pictures.Add(docObj);}}foreach (DocumentObject pic in pictures){int index = para.ChildObjects.IndexOf(pic);TextRange range = new TextRange(document);range.Text = string.Format("Here was image {0}", j);para.ChildObjects.Insert(index, range);para.ChildObjects.Remove(pic);j++;}}}

第 3 步:保存并启动文件。

document.SaveToFile(@"....result.docx", FileFormat.Docx);System.Diagnostics.Process.Start(@"....result.docx");

结果:

用 C# 中的文本替换 Word 中的图像

完整的 C# 代码:

[C#]

using System;using System.Collections.Generic;using System.Linq;using System.Text;using Spire.Doc;using Spire.Doc.Documents;using Spire.Doc.Fields;using Spire.Doc.Interface;using System.Drawing;namespace ReplaceImageWithText{class Program{static void Main(string[] args){Document document = new Document(@"....test.docx");int j = 1;foreach (Section sec in document.Sections){foreach (Paragraph para in sec.Paragraphs){List pictures = new List();foreach (DocumentObject docObj in para.ChildObjects){if (docObj.DocumentObjectType == DocumentObjectType.Picture){pictures.Add(docObj);}}foreach (DocumentObject pic in pictures){int index = para.ChildObjects.IndexOf(pic);TextRange range = new TextRange(document);range.Text = string.Format("Here was image {0}", j);para.ChildObjects.Insert(index, range);para.ChildObjects.Remove(pic);j++;}}}document.SaveToFile(@"....result.docx", FileFormat.Docx);System.Diagnostics.Process.Start(@"....result.docx");}}}

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


欢迎下载|体验更多E-iceblue产品

获取更多信息请咨询在线客服  


标签:

来源:慧都

声明:本站部分文章及图片转载于互联网,内容版权归原作者所有,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2022年9月5日
下一篇 2022年9月5日

相关推荐

发表回复

登录后才能评论