步骤一:模板制作

用world2003做一个导出模板,如果有图片则加入一张图片占位,将world另存为xml,将xml中需要导出的内容用Freemarker标签表示,最后另存为.ftl结尾的模板:

步骤二:后台代码

1、获取导出的数据:

  1. @RequestMapping(value = "/exportDoc")
  2. public void exportDoc(String resumeId,HttpServletResponse response,HttpServletRequest request) throws Exception{
  3.  
  4. User u= SessionUtils.getUser(request.getSession());
  5. Map<String, Object> dataMap = new HashMap<String, Object>();// 要填入模本的数据文件
  6. ResumeBasicInformationQueryParam resumeParam=new ResumeBasicInformationQueryParam();
  7.  
  8. resumeParam.setUuid(resumeId);
  9. WorkExperienceParam workExperienceParam=new WorkExperienceParam();
  10. workExperienceParam.setResumeId(resumeId);
  11.  
  12. EducationBackgroundParam educationParam=new EducationBackgroundParam();
  13. educationParam.setResumeId(resumeId);
  14.  
  15. SkillEvaluationParam skillParam=new SkillEvaluationParam();
  16. skillParam.setResumeId(resumeId);
  17.  
  18. ProjectExperienceParam projectParam=new ProjectExperienceParam();
  19. projectParam.setResumeId(resumeId);
  20.  
  21. LanguageabilityParam languageParam=new LanguageabilityParam();
  22. languageParam.setResumeId(resumeId);
  23.  
  24. TrainingExperienceParam trainParam=new TrainingExperienceParam();
  25. trainParam.setResumeId(resumeId);
  26.  
  27. //验证导出用户是否可以看到简历姓名
  28. ResumeHandleParam handleParam=new ResumeHandleParam();
  29. handleParam.setResumeIds("'"+resumeParam.getUuid()+"'");
  30. handleParam.setCorpId(SessionUtils.getCorpId(request.getSession()));
  31. int count = 0;
  32.  
  33. count = resumeHandleService.checkEnshrine(handleParam);
  34.  
  35. ResumeBasicInformationResp rbIfonResp = new ResumeBasicInformationResp();
  36. //查询当前登录用户的简历基本信息
  37. List<ResumeBasicInformationResp> resumeBasicList = resumeBasicInformationService.getResumeBasic(resumeParam);
  38. if(resumeBasicList.size()>0){
  39. rbIfonResp = resumeBasicList.get(0);
  40. //性别
  41. if("1".equals(rbIfonResp.getGender())){
  42. rbIfonResp.setGender("男");
  43. }else{
  44. rbIfonResp.setGender("女");
  45. }
  46. //婚姻状况
  47. if("1".equals(rbIfonResp.getMaritalStatus())){
  48. rbIfonResp.setGender("已婚");
  49. }else if("2".equals(rbIfonResp.getMaritalStatus())){
  50. rbIfonResp.setGender("未婚");
  51. }else{
  52. rbIfonResp.setGender("保密");
  53. }
  54.  
  55. //姓名、邮箱、电话是否可见
  56. if(count==0){ //没有将该简历放入简历库、没有投递该企业,若简历设置了不可见,则企业看不到
  57. if("1".equals(rbIfonResp.getNamePrivacy()) && rbIfonResp.getName()!=""){
  58. String name = rbIfonResp.getName().substring(0, 1)+" *";
  59. rbIfonResp.setName(name);
  60. }
  61.  
  62. if("1".equals(rbIfonResp.getEmailPrivacy()) && rbIfonResp.getEmail()!=""){
  63. int pos = rbIfonResp.getEmail().indexOf("@");
  64. String result = rbIfonResp.getEmail().substring(pos, rbIfonResp.getEmail().length());
  65. rbIfonResp.setEmail("****"+result);
  66. }
  67.  
  68. if("1".equals(rbIfonResp.getTelPrivacy()) && rbIfonResp.getTelephone()!=""){
  69. String telephone = rbIfonResp.getTelephone().substring(0, 3) + "****" + rbIfonResp.getTelephone().substring(7, 11) ;
  70. rbIfonResp.setTelephone(telephone);
  71. }
  72. }
  73. }
  74.  
  75. dataMap.put("rbIfonResp", rbIfonResp);
  76. //dataMap.put("resumeList", resumeBasicList);
  77.  
  78. //工作经历信息
  79. List<WorkExperienceResp> workExperienceList=workExperienceService.selectWorkExperience(workExperienceParam);
  80. dataMap.put("workExperienceList", workExperienceList);
  81. //教育经历信息
  82. List<EducationBackgroundResp> educationList=educationService.selectEducation(educationParam);
  83. dataMap.put("educationList", educationList);
  84. //技能评价信息
  85. List<SkillEvaluationResp> skillList=skillService.selectSkillEvaluation(skillParam);
  86. dataMap.put("skillList", skillList);
  87. //项目经验信息
  88. List<ProjectExperienceResp> projectList=projectService.selectProject(projectParam);
  89. dataMap.put("projectList", projectList);
  90. //语言能力信息
  91. List<LanguageabilityResp> languageList=languageService.selectLanguage(languageParam);
  92. dataMap.put("languageList", languageList);
  93. //培训经历
  94. List<TrainingExperienceResp> trainList=trainingService.selectTrainingExperience(trainParam);
  95. dataMap.put("trainList", trainList);
  96.  
  97. //作品展示
  98. WorkAttachmentParam waParam = new WorkAttachmentParam();
  99. waParam.setResumeId(resumeId);
  100. waParam.setWorkType("1"); // 类型:1-作品;2-附件
  101. List<WorkAttachmentResp> workAttachemntList = workAttachmentService.selectWorkAttachment(waParam);
  102.  
  103. //作品路径
  104. String resourceUrl = "";
  105. //项目路径
  106. String url = FileManagerUtils.getFilePath(null) + "/";
  107.  
  108. if(workAttachemntList!=null && workAttachemntList.size()>0){
  109. for(int i=0;i<workAttachemntList.size();i++){
  110. resourceUrl = url + workAttachemntList.get(i).getResourceUrl();
  111.  
  112. //先将网络图片下载到本地,再将本地图片转换成BASE64字符串
  113. workAttachemntList.get(i).setResourceUrl(getImageString(resourceUrl));
  114. workAttachemntList.get(i).setIndex(i);
  115.  
  116. }
  117. }
  118. dataMap.put("workAttachemntList", workAttachemntList);
  119.  
  120. ExportDoc exportDoc = new ExportDoc();
  121. exportDoc.create(dataMap,response);
  122.  
  123. }

