本文介绍如何使用Spire.Doc for Java将Word文档中的特定文本用图片来替换。
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
public class ReplaceTextWithImage {
public static void main(String[] args) {
//加载示例文档
Document document = new Document();
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");
//查找文档中的字符串“成都冰蓝科技有限公司”
TextSelection[] selections = document.findAllString("成都冰蓝科技有限公司", true, true);
//用图片替换文字
int index = 0;
TextRange range = null;
for (Object obj : selections) {
TextSelection textSelection = (TextSelection)obj;
DocPicture pic = new DocPicture(document);
pic.loadImage("C:\\Users\\Administrator\\Desktop\\e-iceblue-logo.png");
range = textSelection.getAsOneRange();
index = range.getOwnerParagraph().getChildObjects().indexOf(range);
range.getOwnerParagraph().getChildObjects().insert(index,pic);
range.getOwnerParagraph().getChildObjects().remove(range);
}
//保存文档
document.saveToFile("output/ReplaceTextWithImage.docx", FileFormat.Docx_2013);
}
}