本文介紹通過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;
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);
}
}
}
}
}
}
}
坐标擷取結果:
原創文章,如需轉載請務必注明出處!