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 ...
随机推荐
- Linux命令应用大词典-第21章 LVM和RAID管理
21.1 pvcreate:创建物理卷 21.2 pvscan:列出找到的物理卷 21.3 pvdisplay:显示物理卷的相关属性 21.4 vgcreate:创建卷组 21.5 vgscan:查找 ...
- Linux 文件的常识
文件 文件的分类 文件 目录 链接 区分办法,ls -la 查看 十个标志符中的第一个 如:drwxrwxr-x. 2 normal normal 4096 8月 31 23:43 dir 目录是d ...
- Spring Cloud(十一):服务网关 Zuul(过滤器)【Finchley 版】
Spring Cloud(十一):服务网关 Zuul(过滤器)[Finchley 版] 发表于 2018-04-23 | 更新于 2018-05-07 | 在上篇文章中我们了解了 Spring ...
- JavaScript 正则
元字符 预定义类 边界 ^在中括号中时,匹配非hello的 str = 'hello world' str.match(/[^hello]/g) //[" ", "w&q ...
- Centos配置深度学习开发环境
目录 1. 安装显卡驱动 2. 安装CUDA\CUDNN 3. 安装TensorFlow-gpu 测试 1. 安装显卡驱动 检测显卡驱动及型号 $ sudo rpm --import https:// ...
- 使用深度学习来破解 captcha 验证码(转)
使用深度学习来破解 captcha 验证码 本项目会通过 Keras 搭建一个深度卷积神经网络来识别 captcha 验证码,建议使用显卡来运行该项目. 下面的可视化代码都是在 jupyter not ...
- HADOOP docker(八):hadoop本地库
前言2. Native Hadoop Library3. 使用本地库4. 本地库组件5. 支持的平台6. 下载7. 编译8. 运行时观察9. 检查本地库10. 如果共享本地库 小伙伴还记得每次启动hd ...
- [leetcode-676-Implement Magic Dictionary]
Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...
- logstash+elasticsearch 错误摘记
[2017-09-17T06:00:22,511][WARN ][o.e.b.ElasticsearchUncaughtExceptionHandler] [] uncaught exception ...
- python学习笔记06:操作文件
调用内置的open函数打开文件,传递两个参数:文件路径(绝对路径或相对路径),打开模式('r':读,'r+':读写,'w':写,'b':二进制): f = open('data.txt','w') f ...