如题,前端页面不是定死的,需要动态生成.ftl模板以导出pdf,求解如何生成
尝试过根据url获取html代码转模板,由于前端是vue写的,有代理,我没有将html代码解析出来,对前端不太了解,有没有人给我解惑一下
如题,前端页面不是定死的,需要动态生成.ftl模板以导出pdf,求解如何生成
尝试过根据url获取html代码转模板,由于前端是vue写的,有代理,我没有将html代码解析出来,对前端不太了解,有没有人给我解惑一下
这样来创建:
根据自己的需求创建一个Freemarker模板,后缀为.ftl,我这里在WEB-INF下创建了一个文件夹用于存放Freemarker模板
Template1.ftl部分代码
<table id="tableid" class="table-condensed layui-table table-hover" data-toggle="table" style="font-size: 12px;">
省略了非关键代码
<thead>
<tr>
<th>商品名称</th> <th>商品编号</th><th>规格</th>
<th>单位</th><th>数量</th><th>单价</th>
</tr>
</thead> <tbody>
<#list list as stu>
<tr>
<th>${stu.designation}</th>
<th>${stu.serialNumber}</th>
<th>${stu.specification}</th>
<th>${stu.unit}</th>
<th>${stu.quantity}</th>
<th>${stu.unitPrice}</th>
<th>${stu.grossAmount}</th>
</tr>
</#list></tbody>
</table>
<td style="font-size:12px;text-align: left;font-family: Arial,'微软雅黑','宋体';line-height: 200%;" class="borderRNone" width="80"> <span>其他费用(元):</span> </td>
<td width="100">
<span style="color:red">¥</span><span id="spanFaReceAmt" style="font-size:12px;color:red" class="money">${info.restExpenses}</span>
</td>
</tr>
Servlet代码
从上面代码可以看出首先创建一个Configuration对象,设置模板文件的格式,再加载模板文件从而创建一个模板对象,其中将需要传过去的数据装进map中,从而生成需要的静态页面。
public void testFreeMarker(HttpServletRequest request, HttpServletResponse response) throws IOException, TemplateException{
//创建一个模板文件
//创建一个Configuration对象
Configuration configuration = new Configuration(Configuration.getVersion());
String file = request.getServletContext().getRealPath("WEB-INF/freemarkertemplate");
//设置模板文件保存的目录
configuration.setDirectoryForTemplateLoading(new File(file));
//设置模板文件的编码格式
configuration.setDefaultEncoding("UTF-8");
//加载一个模板文件,创建一个模板对象
String html = request.getServletContext().getRealPath("promotion");
File htmlFile = new File(html,"test.html");
System.out.println(htmlFile);
Template template = configuration.getTemplate("temp2.ftl");
//创建一个数据集可以是pojo,也可以是map,一般使用map
Map<String, Object> maps=new HashMap<String, Object>();
//将项目名称存进map中
maps.put("ctv", request.getContextPath());
List<CommodityList> list = null;
//获取id
int commodityStockOrderID = Integer.parseInt(request.getParameter("commodityStockOrderID")) ; StockCommodityBean StockCommodity = new StockCommodityBean();
// 调用servic层的方法查询出需要的数据
StockCommodity= dao.selectDetails(commodityStockOrderID);
//获取到list集合
list = StockCommodity.getCommList();
//将list保存进去
maps.put("list", list);
maps.put("info",StockCommodity);
//生成静态页面
template.process(maps, new FileWriter(htmlFile));
//关闭流
//out.close();
}