Document document = new Document();
document.loadFromFile("test.docx");
Section section = document.getSections().get(0);
Paragraph paragraph = section.getParagraphs().get(0);
// 设置首行缩进
paragraph.getFormat().setFirstLineIndent(15f);
//设置图片为四周环绕型
DocPicture docPicture = paragraph.appendPicture("Doc-Java.png");
docPicture.setTextWrappingStyle(TextWrappingStyle.Square); Document document = new Document();
document.loadFromFile("test.docx");
Section section = document.getSections().get(0);
List<DocPicture> pictureList= new ArrayList<>();
// 获取所有段落集合
ParagraphCollection paragraphs = section.getParagraphs();
// 例如获取第二个段落的所有DocPicture对象
int paraIndex = 1;
Paragraph paragraph = paragraphs.get(paraIndex);
// 获取段落所有子对象
DocumentObjectCollection childObjects = paragraph.getChildObjects();
for (int j = 0; j < childObjects.getCount(); j++) {
// 判断子对象类型
if (childObjects.get(j).getDocumentObjectType().equals(DocumentObjectType.Picture)) {
DocPicture docPicture = (DocPicture) childObjects.get(j);
// 添加docPicture对象到集合中
pictureList.add(docPicture);
}
} DocPicture docPicture = new DocPicture(document);
docPicture.loadImage("test.png");
docPicture.setTextWrappingStyle(TextWrappingStyle.Square);
// 获取某段落子对象数量
int count = paragraph.getChildObjects().getCount();
Map<Integer,DocPicture> docMap = new HashMap<>();
int index= 0;
for (int i = 0; i < count; i++) {
// 获取每一个段落子对象
DocumentObject documentObject = paragraph.getChildObjects().get(i);
// 判断子对象类型是否为图片
if (documentObject.getDocumentObjectType().equals(DocumentObjectType.Picture)) {
// 如果是的话,添加到map中
DocPicture docPicture1 = (DocPicture) paragraph.getChildObjects().get(i);
docMap.put(index++,docPicture1);
}
}
// 遍历完某个段落之后,可以去替换某张图片,例如替换第二张
DocPicture picture = docMap.get(1);
// 获取图片在段落中的索引值
int pictureIndex = paragraph.getChildObjects().indexOf(picture);
// 插入新图片,删除原有图片
paragraph.getChildObjects().insert(pictureIndex,picture);
paragraph.getChildObjects().removeAt(pictureIndex + 1);