亲宝软件园·资讯

展开

C# 获取Word中的指定图片坐标位置(附VB.NET)

TO BE 人气:0

以下内容通过C#以及VB.NET代码示例来介绍获取Word文档中指定图片的坐标位置。

01

指定文件路径,本次测试代码路径为项目文件夹路径。即在Visual Studio项目文件下存入用于测试的Word文档,如:C:\Users\Administrator\Documents\Visual Studio 2013\Projects\ExtractTextandImage_Doc\GetCoordinatesOfImg\bin\Debug\test.docx。文件路径也可自定义为其他路径。

02

在“解决方案资源管理器”中引入必要程序集文件,如下图:

03

在程序中键入如下C#代码: 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(); } } } } } } } }

04

完成代码后,执行程序,输出图片坐标获取结果,如下图:

05

附VB.NET代码: 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

加载全部内容

相关教程
猜你喜欢
用户评论