文档星空最火知名网站>>Spire.Doc系列教程>>Spire.Doc系列教程(6):插入图片到 Word 以及提取 Word 中的图片
Spire.Doc系列教程(6):插入图片到 Word 以及提取 Word 中的图片
图片是Word文档的基本要素之一,常见的对Word图片的操作有插入、删除、替换和提取。本文将介绍如何使通过编程的方式添加图片到指定位置,以及如何获取Word文档中的图片并保存到本地路径。
在指定位置插入图片
//实例化一个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);

提取Word文档中的图片
//初始化一个Document实例并加载Word文档
Document doc = new Document();
doc.LoadFromFile(@"Image.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++;
}
}
}
}


QQ交谈
在线咨询

渝公网安备
50010702500608号

客服热线