2、将本地、网络图片转换成BASE64字符串

  1. /**
  2. *
  3. * @Title: getImageString
  4. * @Description: 将本地、网络图片转换成BASE64字符串
  5. * @param @param filename
  6. * @param @return
  7. * @param @throws IOException
  8. * @return String
  9. * @throws
  10. */
  11. public static String getImageString(String imageUrl) throws IOException {
  12.  
  13. //InputStream in = null;
  14.  
  15. InputStream dis = null;
  16. byte[] data = null;
  17.  
  18. try {
  19.  
  20. //方法一、将网络图片导入wolrd
  21. URL url = new URL(imageUrl);
  22. //打开网络输入流
  23. URLConnection conn = url.openConnection();
  24.  
  25. //设置超时间为3秒
  26. //conn.setConnectTimeout(3*1000);
  27. //防止屏蔽程序抓取而返回403错误
  28. //conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  29.  
  30. //得到输入流
  31. InputStream inputStream = conn.getInputStream();
  32. //获取自己数组
  33. data = readInputStream(inputStream);
  34.  
  35. /*
  36. //方法二、将本地图片导入wolrd,打开本地输入流
  37. in = new FileInputStream(imageUrl);
  38. data = new byte[in.available()];
  39. in.read(data);
  40. in.close();
  41. */
  42.  
  43. } catch (IOException e) {
  44. throw e;
  45. } finally {
  46. if (dis != null)
  47. dis.close();
  48. }
  49.  
  50. BASE64Encoder encoder = new BASE64Encoder();
  51.  
  52. return data != null ? encoder.encode(data) : "";
  53.  
  54. }
  1. /**
  2. *
  3. * @Title: readInputStream
  4. * @Description: 将网络图片流转换成数组
  5. * @param @param inputStream
  6. * @param @return
  7. * @param @throws IOException
  8. * @return byte[]
  9. * @throws
  10. */
  11. public static byte[] readInputStream(InputStream inputStream) throws IOException {
  12. byte[] buffer = new byte[1024];
  13. int len = 0;
  14. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  15. while((len = inputStream.read(buffer)) != -1) {
  16. bos.write(buffer, 0, len);
  17. }
  18. bos.close();
  19. return bos.toByteArray();
  20. }
  21.  
  22. /**
  23. * @Title: downloadImg
  24. * @Description: 网络图片下載到本地
  25. * @param @param imgUrl:网络图片,http开头
  26. * @param @return 返回下载到本地的图片路径
  27. * @param @throws Exception
  28. * @return String
  29. * @throws
  30. */
  31. public String downloadImg(String imgUrl) throws Exception{
  32.  
  33. // 构造URL
  34. URL url = new URL(imgUrl);
  35. // 打开连接
  36. URLConnection con = url.openConnection();
  37. //设置请求超时为5s
  38. con.setConnectTimeout(5*1000);
  39. // 输入流
  40. InputStream is = con.getInputStream();
  41.  
  42. // 1K的数据缓冲
  43. byte[] bs = new byte[1024];
  44. // 读取到的数据长度
  45. int len;
  46.  
  47. //创建下载路径
  48. String savePath = "D://download//";
  49. String filename = UUIDUtil.getUUID()+".jpg";
  50. String returnUrl = savePath+filename;
  51.  
  52. File sf = new File(savePath);
  53. if(!sf.exists()){
  54. sf.mkdirs();
  55. }
  56.  
  57. // 输出的文件流
  58. OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
  59. // 开始读取
  60. while ((len = is.read(bs)) != -1) {
  61. os.write(bs, 0, len);
  62. }
  63. // 完毕,关闭所有链接
  64. os.flush();
  65. os.close();
  66. is.close();
  67.  
  68. return returnUrl;
  69. }

3、导出模板

  1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.BufferedWriter;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.io.OutputStreamWriter;
  10. import java.io.Writer;
  11. import java.util.Map;
  12. import javax.servlet.http.HttpServletResponse;
  13. import freemarker.template.Configuration;
  14. import freemarker.template.Template;
  15.  
  16. /**
  17. *
  18. * @ClassName:ExportDoc
  19. * @Description: 导出简历模板
  20. * @author:
  21. * @date:2015-6-25 下午3:52:12
  22. * @version 1.0
  23. */
  24. public class ExportDoc {
  25.  
  26. private Configuration configuration = null;
  27.  
  28. public ExportDoc() {
  29. configuration = new Configuration();
  30. configuration.setDefaultEncoding("UTF-8");
  31. }
  32.  
  33. /**
  34. *
  35. * @Title: create
  36. * @Description: 注意dataMap里存放的数据Key值要与模板中的参数相对应
  37. * @param @param dataMap
  38. * @param @param response
  39. * @param @throws Exception
  40. * @return void
  41. * @throws
  42. */
  43. public void create(Map<String, Object> dataMap, HttpServletResponse response)
  44. throws Exception {
  45.  
  46. // 模板放在com.canyou.template包下面,通过classpath装载
  47. configuration.setClassForTemplateLoading(this.getClass(), "/com/***/ftl"); //自己在项目中放入模板位置
  48. Template template = configuration.getTemplate("resume.ftl");// 设置要装载的模板
  49.  
  50. String fileName = String.valueOf(Math.random()*10000);
  51. File outFile = new File(fileName.replace(".", "")+".doc");
  52.  
  53. if (!outFile.exists()) {
  54. outFile.createNewFile();
  55. }
  56.  
  57. Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
  58. template.process(dataMap, out);
  59. out.close();
  60.  
  61. //导出时有界面,可选择下载路径
  62. response.addHeader("Content-Disposition", "attachment;filename=" + new String(outFile.getName().getBytes("utf-8"), "utf-8"));
  63. response.setContentType("application/msword");
  64.  
  65. OutputStream out1 = null;
  66. InputStream in = null;
  67.  
  68. try {
  69. in = new FileInputStream(outFile);
  70.  
  71. out1 = response.getOutputStream();
  72. BufferedInputStream bis = new BufferedInputStream(in);
  73. BufferedOutputStream bos = new BufferedOutputStream(out1);
  74.  
  75. byte[] buff = new byte[20480];
  76. int bytesRead;
  77. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  78. bos.write(buff, 0, bytesRead);
  79. }
  80. bis.close();
  81. bos.flush();
  82. bos.close();
  83.  
  84. } catch (Exception e) {
  85. e.printStackTrace();
  86. }
  87.  
  88. finally {
  89. if (out1 != null)
  90. out1.close();
  91. if (in != null)
  92. in.close();
  93. }
  94.  
  95. }
  96.  
  97. }

