本篇文章将介绍如何使用Spire.Doc for .NET来实现将图片插入到Word批注以及提取Word批注中的图片。
插入图片到Word批注
C#
//创建Document类的对象,加载文档
Document doc = new Document();
doc.LoadFromFile("testfile.docx");
//获取第一个批注
Comment comment = doc.Comments[0];
//实例化DocPicture类,加载图片
DocPicture docPicture = new DocPicture(doc);
Image img = Image.FromFile("img1.png");
docPicture.LoadImage(img);
//插入图片到批注
comment.Body.AddParagraph().ChildObjects.Add(docPicture);
//保存文档
doc.SaveToFile("result.docx", FileFormat.Docx2013);
VB.NET
'创建Document类的对象,加载文档
Dim doc As Document = New Document
doc.LoadFromFile("testfile.docx")
'获取第一个批注
Dim comment As Comment = doc.Comments(0)
'实例化DocPicture类,加载图片
Dim docPicture As DocPicture = New DocPicture(doc)
Dim img As Image = Image.FromFile("img1.png")
docPicture.LoadImage(img)
'插入图片到批注
comment.Body.AddParagraph.ChildObjects.Add(docPicture)
'保存文档
doc.SaveToFile("result.docx", FileFormat.Docx2013)
图片插入效果:
读取Word批注中的图片
C#
//创建实例,加载文档
Document doc = new Document();
doc.LoadFromFile("sample.docx");
int index = 0;
//遍历批注,获取图片
foreach (Comment comment in doc.Comments)
{
foreach (Paragraph p in comment.Body.Paragraphs)
{
foreach (DocumentObject docObject in p.ChildObjects)
{
if (docObject.DocumentObjectType == DocumentObjectType.Picture)
{
DocPicture picture = docObject as DocPicture;
String imageName = String.Format("图片{0}.png", index);
picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png);
index++;
}
}
}
}
VB.NET
'创建实例,加载文档
Dim doc As Document = New Document
doc.LoadFromFile("sample.docx")
Dim index As Integer = 0
'遍历批注,获取图片
For Each comment As Comment In doc.Comments
For Each p As Paragraph In comment.Body.Paragraphs
For Each docObject As DocumentObject In p.ChildObjects
If (docObject.DocumentObjectType = DocumentObjectType.Picture) Then
Dim picture As DocPicture = CType(docObject,DocPicture)
Dim imageName As String = String.Format("图片{0}.png", index)
picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png)
index = (index + 1)
End If
Next
Next
Next
图片读取结果: