zoukankan      html  css  js  c++  java
  • 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);
            
        }
    View Code

         

         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();
            }
    
        }
        
    }
  • 相关阅读:
    枚举类型(C#)
    如何在Delphi中安装组件
    操作系统知识点总结
    Java内部类学习笔记
    计算机网络笔试面试常考考点
    电话号码分身问题
    最长下降/上升子序列问题
    LeetCode(162):Find Peak Element
    LeetCode(153):Find Minimum in Rotated Sorted Array
    LeetCode(75):Sort Colors
  • 原文地址:https://www.cnblogs.com/mingyue1818/p/4742706.html
Copyright © 2011-2022 走看看