图片是Word文档的基本要素之一,常见的对Word图片的操作有插入、删除、替换和提取。本文将介绍如何使通过编程的方式添加图片到指定位置,以及如何获取Word文档中的图片并保存到本地路径。
在指定位置插入图片
C#
//实例化一个Document对象
Document doc = new Document();
//添加section和段落
Section section = doc.AddSection();
Paragraph para = section.AddParagraph();
//加载图片到System.Drawing.Image对象, 使用AppendPicture方法将图片插入到段落
Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
DocPicture picture = doc.Sections[0].Paragraphs[0].AppendPicture(image);
//设置文字环绕方式
picture.TextWrappingStyle = TextWrappingStyle.Square;
//指定图片位置
picture.HorizontalPosition = 50.0f;
picture.VerticalPosition = 50.0f;
//设置图片大小
picture.Width = 100;
picture.Height = 100;
//保存到文档
doc.SaveToFile("Image.doc", FileFormat.Doc);
VB.NET
'实例化一个Document对象 Dim doc As Document = New Document '添加section和段落
Dim section As Section = doc.AddSection
Dim para As Paragraph = section.AddParagraph
'加载图片到System.Drawing.Image对象,使用AppendPicture方法将图片插入到段落 Dim image As Image = Image.FromFile("C:\Users\Administrator\Desktop\logo.png") Dim picture As DocPicture = doc.Sections(0).Paragraphs(0).AppendPicture(image) '设置文字环绕方式
picture.TextWrappingStyle = TextWrappingStyle.Square
'指定图片位置 picture.HorizontalPosition = 50! picture.VerticalPosition = 50! '设置图片大小
picture.Width = 100
picture.Height = 100
'保存到文档 doc.SaveToFile("Image.doc",FileFormat.Doc)
提取Word文档中的图片
C#
//初始化一个Document实例并加载Word文档 Document doc = new Document();doc.LoadFromFile(@"sample.doc");int index = 0;//遍历Word文档中每一个section foreach (Section section in doc.Sections){//遍历section中的每个段落 foreach (Paragraph paragraph in section.Paragraphs){//遍历段落中的每个DocumentObject foreach (DocumentObject docObject in paragraph.ChildObjects){//判断DocumentObject是否为图片 if (docObject.DocumentObjectType == DocumentObjectType.Picture){//保存图片到指定路径并设置图片格式 DocPicture picture = docObject as DocPicture;String imageName = String.Format(@"images\Image-{0}.png",index);picture.Image.Save(imageName,System.Drawing.Imaging.ImageFormat.Png);index++;}}}}
VB.NET
'初始化一个Document实例并加载Word文档
Dim doc As Document = New Document
doc.LoadFromFile("sample.doc")
Dim index As Integer = 0
'遍历Word文档中每一个section For Each section As Section In doc.Sections '遍历section中的每个段落
For Each paragraph As Paragraph In section.Paragraphs
'遍历段落中的每个DocumentObject For Each docObject As DocumentObject In paragraph.ChildObjects '判断DocumentObject是否为图片
If (docObject.DocumentObjectType = DocumentObjectType.Picture) Then
'保存图片到指定路径并设置图片格式 Dim picture As DocPicture = CType(docObject,DocPicture) Dim imageName As String = String.Format("images\Image-{0}.png",index) picture.Image.Save(imageName,System.Drawing.Imaging.ImageFormat.Png) index = (index + 1) End If Next Next Next