Java Web用Freemarker生成带图片的Word文档
步骤一:模板制作
用world2003做一个导出模板,如果有图片则加入一张图片占位,将world另存为xml,将xml中需要导出的内容用Freemarker标签表示,最后另存为.ftl结尾的模板:
步骤二:后台代码
1、获取导出的数据:
@RequestMapping(value = "/exportDoc")
public void exportDoc(String resumeId,HttpServletResponse response,HttpServletRequest request) throws Exception{ User u= SessionUtils.getUser(request.getSession());
Map<String, Object> dataMap = new HashMap<String, Object>();// 要填入模本的数据文件
ResumeBasicInformationQueryParam resumeParam=new ResumeBasicInformationQueryParam(); resumeParam.setUuid(resumeId);
WorkExperienceParam workExperienceParam=new WorkExperienceParam();
workExperienceParam.setResumeId(resumeId); EducationBackgroundParam educationParam=new EducationBackgroundParam();
educationParam.setResumeId(resumeId); SkillEvaluationParam skillParam=new SkillEvaluationParam();
skillParam.setResumeId(resumeId); ProjectExperienceParam projectParam=new ProjectExperienceParam();
projectParam.setResumeId(resumeId); LanguageabilityParam languageParam=new LanguageabilityParam();
languageParam.setResumeId(resumeId); TrainingExperienceParam trainParam=new TrainingExperienceParam();
trainParam.setResumeId(resumeId); //验证导出用户是否可以看到简历姓名
ResumeHandleParam handleParam=new ResumeHandleParam();
handleParam.setResumeIds("'"+resumeParam.getUuid()+"'");
handleParam.setCorpId(SessionUtils.getCorpId(request.getSession()));
int count = 0; count = resumeHandleService.checkEnshrine(handleParam); ResumeBasicInformationResp rbIfonResp = new ResumeBasicInformationResp();
//查询当前登录用户的简历基本信息
List<ResumeBasicInformationResp> resumeBasicList = resumeBasicInformationService.getResumeBasic(resumeParam);
if(resumeBasicList.size()>0){
rbIfonResp = resumeBasicList.get(0);
//性别
if("1".equals(rbIfonResp.getGender())){
rbIfonResp.setGender("男");
}else{
rbIfonResp.setGender("女");
}
//婚姻状况
if("1".equals(rbIfonResp.getMaritalStatus())){
rbIfonResp.setGender("已婚");
}else if("2".equals(rbIfonResp.getMaritalStatus())){
rbIfonResp.setGender("未婚");
}else{
rbIfonResp.setGender("保密");
} //姓名、邮箱、电话是否可见
if(count==0){ //没有将该简历放入简历库、没有投递该企业,若简历设置了不可见,则企业看不到
if("1".equals(rbIfonResp.getNamePrivacy()) && rbIfonResp.getName()!=""){
String name = rbIfonResp.getName().substring(0, 1)+" *";
rbIfonResp.setName(name);
} if("1".equals(rbIfonResp.getEmailPrivacy()) && rbIfonResp.getEmail()!=""){
int pos = rbIfonResp.getEmail().indexOf("@");
String result = rbIfonResp.getEmail().substring(pos, rbIfonResp.getEmail().length());
rbIfonResp.setEmail("****"+result);
} if("1".equals(rbIfonResp.getTelPrivacy()) && rbIfonResp.getTelephone()!=""){
String telephone = rbIfonResp.getTelephone().substring(0, 3) + "****" + rbIfonResp.getTelephone().substring(7, 11) ;
rbIfonResp.setTelephone(telephone);
}
}
} dataMap.put("rbIfonResp", rbIfonResp);
//dataMap.put("resumeList", resumeBasicList); //工作经历信息
List<WorkExperienceResp> workExperienceList=workExperienceService.selectWorkExperience(workExperienceParam);
dataMap.put("workExperienceList", workExperienceList);
//教育经历信息
List<EducationBackgroundResp> educationList=educationService.selectEducation(educationParam);
dataMap.put("educationList", educationList);
//技能评价信息
List<SkillEvaluationResp> skillList=skillService.selectSkillEvaluation(skillParam);
dataMap.put("skillList", skillList);
//项目经验信息
List<ProjectExperienceResp> projectList=projectService.selectProject(projectParam);
dataMap.put("projectList", projectList);
//语言能力信息
List<LanguageabilityResp> languageList=languageService.selectLanguage(languageParam);
dataMap.put("languageList", languageList);
//培训经历
List<TrainingExperienceResp> trainList=trainingService.selectTrainingExperience(trainParam);
dataMap.put("trainList", trainList); //作品展示
WorkAttachmentParam waParam = new WorkAttachmentParam();
waParam.setResumeId(resumeId);
waParam.setWorkType("1"); // 类型:1-作品;2-附件
List<WorkAttachmentResp> workAttachemntList = workAttachmentService.selectWorkAttachment(waParam); //作品路径
String resourceUrl = "";
//项目路径
String url = FileManagerUtils.getFilePath(null) + "/"; if(workAttachemntList!=null && workAttachemntList.size()>0){
for(int i=0;i<workAttachemntList.size();i++){
resourceUrl = url + workAttachemntList.get(i).getResourceUrl(); //先将网络图片下载到本地,再将本地图片转换成BASE64字符串
workAttachemntList.get(i).setResourceUrl(getImageString(resourceUrl));
workAttachemntList.get(i).setIndex(i); }
}
dataMap.put("workAttachemntList", workAttachemntList); ExportDoc exportDoc = new ExportDoc();
exportDoc.create(dataMap,response); }
2、将本地、网络图片转换成BASE64字符串
/**
*
* @Title: getImageString
* @Description: 将本地、网络图片转换成BASE64字符串
* @param @param filename
* @param @return
* @param @throws IOException
* @return String
* @throws
*/
public static String getImageString(String imageUrl) throws IOException { //InputStream in = null; InputStream dis = null;
byte[] data = null; try { //方法一、将网络图片导入wolrd
URL url = new URL(imageUrl);
//打开网络输入流
URLConnection conn = url.openConnection(); //设置超时间为3秒
//conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
//conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
data = readInputStream(inputStream); /*
//方法二、将本地图片导入wolrd,打开本地输入流
in = new FileInputStream(imageUrl);
data = new byte[in.available()];
in.read(data);
in.close();
*/ } catch (IOException e) {
throw e;
} finally {
if (dis != null)
dis.close();
} BASE64Encoder encoder = new BASE64Encoder(); return data != null ? encoder.encode(data) : ""; }
/**
*
* @Title: readInputStream
* @Description: 将网络图片流转换成数组
* @param @param inputStream
* @param @return
* @param @throws IOException
* @return byte[]
* @throws
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
} /**
* @Title: downloadImg
* @Description: 网络图片下載到本地
* @param @param imgUrl:网络图片,http开头
* @param @return 返回下载到本地的图片路径
* @param @throws Exception
* @return String
* @throws
*/
public String downloadImg(String imgUrl) throws Exception{ // 构造URL
URL url = new URL(imgUrl);
// 打开连接
URLConnection con = url.openConnection();
//设置请求超时为5s
con.setConnectTimeout(5*1000);
// 输入流
InputStream is = con.getInputStream(); // 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len; //创建下载路径
String savePath = "D://download//";
String filename = UUIDUtil.getUUID()+".jpg";
String returnUrl = savePath+filename; File sf = new File(savePath);
if(!sf.exists()){
sf.mkdirs();
} // 输出的文件流
OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.flush();
os.close();
is.close(); return returnUrl;
}
3、导出模板
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import freemarker.template.Configuration;
import freemarker.template.Template; /**
*
* @ClassName:ExportDoc
* @Description: 导出简历模板
* @author:
* @date:2015-6-25 下午3:52:12
* @version 1.0
*/
public class ExportDoc { private Configuration configuration = null; public ExportDoc() {
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
} /**
*
* @Title: create
* @Description: 注意dataMap里存放的数据Key值要与模板中的参数相对应
* @param @param dataMap
* @param @param response
* @param @throws Exception
* @return void
* @throws
*/
public void create(Map<String, Object> dataMap, HttpServletResponse response)
throws Exception { // 模板放在com.canyou.template包下面,通过classpath装载
configuration.setClassForTemplateLoading(this.getClass(), "/com/***/ftl"); //自己在项目中放入模板位置
Template template = configuration.getTemplate("resume.ftl");// 设置要装载的模板 String fileName = String.valueOf(Math.random()*10000);
File outFile = new File(fileName.replace(".", "")+".doc"); if (!outFile.exists()) {
outFile.createNewFile();
} Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
template.process(dataMap, out);
out.close(); //导出时有界面,可选择下载路径
response.addHeader("Content-Disposition", "attachment;filename=" + new String(outFile.getName().getBytes("utf-8"), "utf-8"));
response.setContentType("application/msword"); OutputStream out1 = null;
InputStream in = null; try {
in = new FileInputStream(outFile); out1 = response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(in);
BufferedOutputStream bos = new BufferedOutputStream(out1); byte[] buff = new byte[20480];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.flush();
bos.close(); } catch (Exception e) {
e.printStackTrace();
} finally {
if (out1 != null)
out1.close();
if (in != null)
in.close();
} } }
Java Web用Freemarker生成带图片的Word文档的更多相关文章
- freemarker导出带图片的word文档
最近做一个关于文档导出功能, 顺便学习了下freemarker,做了个关于导出带图片的word文档,模板并没有写全,只是验证代码的正确性 这只是做一个小功能,故只做了后台代码关于导出的代码,并未与前台 ...
- java 在MySQL中存储文件,读取文件(包括图片,word文档,excel表格,ppt,zip文件等)
转自:https://blog.csdn.net/u014475796/article/details/49893261 在设计到数据库的开发中,难免要将图片或文档文件(如word)插入到数据库中的情 ...
- 解决图片插入word文档后清晰度降低的问题
解决图片插入word文档后清晰度降低的问题 在默认情况下,word程序会自动压缩插入word文档中的图片以减小整个word文档的.当我们需要插入word文档中的图片保持原始清晰度时,可以通过设置wor ...
- 基于springboot的freemarker创建指定格式的word文档
在web或其他应用中,经常我们需要导出或者预览word文档,比较实际的例子有招聘网站上预览或者导出个人简历,使用POI导出excel会非常的方便,但是如果想导出word,由于其格式控制非常复杂,故而使 ...
- JAVA:借用OpenOffice将上传的Word文档转换成Html格式
为什么会想起来将上传的word文档转换成html格式呢?设想,如果一个系统需要发布在页面的文章都是来自word文档,一般会执行下面的流程:使用word打开文档,Ctrl+A,进入发布文章页面,Ctrl ...
- Java 添加条码、二维码到Word文档
本文介绍如何在Word文档中添加条码.二维码.可在文档正文段落中添加,也可在页眉页脚中添加.下面将通过Java代码示例介绍如何实现. 使用工具:Free Spire.Office for Java(免 ...
- Java文件操作系列[3]——使用jacob操作word文档
Java对word文档的操作需要通过第三方组件实现,例如jacob.iText.POI和java2word等.jacob组件的功能最强大,可以操作word,Excel等格式的文件.该组件调用的的是操作 ...
- Java 添加、读取、修改、删除Word文档属性
Word文档属性包括常规.摘要.统计.内容.自定义等,其中摘要包括标题.主题.作者.经理.单位.类别.关键词.备注等项目,通过设置这些摘要信息或自定义属性可方便对文档的管理.本文中将主要介绍对文档摘要 ...
- java通过freemarker导出包含富文本图片的word文档
废话不多说,进入正题! 本文重点在于:对富文本图片的导出(基础的freemarker+word模板导出这里不做详细解说哈) 参考文章:http://www.cnblogs.com/liaofeifig ...
随机推荐
- Python 多线程、进程、协程上手体验
浅谈 Python 多线程.进程.协程上手体验 前言:浅谈 Python 很多人都认为 Python 的多线程是垃圾(GIL 说这锅甩不掉啊~):本章节主要给你体验下 Python 的两个库 Thre ...
- python一标准异常总结大全(非常全)
Python标准异常总结 AssertionError 断言语句(assert)失败 AttributeError 尝试访问未知的对象属性 EOFError 用户输入文件末尾标志EOF(Ctrl+d) ...
- 只写Python一遍代码,就可以同时生成安卓及IOS的APP,真优秀
前言: 用Python写安卓APP肯定不是最好的选择,但是肯定是一个很偷懒的选择 我们使用kivy开发安卓APP,Kivy是一套专门用于跨平台快速应用开发的开源框架,使用Python和Cython编写 ...
- POJ 3608 Bridge Across Islands(计算几何の旋转卡壳)
Description Thousands of thousands years ago there was a small kingdom located in the middle of the ...
- Sublime Text 插件推荐——for web developers
楼主向高大上的: web front-end development engineer (好吧,google就是这样翻译的 ^_^)们推荐 ST 插件,在此抛砖引玉: NO.1 :Emmet (原名: ...
- “Hello World!”团队——Alpha发布用户使用报告
博客内容: 1.用户体验报告表 2.用户评论截图 3.总结 一.用户体验报告表 用户使用报告 用户序号 用户姓名(化名) 性别 用户职业 使用频次 用户评论 1 小董 女 文学在读硕士 5 1.游戏界 ...
- 学霸系统PipeLine功能规格说明书
学霸系统PipeLine功能规格说明书共分为以下三部分: 1.产品面向用户群体 2.用户使用说明 3.产品功能具体实现 1.产品面向用户群体 我们这组的项目并不是传统意义上能发布并进行展示的项目,因此 ...
- Android屏幕适配解析 - 详解像素,设备独立像素,归一化密度,精确密度及各种资源对应的尺寸密度分辨率适配问题
. 作者 :万境绝尘 转载请注明出处 : http://blog.csdn.net/shulianghan/article/details/19698511 . 最近遇到了一系列的屏幕适配问题, 以及 ...
- 刷ROM必備的clockworkmod recovery
Desire HD 手機早早就 Root,前陣子也S-OFF 變成工程版的 HBOOT(ENG S-OFF),想要刷機的朋友一定常常聽人提起 clockworkmod recovery ,接下來就是安 ...
- iOS APP中第三方APP调用自己的APP,打开文件
根据需求需要在项目中要打开word.pdf.excel等文件,在info.plist文件中添加 <key>CFBundleDocumentTypes</key> <arr ...