本文介绍如何使用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);
}
}