下载并安装Spire.Doc for .NET, 并将Spire.Doc.dll文件引用到项目中。
插入图片
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
using Spire.Doc.Fields;
namespace Insert_Image_in_Word
{
class Program
{
static void Main(string[] args)
{
//实例化一个Document对象
Document doc = new Document();
doc.LoadFromFile("爱莲说.docx");
//添加section和段落
Section section = doc.AddSection();
Paragraph para = section.AddParagraph();
//加载图片到System.Drawing.Image对象, 使用AppendPicture方法将图片插入到段落
Image image = Image.FromFile("莲花.jpg");
DocPicture picture = doc.Sections[0].Paragraphs[0].AppendPicture(image);
//设置文字环绕方式
picture.TextWrappingStyle = TextWrappingStyle.Square; //指定图片位置
picture.HorizontalPosition = 10f;
picture.VerticalPosition = 10f;
//设置图片大小
picture.Width = 200;
picture.Height = 200;
//保存到文档
doc.SaveToFile("Image.doc", FileFormat.Doc);
}
}
}
提取Word文档中的图片
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace Extract_Image_in_Word
{
class Program
{
static void Main(string[] args)
{
//初始化一个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("Image-{0}.jpg", index);
picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png);
index++;
}
}
}
}
}
}
}