本文内容分享通过C#程序代码来获取Word中指定图片的坐标位置的方法。附VB.NET代码,供参考。
程序运行环境:
-
.NET Framework 4.8
-
Free Spire.Doc for .NET 7.11
-
Word测试文档:.docx 2013
方法步骤:
1. 指定文件路径,本次测试代码路径为项目文件夹路径。即在Visual Studio项目文件下存入用于测试的Word文档,如:C:UsersAdministratorDocumentsVisual Studio 2013ProjectsImage_DocGetCoordinatesOfImgbinDebugtest.docx。文件路径也可自定义为其他路径。
2. 在“解决方案资源管理器”中引入必要程序集文件,如下图:
程序代码:
C#
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System;
namespace GetCoordinatesOfImg { class Program { static void Main(string[] args) { //加载Word测试文档 Document doc = new Document(); doc.LoadFromFile("test.docx");
//遍历section for (int a = doc.Sections.Count - 1; a >= 0; a--) { Section section = doc.Sections[a];
//遍历paragraph段落 for (int j = section.Paragraphs.Count - 1; j >= 0; j--) { Paragraph paragraph = section.Paragraphs[j];
//遍历段落中的对象 for (int i = 0; i < paragraph.ChildObjects.Count; i++) { DocumentObject docobj = paragraph.ChildObjects[i];
//判断对象是否为图片 if (docobj.DocumentObjectType == DocumentObjectType.Picture) { DocPicture picture = docobj as DocPicture;
if (picture.Title.Equals("图片4"))//定位标题为“图片4”的图片 { //获取图片坐标位置 float x = picture.HorizontalPosition; float y = picture.VerticalPosition; Console.WriteLine("坐标位置为:n X=" + x + "n Y=" + y); Console.ReadLine(); } } } } } } } } |
vb.net
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | Imports Spire.Doc Imports Spire.Doc.Documents Imports Spire.Doc.Fields
Namespace GetCoordinatesOfImg Class Program Private Shared Sub Main(args As String()) '加载Word测试文档 Dim doc As New Document() doc.LoadFromFile("test.docx")
'遍历section For a As Integer = doc.Sections.Count - 1 To 0 Step -1 Dim section As Section = doc.Sections(a)
'遍历paragraph段落 For j As Integer = section.Paragraphs.Count - 1 To 0 Step -1 Dim paragraph As Paragraph = section.Paragraphs(j)
'遍历段落中的对象 For i As Integer = 0 To paragraph.ChildObjects.Count - 1 Dim docobj As DocumentObject = paragraph.ChildObjects(i)
'判断对象是否为图片 If docobj.DocumentObjectType = DocumentObjectType.Picture Then Dim picture As DocPicture = TryCast(docobj, DocPicture)
If picture.Title.Equals("图片4") Then '定位标题为“图片4”的图片 '获取图片坐标位置 Dim x As Single = picture.HorizontalPosition Dim y As Single = picture.VerticalPosition Console.WriteLine("坐标位置为:" & vbLf & " X=" + x + vbLf & " Y=" + y) Console.ReadLine() End If End If Next Next Next End Sub End Class End Namespace |
图片坐标位置读取结果:
测试的Word中的图片
图片坐标获取结果:



