最好可以指定大小,在其基础上还要编辑文本信息,表格信息。
用poi技术可以实现Word文档的操作。
word文档实际上也是 一个个xml文件进行压缩而成的 可以通过压缩文件进行打开 然后通过操作xml
方便的话,能否提供一个demo
import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordUtil_img {
// word运行程序对象
private ActiveXComponent word;
// 所有word文档集合
private Dispatch documents;
// word文档
private Dispatch doc;
// 选定的范围或插入点
private Dispatch selection;
// 保存退出
private boolean saveOnExit;
/**
* 是否可见word程序
* @param visible true-可见word程序,false-后台默默执行。
*/
public WordUtil_img(boolean visible) {
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible", new Variant(visible));
documents = word.getProperty("Documents").toDispatch();
}
/**
* 打开一个已经存在的Word文档
* @param docPath 文件的路径
*/
public void openDocument(String docPath) {
doc = Dispatch.call(documents, "Open", docPath).toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
}
/**
* 全局将指定的文本替换成图片
* @param findText
* @param imagePath
*/
public void replaceAllImage(String findText, String imagePath, int width, int height){
moveStart();
while (find(findText)){
Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch();
Dispatch.call(picture, "Select");
Dispatch.put(picture, "Width", new Variant(width));
Dispatch.put(picture, "Height", new Variant(height));
moveStart();
}
}
/**
* 把插入点移动到文件首位置
*/
public void moveStart(){
Dispatch.call(getSelection(), "HomeKey", new Variant(6));
}
/**
* 获取当前的选定的内容或者插入点
* @return 当前的选定的内容或者插入点
*/
public Dispatch getSelection(){
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
return selection;
}
/**
* 从选定内容或插入点开始查找文本
* @param findText 要查找的文本
* @return boolean true-查找到并选中该文本,false-未查找到文本
*/
public boolean find(String findText){
if(findText == null || findText.equals("")){
return false;
}
// 从selection所在位置开始查询
Dispatch find = Dispatch.call(getSelection(), "Find").toDispatch();
// 设置要查找的内容
Dispatch.put(find, "Text", findText);
// 向前查找
Dispatch.put(find, "Forward", "True");
// 设置格式
Dispatch.put(find, "Format", "True");
// 大小写匹配
Dispatch.put(find, "MatchCase", "True");
// 全字匹配
Dispatch.put(find, "MatchWholeWord", "True");
// 查找并选中
return Dispatch.call(find, "Execute").getBoolean();
}
/**
* 文档另存为
* @param savePath
*/
public void saveAs(String savePath){
Dispatch.call(doc, "SaveAs", savePath);
}
/**
* 关闭word文档
*/
public void closeDocument(){
if (doc != null) {
Dispatch.call(doc, "Close", new Variant(saveOnExit));
doc = null;
}
}
}
public static void main(String[] args) {
WordInsertImg("F:\\我是word.doc","F:\\pikaqiu,jpg");
}
public static void WordInsertImg(String WordPath,String ImgPaht) {
WordUtil_img demo = new WordUtil_img(false);//获取工具类对象
demo.openDocument(WordPath);//打开word
// 在指定位置插入指定的图片
demo.replaceAllImage("AAA",ImgPaht,60,60);//AAA是指定的图片位置。后面的两个参数是指定图片的长和宽。
demo.saveAs("f:\\我是皮卡丘.doc");//插入成功后生成的新word
demo.closeDocument();//关闭对象。
System.out.println("插入成功");
}
springboot项目,先导入两个POI依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
首先创建一个继承XWPFDocument的类,写一个创建图片的方法。之后会使用该类进行创建图片(poi创建图片有bug),因为继承了XWPFDocument,所以后续的使用中不会报错。
/**
* @Author: SONGTIANk
* @Description: 继承XWPF类,写一个创建图片方法
* @Date: 2020/11/11 17:42
* @Version: 1.0
*/
public class CustomXWPFDocument extends XWPFDocument {
public CustomXWPFDocument(InputStream in) throws IOException {
super(in);
}
public CustomXWPFDocument() {
super();
}
public CustomXWPFDocument(OPCPackage pkg) throws IOException {
super(pkg);
}
/**
* @param id
* @param width 宽
* @param height 高
* @param paragraph 段落
*/
public void createPicture(int id, int width, int height, XWPFParagraph paragraph) {
final int EMU = 9525;
width *= EMU;
height *= EMU;
String blipId = getAllPictures().get(id).getPackageRelationship().getId();
CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();
String picXml = ""
+"<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
+" <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
+" <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
+" <pic:nvPicPr>" + " <pic:cNvPr id=\""
+ id
+"\" name=\"Generated\"/>"
+" <pic:cNvPicPr/>"
+" </pic:nvPicPr>"
+" <pic:blipFill>"
+" <a:blip r:embed=\""
+ blipId
+"\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
+" <a:stretch>"
+" <a:fillRect/>"
+" </a:stretch>"
+" </pic:blipFill>"
+" <pic:spPr>"
+" <a:xfrm>"
+" <a:off x=\"0\" y=\"0\"/>"
+" <a:ext cx=\""
+ width
+"\" cy=\""
+ height
+"\"/>"
+" </a:xfrm>"
+" <a:prstGeom prst=\"rect\">"
+" <a:avLst/>"
+" </a:prstGeom>"
+" </pic:spPr>"
+" </pic:pic>"
+" </a:graphicData>" + "</a:graphic>";
inline.addNewGraphic().addNewGraphicData();
XmlToken xmlToken = null;
try{
xmlToken = XmlToken.Factory.parse(picXml);
}catch(XmlException xe) {
xe.printStackTrace();
}
inline.set(xmlToken);
inline.setDistT(0);
inline.setDistB(0);
inline.setDistL(0);
inline.setDistR(0);
CTPositiveSize2D extent = inline.addNewExtent();
extent.setCx(width);
extent.setCy(height);
CTNonVisualDrawingProps docPr = inline.addNewDocPr();
docPr.setId(id);
docPr.setName("图片"+ id);
docPr.setDescr("测试");
}
}
之后就是Word工具类了,看一下注释吧
import org.apache.poi.xwpf.usermodel.*;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Author: SONGTIANk
* @Description: Word替换字符和插入图片工具类
* @Date: 2020/11/11 17:16
* @Version: 1.0
*/
public class WordUtils {
/**
* 根据模板生成word
* @param path 模板的路径
* @param params 需要替换的参数
* @param fileName 生成word文件的文件名
* @tips 此处为了方便而将文件生成在了本地,
* 你也可以直接将文件放入response 响应头中,调用浏览器的下载器直接下载到本地,
* 这样更符合业务逻辑,即:数据库或者页面输入数据到word模板中,自动生成word并下载;
* 也可使用插入图片,替换需要在业务中插入的电子签名,或者盖章的word文档。
* 当然了,此处的传参就需要多加一个 HttpServletResponse response
* 文件名写中文会有乱码,具体如何调用浏览器下载和解决乱码问题可参考我的另一篇
* [简便的Excel导出功能](https://blog.csdn.net/weixin_43238452/article/details/108790379)的解决办法。
*/
public void getWord(String path, Map<String, Object> params,String fileName) throws Exception {
File file = new File(path);
//创建输入流
InputStream is = new FileInputStream(file);
//创建doc对象
CustomXWPFDocument doc = new CustomXWPFDocument(is);
//替换文本里面的变量
this.replaceInPara(doc, params);
//输出流写入文件
FileOutputStream out = new FileOutputStream(fileName);
doc.write(out);
//关闭输入输出流
this.close(is);
out.close();
System.out.println("<-----生成结束----->");
}
/**
* 替换段落里面的变量
* @param doc 要替换的文档
* @param params 参数
*/
private void replaceInPara(CustomXWPFDocument doc, Map<String, Object> params) {
Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
XWPFParagraph para;
while (iterator.hasNext()) {
para = iterator.next();
this.replaceInPara(para, params, doc);
}
}
/**
* 替换段落里面的变量
* @param para 要替换的段落
* @param params 参数
*/
private void replaceInPara(XWPFParagraph para, Map<String, Object> params, CustomXWPFDocument doc) {
List<XWPFRun> runs;
Matcher matcher;
if (this.matcher(para.getParagraphText()).find()) {
runs = para.getRuns();
int start = -1;
int end = -1;
String str = "";
for (int i = 0; i < runs.size(); i++) {
XWPFRun run = runs.get(i);
String runText = run.toString();
if ('$' == runText.charAt(0) && '{' == runText.charAt(1)) {
start = i;
}
if ((start != -1)) {
str += runText;
}
if ('}' == runText.charAt(runText.length() - 1)) {
if (start != -1) {
end = i;
break;
}
}
}
for (int i = start; i <= end; i++) {
para.removeRun(i);
i--;
end--;
}
for (Map.Entry<String, Object> entry : params.entrySet()) {
String key = entry.getKey();
if (str.indexOf(key) != -1) {
Object value = entry.getValue();
if (value instanceof String) {
str = str.replace(key, value.toString());
para.createRun().setText(str, 0);
break;
} else if (value instanceof Map) {
str = str.replace(key, "");
Map pic = (Map) value;
int width = Integer.parseInt(pic.get("width").toString());
int height = Integer.parseInt(pic.get("height").toString());
int picType = getPictureType(pic.get("type").toString());
byte[] byteArray = (byte[]) pic.get("content");
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
try {
//int ind = doc.addPicture(byteInputStream,picType);
//doc.createPicture(ind, width , height,para);
doc.addPictureData(byteInputStream, picType);
doc.createPicture(doc.getAllPictures().size() - 1, width, height, para);
para.createRun().setText(str, 0);
break;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
/**
* 正则匹配字符串
* @param str
* @return
*/
private Matcher matcher(String str) {
Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
}
/**
* 根据图片类型,取得对应的图片类型代码
* @param picType
* @return int
*/
private static int getPictureType(String picType) {
int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
if (picType != null) {
if (picType.equalsIgnoreCase("png")) {
res = CustomXWPFDocument.PICTURE_TYPE_PNG;
} else if (picType.equalsIgnoreCase("dib")) {
res = CustomXWPFDocument.PICTURE_TYPE_DIB;
} else if (picType.equalsIgnoreCase("emf")) {
res = CustomXWPFDocument.PICTURE_TYPE_EMF;
} else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
} else if (picType.equalsIgnoreCase("wmf")) {
res = CustomXWPFDocument.PICTURE_TYPE_WMF;
}
}
return res;
}
/**
* 将输入流中的数据写入字节数组
* @param in
* @return
*/
public static byte[] inputStream2ByteArray(InputStream in, boolean isClose) {
byte[] byteArray = null;
try {
int total = in.available();
byteArray = new byte[total];
in.read(byteArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (isClose) {
try {
in.close();
} catch (Exception e2) {
e2.getStackTrace();
}
}
}
return byteArray;
}
/**
* 关闭输入流
* @param is
*/
private void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
word和测试类
public static void main(String[] args) {
WordUtils wordUtil=new WordUtils();
Map<String, Object> params = new HashMap<String, Object>();
params.put("${position}", "java开发");
params.put("${name}", "焦糖橙子");
params.put("${sex}", "男");
params.put("${eMail}", "8888@csdn.com");
try{
Map<String,Object> jpeg1 = new HashMap<String, Object>();
jpeg1.put("width", 100);
jpeg1.put("height", 150);
jpeg1.put("type", "jpg");
jpeg1.put("content", WordUtils.inputStream2ByteArray(new FileInputStream("D:\\text\\cat.jpg"), true));
params.put("${jpeg1}",jpeg1);
Map<String,Object>jpeg2 = new HashMap<String, Object>();
jpeg2.put("width", 100);
jpeg2.put("height", 150);
jpeg2.put("type", "jpg");
jpeg2.put("content", WordUtils.inputStream2ByteArray(new FileInputStream("D:\\text\\dog.jpg"), true));
params.put("${jpeg2}",jpeg2);
//模板文件位置
String path="D:\\text\\myword.docx";
//生成文件位置
String fileName= new String("D:\\text\\myTest.docx".getBytes("UTF-8"),"iso-8859-1");
wordUtil.getWord(path,params,fileName);
}catch(Exception e){
e.printStackTrace();
}
}
执行结果
参考下free spire.doc for java添加图片的方法
https://www.e-iceblue.cn/docforjava/insert-image-into-word-document-in-java.html
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632
找到了有效的解决办法,国内有一个很强大的工具类,有遇到类似问题的都可以去看一下。http://deepoove.com/poi-tl/