Java Web用Freemarker生成帶圖片的Word文檔

 

步驟一:模板製做java

    用world2003作一個導出模板,若是有圖片則加入一張圖片佔位,將world另存爲xml,將xml中須要導出的內容用Freemarker標籤表示,最後另存爲.ftl結尾的模板:數組

 

步驟二:後臺代碼網絡

     一、獲取導出的數據:app

@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

     

     二、將本地、網絡圖片轉換成BASE64字符串dom

/**
     * 
     * @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 {
            
            //方法1、將網絡圖片導入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); 
            
            /*
            //方法2、將本地圖片導入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;
    }

      

        三、導出模板ide

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();
        }

    }
    
}
相關文章
相關標籤/搜索