Java 替换word文档文字并指定位置插入图片
程序员文章站
2023-12-01 14:55:58
先说下 需要的依赖包
org.apache.poi
先说下 需要的依赖包
<dependency> <groupid>org.apache.poi</groupid> <artifactid>poi-excelant</artifactid> <version>3.12</version> </dependency> <dependency> <groupid>org.apache.poi</groupid> <artifactid>poi-scratchpad</artifactid> <version>3.12</version> </dependency> <dependency> <groupid>org.apache.poi</groupid> <artifactid>poi-ooxml</artifactid> <version>3.8</version> </dependency> <dependency> <groupid>org.apache.poi</groupid> <artifactid>poi-ooxml-schemas</artifactid> <version>3.8</version> </dependency> <!-- 生成图片--> <dependency> <groupid>org.jfree</groupid> <artifactid>jfreechart</artifactid> <version>1.0.19</version> </dependency> <dependency> <!--支持插入图片--> <groupid>org.docx4j</groupid> <artifactid>docx4j</artifactid> <version>3.3.1</version> </dependency>
示例,下图
如上图,需要替换的字符串地方“$1”为“1231”,在指定位置插入书签,并命名“test” ,插入的图片如下
本人也没太过多去研究,亲测通过有效,在这分享下
1.demo
import java.awt.font; import java.io.file; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.math.biginteger; import java.text.decimalformat; import java.text.numberformat; import java.util.iterator; import java.util.list; import java.util.map; import java.util.set; import org.apache.poi.poixmldocument; import org.apache.poi.openxml4j.opc.opcpackage; import org.apache.poi.util.ioutils; import org.apache.poi.xwpf.usermodel.xwpfdocument; import org.apache.poi.xwpf.usermodel.xwpfparagraph; import org.apache.poi.xwpf.usermodel.xwpfrun; import org.docx4j.traversalutil; import org.docx4j.dml.wordprocessingdrawing.inline; import org.docx4j.finders.rangefinder; import org.docx4j.openpackaging.packages.wordprocessingmlpackage; import org.docx4j.openpackaging.parts.wordprocessingml.binarypartabstractimage; import org.docx4j.openpackaging.parts.wordprocessingml.maindocumentpart; import org.docx4j.wml.body; import org.docx4j.wml.booleandefaulttrue; import org.docx4j.wml.ctbookmark; import org.docx4j.wml.color; import org.docx4j.wml.document; import org.docx4j.wml.drawing; import org.docx4j.wml.hpsmeasure; import org.docx4j.wml.objectfactory; import org.docx4j.wml.p; import org.docx4j.wml.r; import org.docx4j.wml.rpr; import org.jfree.chart.chartfactory; import org.jfree.chart.chartutilities; import org.jfree.chart.jfreechart; import org.jfree.chart.labels.standardpiesectionlabelgenerator; import org.jfree.chart.plot.pieplot; import org.jfree.chart.title.texttitle; import org.jfree.data.general.defaultpiedataset;import com.aisino.qysds.common.constant.errorconstants; import com.aisino.qysds.common.exception.sysexception; import com.aisino.qysds.service.iexportbgservice; import com.google.common.collect.maps; public class exportbgserviceimpl { public static void main(string[] args) throws exception { map<string, string> map = maps.newhashmap(); map.put("$1", "1231"); xwpfdocument document = new xwpfdocument(poixmldocument.openpackage("d:\\tp\\test.docx")); iterator<xwpfparagraph> itpara = document.getparagraphsiterator(); while (itpara.hasnext()) { xwpfparagraph paragraph = (xwpfparagraph) itpara.next(); list<xwpfrun> runs = paragraph.getruns(); for (int i = 0; i < runs.size(); i++) { string oneparastring = runs.get(i).gettext(runs.get(i).gettextposition()); for (map.entry<string, string> entry : map.entryset()) { if (oneparastring.equals(entry.getkey())) { oneparastring = oneparastring.replace(entry.getkey(), entry.getvalue()); } } runs.get(i).settext(oneparastring, 0); } } fileoutputstream outstream = null; outstream = new fileoutputstream("d:\\tp\\test1.docx"); document.write(outstream); outstream.close(); //-----------------------------------这块为生成图片 和 插入图片 defaultpiedataset dataset = new defaultpiedataset(); dataset.setvalue("修改类", 1); dataset.setvalue("提示类", 1); dataset.setvalue("校验不通过", 3); dataset.setvalue("正常类", 3); jfreechart chart = chartfactory.createpiechart3d(null, dataset, true, false, false); chart.getlegend().setitemfont(new font("黑体", font.bold, 15)); // 设置图例类别字体 // texttitle title = new texttitle(titlestring); // title.setfont(new font("黑体", font.italic, 20));//设置标题字体 // chart.settitle(title); pieplot pieplot = (pieplot) chart.getplot(); decimalformat df = new decimalformat("0.00%"); numberformat nf = numberformat.getinstance(); standardpiesectionlabelgenerator generator = new standardpiesectionlabelgenerator("{0} {2}", nf, df);// 获得standardpiesectionlabelgenerator对象,生成的格式, // {0}表示section名,{1}表示section的值,{2}表示百分比。可以自定义 pieplot.setlabelgenerator(generator);// 设置百分比 pieplot.setlabelfont(new font("黑体", font.italic, 15));// 设置饼图中类别字体 pieplot.setnodatamessage("此时并没有任何数据可用"); pieplot.setcircular(false); pieplot.setlabelgap(0.02d); pieplot.setignorenullvalues(true);// 设置不显示空位 pieplot.setignorezerovalues(true);// 设置不显示负值或零值 string fname = "pie.png"; file file = new file("d:\\tp", fname); if (file.exists()) { file.delete(); } try { chartutilities.savechartaspng(file, chart, 800, 500); file file2 = new file("d:\\tp\\test1.docx"); wordprocessingmlpackage wpackage = wordprocessingmlpackage.load(new fileinputstream(file2)); maindocumentpart maindocumentpart = wpackage.getmaindocumentpart(); document wmldoc = (document) maindocumentpart.getjaxbelement(); body body = wmldoc.getbody(); // 提取正文中所有段落 list<object> paragraphs = body.getcontent(); // 提取书签并创建书签的游标 rangefinder rt = new rangefinder("ctbookmark", "ctmarkuprange"); new traversalutil(paragraphs, rt); for (ctbookmark bm : rt.getstarts()) { if (bm.getname().equals("test")) {// 这里的test为 word文档中预设的 书签名 inputstream inputstream = new fileinputstream(file); byte[] bytes = ioutils.tobytearray(inputstream); binarypartabstractimage imagepart = binarypartabstractimage.createimagepart(wpackage, bytes); inline inline = imagepart.createimageinline(null, null, 0, 1, false, 10000);//这里的100000不是正常屏幕大小,用于设置插入图片的大小 p p = (p) (bm.getparent()); objectfactory factory = new objectfactory(); // r对象是匿名的复杂类型,然而我并不知道具体啥意思,估计这个要好好去看看ooxml才知道 r run = factory.creater(); // drawing理解为画布? drawing drawing = factory.createdrawing(); drawing.getanchororinline().add(inline); run.getcontent().add(drawing); p.getcontent().add(run); } } wpackage.save(new fileoutputstream(new file("d:\\tp\\test1.docx"))); } catch (ioexception e) { } } }
最后效果图如下:
总结
以上所述是小编给大家介绍的java 替换word文档文字并指定位置插入图片,希望对大家有所帮助
上一篇: Java虚拟机GC日志分析