freemarker作为PDF模板实现下载功能

freemarker 文件

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<title></title>
<style type="text/css">
body {
    font-family: SimSun;
    font-size: 12px;
}

table {
    border-collapse: collapse;
    border-spacing: 0;
}

td {
    
}

.table {
    margin-top: 0;
    margin-right: auto;
    margin-bottom: 80;
    margin-left: auto;
}

.table td {
    border: 1px solid #333333;
    border-collapse: collapse;
    padding: 7px;
}

.table1 {
    margin-top: 0;
    margin-right: auto;
    margin-left: auto;
}

.table1 td {
    border: 0px solid #333333;
    border-collapse: collapse;
    padding: 7px;
}

.odct_zhangpic {
    width: 160px;
    height: 160px;
    position: absolute;
    margin-top: -110px;
    clear: both;
    float: none;
    margin-left: 400px;
}
</style>
</head>

<body>
    <table width="96%" border="0" align="center" cellspacing="0">
        <tr>
            <td align="right">
                <img src="http://www.10000show.com/static/index/images/logo.png" width="124" height="62"></img>
                </td>
        </tr>
        <tr>
            <td height="90" align="center"><h2>订单详情</h2></td>
        </tr>
    </table>
   <table width="96%" border="0" align="center" cellspacing="0" cellpadding="0" class="table">
         <h2><strong>参展企业信息</strong></h2>
        <tr>
                        <td>公司名称</td>
                        <td>联系地址</td>
                        <td>公司电话</td>
                        <td>所属行业</td>
                        <td>公司网址</td>
                        <td>公司传真</td>
                    </tr>
                    <tr>
                        <td>${order.company?if_exists }</td>
                        <td>${order.com_addr?if_exists }</td>
                        <td>${order.telephone?if_exists }</td>
                        <td>${hangYe?if_exists}</td>
                        <td>${order.net_add?if_exists }</td>
                        <td> ${order.post_fax?if_exists }</td>
                    </tr>
    </table>
     <table width="96%" border="0" align="center" cellspacing="0" cellpadding="0" class="table">
     <h2><strong>联系人信息</strong></h2>
     
                    <tr>
                        <td>姓名</td>
                        <td>性别</td>
                        <td>手机</td>
                        <td>邮箱</td>
                        <td>职位</td>
                        <td>QQ</td>
                    </tr>
                    <tr>
                        <td>${order.contact_name?if_exists }</td>
                        <td>${sex?if_exists}</td>
                        <td>${order.contact_phone?if_exists }</td>
                        <td>${order.mail?if_exists }</td>
                        <td>${order.job?if_exists }</td>
                        <td>${order.qq?if_exists }</td>
                    </tr>
    </table>
    <table width="96%" border="0" align="center" cellspacing="0" cellpadding="0" class="table">
     <h2><strong>参展展品</strong></h2>
       <p>${exhiProduct?if_exists }</p>    
    </table>
    
    <table width="96%" border="0" align="center" cellspacing="0" cellpadding="0" class="table">
    <h2><strong>展位信息</strong></h2>
    <#if order.exhi_type ??>
                <tr>
                    <td>展位类型</td>
                    <td>展位购买数量</td>
                    <td>展位信息</td>
                    <td>展位配置</td>
                    <td>展位意向</td>
                </tr>
                <tr>
                    <td>${order.exhi_type?if_exists }</td>
                    <td>
                    <#if order.exhi_num==0>
                      <span>1</span>
                      <#else>
                        <span>${order.exhi_num?if_exists }</span>
                    </#if>
                    </td>
                    <td>
                    <#if zhanweis??>
                       <#list zhanweis as zhanwei> 
                          
                              <span>展位编号:</span>
                              <span>${zhanwei.bianHao?if_exists }</span>
                              <span>展位面积:</span>
                              <span>${zhanwei.mianJi?if_exists }</span>
                              <span>开口类型:</span>
                              <span>${kaiKou?if_exists}</span>
                          
                       </#list>
                    
                    <#else>
                         
                                <span>展位面积:</span>
                                <span>${order.zhan_wei_total_area?if_exists }</span>
                                <span>开口类型:</span>
                                <span>${kaiKouType?if_exists}</span>
                        
                    </#if>
                    </td>
                    <td>${zhanWeiPeiZhi?if_exists }</td>
                    <td>${order.exhi_yi_xiang?if_exists }</td>
                </tr>
                   <#else>
                    <span></span>
                </#if>
    </table>
    
    <#if order.bill_money ??>
       <#else>
       <table width="96%" border="0" align="center" cellspacing="0" cellpadding="0" class="table">
       <h2><strong>发票信息</strong></h2>
        <p>发票类型:    不开发票</p>
      </table>
    </#if>
    <#if order.bill_title ??>
        <table width="96%" border="0" align="center" cellspacing="0" cellpadding="0" class="table">
           <h2><strong>发票信息</strong></h2>
           <tr>
                <td>发票金额</td>
                <td>发票明细</td>
                <td>发票抬头</td>
                <td>收件人</td>
                <td>邮寄地址</td>
                <td>邮政编码</td>
                <td>手机</td>
                <td>固定电话</td>
            </tr>
            <tr>
                <td>${order.bill_money?if_exists }元</td>
                <td>${order.bill_detail?if_exists }</td>
                <td>${order.bill_title?if_exists }</td>
                <td>${order.post_man?if_exists }</td>
                <td>${order.province?if_exists}${order.city?if_exists}${order.post_address?if_exists }</td>
                <td>${order.post_code?if_exists }</td>
                <td>${order.phone?if_exists }</td>
                <td>${order.fixed_phone?if_exists }</td>
            </tr>
        </table>
    </#if>
    
    <table width="96%" border="0" align="center" cellspacing="0" cellpadding="0" class="table">
    <h2><strong>支付方式</strong></h2>
     <p>${tradeType?if_exists }</p>
    </table>
    
    <table width="96%" border="0" align="center" cellspacing="0" cellpadding="0" class="table">
    <h2><strong>支付额度</strong></h2>
    <p>${payEdu?if_exists}</p>
    </table>
    
    <table width="96%" border="0" align="center" cellspacing="0" cellpadding="0" class="table">
    <h2><strong>积分</strong></h2>
    <span>使用积分:</span>
    <span>
    <#if order.ji_fen ??>
    <span>${order.ji_fen?if_exists }</span>
    <#else>
    <span>0</span>
    </#if>
    </span>
    
    <span>已抵扣金额</span>
    <span>
    <#if newJiFen ??>
       <span>${newJiFen?if_exists }</span>
       <#else>
        <span>0</span>
    </#if>
    </span>
    </table>
    
    <table width="96%" border="0" align="center" cellspacing="0" cellpadding="0" class="table">
    <h2><strong>首单优惠金额</strong></h2>
    <p>${order.shou_dan_mian?if_exists }</p>
    </table>
    
    <table width="96%" border="0" align="center" cellspacing="0" cellpadding="0" class="table">
    <h2><strong>参展人员信息</strong></h2>
    <#if linkMans ??>
        <tr>
            <td>姓名</td>
            <td>性别</td>
            <td>手机</td>
            <td>职位</td>
            <td>邮箱</td>
            <td>护照</td>
            <td>护照有效期</td>
            <td>随团</td>
        </tr>
        <#list linkMans as linkMan>
           <tr>
                <td>${linkMan.name }</td>
                 <td>    
                 <#if linkMan.sex ??>
                          <#if linkMan.sex=='1'>
                              <span></span>
                               <#else>
                               <span></span>
                           </#if>
                    <#else>
                </#if>
                    </td>
                    <td>${linkMan.mobile?if_exists }</td>
                    <td>${linkMan.position?if_exists }</td>
                    <td>${linkMan.email?if_exists}</td>
                    <td>${linkMan.passportNo?if_exists }</td>
                    <td>
                    <#if linkMan.passportExpiry ??>
                    ${linkMan.passportExpiry?string("yyyy-MM-dd")}
                     <#else>
                    
                    </#if>
                    </td>
                    <td>随团</td>
                </tr>
        </#list>
        <#else>
        <span></span>
    </#if>
    
    </table>
    
    <table width="96%" border="0" align="center" cellspacing="0" cellpadding="0" class="table">
     <h2><strong>商品信息</strong></h2>
               <tr>
                   <td>编号</td>
                    <td>名称</td>
                    <td>类型</td>
                    <td>时间</td>
                    <td>地点</td>
                    <td>展馆</td>
                </tr>
                <tr>
                      <td>${order.bian_hao?if_exists }</td>
                         <td>
                           <p>${order.ti_mu?if_exists }</p>
                     </td>
                         <td> 
                          ${productType?if_exists }
                      </td>
                         <td>
                             <#if order.ju_ban_time ??>
                                    ${order.ju_ban_time?string("yyyy-MM-dd")}
                               <#else>
                               
                             </#if>
                         </td>
                         <td>${order.address?if_exists }</td>
                         <td>
                        ${order.ming_cheng?if_exists }
                      </td>
                </tr>
    </table>
    <table width="96%" border="0" align="center" cellspacing="0" cellpadding="0" class="table">
    <h2><strong>费用结算信息</strong></h2>
            <tr>
                   <td width="14%">名称</td>
                   <td width="43%">单价</td>
                   <td width="9%">数量</td>
                   <td width="12%">小计</td>
           </tr>
           <tr>
                 <td>参展费</td>
                 <td>${order.exhi_fee?if_exists }元</td>
                 <td>1</td>
                 <td>${order.exhi_fee?if_exists }</td>
            </tr>
            <tr>
                 <td>注册费</td>
                 <td> 
                 <#if order.zhu_ce_fee ??>
                      <span>¥</span>${order.zhu_ce_fee?if_exists } /企业
                    <#else>
                    <span>¥0 /企业</span>
                 </#if>
                 </td>
                 <td>1</td>
                 <td>
                    <#if order.zhu_ce_fee ??>
                         <span>¥</span>${order.zhu_ce_fee?if_exists }
                       <#else>
                       <span>¥0</span>
                    </#if>
                 </td>
            </tr>
             <tr>
                 <td>服务费</td>
                 <td>
                 <#if order.fu_wu_fei ??>
                    <span>¥</span>${order.fu_wu_fei?if_exists } /企业
                    <#else>
                      <span>¥0 /企业</span>
                 </#if>
                  </td>
                 <td>1</td>
                 <td>
                   <#if order.fu_wu_fei ??>
                         <span>¥</span>${order.fu_wu_fei?if_exists }
                      <#else>
                      <span>¥0</span>
                   </#if>
                 </td>
            </tr>
            
             <tr>
                 <td>开口费</td>
                 <td>
                 ${order.kai_kou_fee?if_exists }/企业
                  </td>
                 <td>1</td>
                 <td>
                   ${order.kai_kou_fee?if_exists }
                 </td>
            </tr>
            
            <#if order.dan_jian_cha_count gt 0>
                <tr>
                     <td>单间差费 </td>
                     <td>${order.dan_jian_cha?if_exists }/人</td>
                     <td>${order.dan_jian_cha_count?if_exists }</td>
                     <td >${order.single_room_fee?if_exists }</td>
                </tr>
            </#if>
           
         
          <#if peopleCount gt 0>
              <tr>
                 <td>参展人员费</td>
                 <td> 
                 <span>¥</span>${order.zhan_wei_ren_yuan_fei?if_exists }/人 
                 </td>
                 <td>${order.people_count?if_exists}</td>
                 <td>${order.people_fee?if_exists }</td>
            </tr>
          </#if>
         
          
          <#if order.visa_fee !=0 >
             <#list visaInfo.visaInfos as v>
                 <#if v.type=='shangWu'>
                    <tr>
                             <td>商务签证 </td>
                             <td><span>¥</span>${v.price?if_exists }/人</td>
                             <td>${v.num?if_exists }</td>
                             <td>${v.price}</td>
                      </tr>
                 </#if>
                 
                 <#if v.type=='lvYou'>
                     <tr>
                             <td>旅游签证 </td>
                             <td><span>¥</span>${v.price?if_exists }/人</td>
                             <td>${v.num ?if_exists}</td>
                             <td>${v.price}</td>
                       </tr>
                 </#if>
             </#list>
          </#if>
         
    </table>
