1、实现思路
1.创建word模板,在模板中填充相应的变量。
2.该模板中存在图片,调整好大小,起到站位的作用
3.将创建好的模板另存为.xml格式的文件,此时的.xml格式的文件在图片的位置就会出现base64位图片代码,将此代码删掉,换成相应的变量,保存
4.在项目中创建template.ftl,将xml中的代码粘贴过去。
5.在该功能中需要用到freemarker的jar包
6.编写后台代码。
2、具体实现
import freemarker.template.TemplateException;
import sun.misc.BASE64Encoder;
String filePath = "D:/jam.jpg";
InputStream in =null;
try {
in=new FileInputStream(filePath);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] data= null;
try {
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
//注意最好用java自带的base64类,笔者使用了其他的几个工具类都有问题
BASE64Encoder base64Encoder = new BASE64Encoder();
String encodeStr = base64Encoder.encode(data);
System.out.println(encodeStr);
FreeMarkerUtil freeMakerUtil = null;
try {
freeMakerUtil = new FreeMarkerUtil("D:/");
} catch (IOException e) {
e.printStackTrace();
}
Map<String, Object> attachmentMap = new HashMap<>();
attachmentMap.put("qrImg",encodeStr);
String destPath = "D:/test";
//生成附件word文件
String wordFileName = destPath + ".doc";
File wordFile = new File(wordFileName);
File parentDir = wordFile.getParentFile();
if (!parentDir.exists()) {
boolean createResult = parentDir.mkdirs();
}
String attachTemplateName = "test_template.ftl";
//生成附件word文件
try {
freeMakerUtil.generate(attachTemplateName, wordFileName, attachmentMap);
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
generate方法
public void generate(String templateName, String destPath, Map<String, Object> data) throws TemplateException, IOException {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
configuration.setDefaultEncoding("UTF-8");
configuration.setClassForTemplateLoading(this.getClass(), "/freemarker");
Template t = configuration.getTemplate(templateName);
BufferedWriter w = null;
try {
File file = new File(destPath);
w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
t.process(data, w);
w.flush();
} finally {
IOUtils.closeQuietly(w);
}
}