Java Web用Freemarker生成带图片的Word文档的更多相关文章

  1. freemarker导出带图片的word文档

    最近做一个关于文档导出功能, 顺便学习了下freemarker,做了个关于导出带图片的word文档,模板并没有写全,只是验证代码的正确性 这只是做一个小功能,故只做了后台代码关于导出的代码,并未与前台 ...

  2. java 在MySQL中存储文件,读取文件(包括图片,word文档,excel表格,ppt,zip文件等)

    转自:https://blog.csdn.net/u014475796/article/details/49893261 在设计到数据库的开发中,难免要将图片或文档文件(如word)插入到数据库中的情 ...

  3. 解决图片插入word文档后清晰度降低的问题

    解决图片插入word文档后清晰度降低的问题 在默认情况下,word程序会自动压缩插入word文档中的图片以减小整个word文档的.当我们需要插入word文档中的图片保持原始清晰度时,可以通过设置wor ...

  4. 基于springboot的freemarker创建指定格式的word文档

    在web或其他应用中,经常我们需要导出或者预览word文档,比较实际的例子有招聘网站上预览或者导出个人简历,使用POI导出excel会非常的方便,但是如果想导出word,由于其格式控制非常复杂,故而使 ...

  5. JAVA:借用OpenOffice将上传的Word文档转换成Html格式

    为什么会想起来将上传的word文档转换成html格式呢?设想,如果一个系统需要发布在页面的文章都是来自word文档,一般会执行下面的流程:使用word打开文档,Ctrl+A,进入发布文章页面,Ctrl ...

  6. Java 添加条码、二维码到Word文档

    本文介绍如何在Word文档中添加条码.二维码.可在文档正文段落中添加,也可在页眉页脚中添加.下面将通过Java代码示例介绍如何实现. 使用工具:Free Spire.Office for Java(免 ...

  7. Java文件操作系列[3]——使用jacob操作word文档

    Java对word文档的操作需要通过第三方组件实现,例如jacob.iText.POI和java2word等.jacob组件的功能最强大,可以操作word,Excel等格式的文件.该组件调用的的是操作 ...

  8. Java 添加、读取、修改、删除Word文档属性

    Word文档属性包括常规.摘要.统计.内容.自定义等,其中摘要包括标题.主题.作者.经理.单位.类别.关键词.备注等项目,通过设置这些摘要信息或自定义属性可方便对文档的管理.本文中将主要介绍对文档摘要 ...

  9. java通过freemarker导出包含富文本图片的word文档

    废话不多说,进入正题! 本文重点在于:对富文本图片的导出(基础的freemarker+word模板导出这里不做详细解说哈) 参考文章:http://www.cnblogs.com/liaofeifig ...

随机推荐

  1. Linux命令应用大词典-第21章 LVM和RAID管理

    21.1 pvcreate:创建物理卷 21.2 pvscan:列出找到的物理卷 21.3 pvdisplay:显示物理卷的相关属性 21.4 vgcreate:创建卷组 21.5 vgscan:查找 ...

  2. Linux 文件的常识

    文件 文件的分类 文件 目录 链接 区分办法,ls -la 查看 十个标志符中的第一个 如:drwxrwxr-x. 2 normal normal 4096 8月 31 23:43 dir 目录是d ...

  3. Spring Cloud(十一):服务网关 Zuul(过滤器)【Finchley 版】

    Spring Cloud(十一):服务网关 Zuul(过滤器)[Finchley 版]  发表于 2018-04-23 |  更新于 2018-05-07 |  在上篇文章中我们了解了 Spring ...

  4. JavaScript 正则

    元字符 预定义类 边界 ^在中括号中时,匹配非hello的 str = 'hello world' str.match(/[^hello]/g) //[" ", "w&q ...

  5. Centos配置深度学习开发环境

    目录 1. 安装显卡驱动 2. 安装CUDA\CUDNN 3. 安装TensorFlow-gpu 测试 1. 安装显卡驱动 检测显卡驱动及型号 $ sudo rpm --import https:// ...

  6. 使用深度学习来破解 captcha 验证码(转)

    使用深度学习来破解 captcha 验证码 本项目会通过 Keras 搭建一个深度卷积神经网络来识别 captcha 验证码,建议使用显卡来运行该项目. 下面的可视化代码都是在 jupyter not ...

  7. HADOOP docker(八):hadoop本地库

    前言2. Native Hadoop Library3. 使用本地库4. 本地库组件5. 支持的平台6. 下载7. 编译8. 运行时观察9. 检查本地库10. 如果共享本地库 小伙伴还记得每次启动hd ...

  8. [leetcode-676-Implement Magic Dictionary]

    Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...

  9. logstash+elasticsearch 错误摘记

    [2017-09-17T06:00:22,511][WARN ][o.e.b.ElasticsearchUncaughtExceptionHandler] [] uncaught exception ...

  10. python学习笔记06:操作文件

    调用内置的open函数打开文件,传递两个参数:文件路径(绝对路径或相对路径),打开模式('r':读,'r+':读写,'w':写,'b':二进制): f = open('data.txt','w') f ...