</body>
</html>

后台java 代码

@RequestMapping("/createOrderPdf")
    public void createOrderPdf(String orderId, Model model, HttpServletResponse response, HttpServletRequest request) {
        String fileName = null;
        try {
            Template template = null;
            Configuration freeMarkerConfig = null;
            Map<String, Object> map = new HashMap<String, Object>();
            freeMarkerConfig = new Configuration();
            freeMarkerConfig.setDirectoryForTemplateLoading(new File(SendMailUtil.getFilePath()));

            // 获取模板
            template = freeMarkerConfig.getTemplate(SendMailUtil.getFileName("mailtemplate/orderPdf.ftl"), new Locale("Zh_cn"), "UTF-8");
            OrderMain orderMain = orderMainService.get(orderId);
            Map<String, Object> orderDetails = orderMainService.getOrderCanZhanDetails(orderMain);
            if (orderDetails != null) {
                for (String key : orderDetails.keySet()) {// 遍历获取行业
                    System.out.println("key" + key + "value" + orderDetails.get(key));
                    if ("hang_ye".equals(key)) {
                        String hangYe = DictUtils.getDictLabel(orderDetails.get(key).toString(), "hang_ye", "");
                        map.put("hangYe", hangYe);// 所属行业
                    } else if ("sex".equals(key)) {
                        String sex = DictUtils.getDictLabelss(orderDetails.get(key).toString(), "sex", "");
                        map.put("sex", sex);// 性别
                    } else if ("exhi_product".equals(key)) {
                        String exhiProduct = orderDetails.get(key).toString();
                        exhiProduct = PDFUtil.getData(exhiProduct, 50);
                        map.put("exhiProduct", exhiProduct);// 参展展品
                    } else if ("kai_kou_type".equals(key)) {
                        String kaiKouType = DictUtils.getDictLabelss(orderDetails.get(key).toString(), "kaikoutype", "");
                        map.put("kaiKouType", kaiKouType);// 开口类型
                    } else if ("zhan_wei_pei_zhi".equals(key)) {
                        String zhanWeiPeiZhi = orderDetails.get(key).toString();
                        zhanWeiPeiZhi = PDFUtil.getData(zhanWeiPeiZhi, 18);
                        map.put("zhanWeiPeiZhi", zhanWeiPeiZhi);// 展览配置
                    } else if ("trade_type".equals(key)) {
                        String tradeType = DictUtils.getDictLabelss(orderDetails.get(key).toString(), "trade_type", "");// 支付方式
                        map.put("tradeType", tradeType);
                    } else if ("pay_edu".equals(key)) {
                        String payEdu = DictUtils.getDictLabelss(orderDetails.get(key).toString(), "pay_edu", "");// 支付额度
                        map.put("payEdu", payEdu);
                    } else if ("ji_fen".equals(key)) {// 用户积分
                        String jiFen = orderDetails.get(key).toString();
                        if (jiFen != null && !"".equals(jiFen)) {
                            int newJiFen = Integer.parseInt(jiFen);
                            if (newJiFen > 0) {
                                newJiFen = newJiFen / 100;
                                map.put("newJiFen", newJiFen);
                            } else {
                                map.put("newJiFen", null);
                            }
                        } else {
                            map.put("newJiFen", null);
                        }
                    } else if ("product_type".equals(key)) {
                        String productType = DictUtils.getDictLabelss(orderDetails.get(key).toString(), "product_type", "");// 类型
                        map.put("productType", productType);
                    } else if ("people_count".equals(key)) {// 参展人员
                        String peopleCount = orderDetails.get(key).toString();
                        map.put("peopleCount", Integer.parseInt(peopleCount));

                    }

                }
            }
            String ids = (String) orderDetails.get("wx_linkman_ids");
            if (StringUtils.isNotBlank(ids)) {
                List<LinkMan> linkMans = linkManService.findByIds(ids);// 参展人员信息
                map.put("linkMans", linkMans);
            }
            // 获取展位编号
            ExhiMain exhiMain = new ExhiMain();
            String exhiNum = (String) orderDetails.get("zhan_wei_bian_hao"); // 获取展位编号
            if (StringUtils.isNotBlank(exhiNum)) {
                ZhanWeis zhanWeis = GsonUtils.getGson().fromJson(exhiNum, ZhanWeis.class);
                exhiMain.setZhanWeis(zhanWeis);
            }
            String visaString = (String) orderDetails.get("visa_info");
            VisitOrder visitOrder = new VisitOrder();
            if (StringUtils.isNotBlank(visaString) && !"0".equals(visaString)) {
                VisaInfos visaInfo = GsonUtils.getGson().fromJson(visaString, VisaInfos.class);
                visitOrder.setVisaInfos(visaInfo);
                map.put("visaInfo", visaInfo);
            }
            map.put("order", orderDetails);
            map.put("exhiMain", exhiMain);

            ZhanWeis newZhanWeis = exhiMain.getZhanWeis();
            if (newZhanWeis != null) {
                List<ZhanWei> zhanweis = newZhanWeis.getZhanweis();
                map.put("zhanweis", zhanweis);
                if (zhanweis != null && zhanweis.size() > 0) {// 遍历获取开口费
                    for (ZhanWei zw : zhanweis) {
                        String kaiKou = DictUtils.getDictLabel(zw.getKaiKou(), "kaikoutype", "");
                        map.put("kaiKou", kaiKou);
                    }
                }
            } else {
                map.put("zhanweis", null);
            }
            Date date = new Date();
            String stringDate = DateUtils.formatDate(date, "yyyy-MM-dd_HH_mm_ss");
            fileName = stringDate + ".pdf"; // 生成pdf文件保存路径
            // 模板内容转换为string
            String htmlStr = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode(fileName));
            PdfGenerator.generate(htmlStr, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

输出到PDF文件方法

/** 
     * Output a pdf to the specified outputstream 
     *  
     * @param htmlStr the htmlstr 
     * @param out the specified outputstream 
     * @throws Exception 
     */  
    public static void generate(String htmlStr, OutputStream out)  
            throws Exception {  
        
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();  
        Document doc = builder.parse(new ByteArrayInputStream(htmlStr.getBytes("utf-8")));  
        ITextRenderer renderer = new ITextRenderer();  
        renderer.setDocument(doc, null); 
        
        //中文问题,同时body里面也要设置,windows环境
        String simsunPath=ServletContextFactory.getServletContext().getRealPath("/WEB-INF/classes/fonts/simsun.ttc");
        renderer.getFontResolver().addFont(simsunPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//        renderer.getFontResolver().addFont("C:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        
        //中文问题,同时body里面也要设置,liunx环境
        // renderer.getFontResolver().addFont("/usr/share/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        // 解决图片的相对路径问题     
       // renderer.getSharedContext().setBaseURL("file:/D:/index/");
                  
        renderer.layout();  
        renderer.createPDF(out);  
        out.close();  
    }  
原文地址:https://www.cnblogs.com/SHMILYHP/p/5458995.html