Java 获取 Word 中指定图片的座标位置

程序运行环境:

  • Word测试文档:.docx 2013
  • Free Spire.doc.jar 3.9.0
  • IntelliJ IDEA
  • JDK 1.8.0

方法步骤:

1. 指定文件路径,本次测试代码路径为项目文件夹路径。即在IDEA项目文件下存入用于测试的Word文档,如:C:\Users\Administrator\IdeaProjects\Picture_Doc\input.docx。文件路径也可自定义为其他路径。

2. 在程序中引入jar文件,如下图:

3.Java程序代码

import com.spire.doc.*;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.DocPicture;

//java项目www.fhadmin.org
public class GetCoordinatesOfPicture {
    public static void main(String[] args) {
        //加载Word测试文档
        Document doc = new Document();
        doc.loadFromFile("input.docx");

        //遍历section
        for (int a = 0; a<doc.getSections().getCount();a++)
        {
            Section section = doc.getSections().get(a);

            //遍历paragraph段落
            for (int b =0 ;b<section.getParagraphs().getCount();b++)
            {
                Paragraph paragraph = section.getParagraphs().get(b);

                //遍历段落中的对象
                for (int i = 0; i < paragraph.getChildObjects().getCount(); i++)
                {
                    DocumentObject docobj = paragraph.getChildObjects().get(i);

                    //判断对象是否为图片
                    if (docobj.getDocumentObjectType()== DocumentObjectType.Picture)
                    {
                        DocPicture picture = (DocPicture) docobj ;

                        if (picture.getTitle().equals("图片4"))//定位标题为“图片4”的图片
                        {
                            //获取图片座标位置
                            float x = picture.getHorizontalPosition();
                            float y = picture.getVerticalPosition();
                            System.out.println("座标位置为:\n X=" + x + " Y=" + y);
                        }
                    }
                }
            }
        }

    }
}

座标获取结果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章