package com.xxxx;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureRenderData;
import org.springframework.core.io.ClassPathResource;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.stream.FileImageOutputStream;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class Text {
public static void asd() {
try {
//待处理的图片
String imgFile = "D:/123.jpg";
//将图片转化成base64
InputStream in = null;
byte[] data1;
//读取图片字节数组
in = new FileInputStream(imgFile);
data1 = new byte[in.available()];
in.read(data1);
in.close();
//获取base64码转换成byte[]数组
byte[] bytes = new byte[0];
//对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
//base64编码会自动换行
String imageData = encoder.encode(data1).replaceAll("[\\s*\t\n\r]", "");
//将base64转化为流
bytes = new BASE64Decoder().decodeBuffer(imageData.trim());
//转化为输入流
File file = new File("");
String filePath1 = file.getCanonicalPath();//获取项目路径
System.out.println(filePath1+"\\p.jpg");
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);//输入流输入bytes数组
int leng;
byte[] b = new byte[1024];
FileImageOutputStream imageOutput = new FileImageOutputStream(new File("filePath1.jpg"));//打开输入流生成图片
while ((leng = inputStream.read(b)) != -1) {
//将byte写入硬盘
imageOutput.write(b, 0, leng);
}
imageOutput.close();
Map<String, Object> data = new HashMap<String, Object>();
// 文本
data.put("name", "张三");
//图片(自定义设置高/宽)
data.put("photo", new PictureRenderData(127, 185, "filePath1.jpg"));
// 写入word输出
System.out.println(filePath1+"\\wordTest.docx");
//获取模板
ClassPathResource template = new ClassPathResource("D:/360/img.docx");
//读取图片路径
String filePath = template.getPath();
//填充word
XWPFTemplate xwpfTemplate = XWPFTemplate.compile(filePath).render(data);
//生成word路径
String docName = filePath1+System.currentTimeMillis() + ".docx";
//新建File文件对象
File targetFile = new File(docName);
//FileOutputStream文件字节输出流
FileOutputStream out = new FileOutputStream(targetFile);
xwpfTemplate.write(out);
out.flush(); //刷新
out.close(); //关流
xwpfTemplate.close();
} catch (
IOException e) {
e.printStackTrace();
}
}
}
向word文档中插入文字和图片
最新推荐文章于 2024-04-29 15:51:13 发布