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);
                        }
                    }
                }
            }
        }

    }
}

座標獲取結果:

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