图片是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