一、需求描述
实现合同模板自动生成合同,再添加电子签名。如图:
二、实现步骤
使用java开源itext库对pdf进行操作,主要分为:
1 html模板+model数据,通过freemarker进行渲染,生成pdf1。
2 查找指定电子签名的位置,然后再在指定位置插入签名图片,生成最终pdf。
备注:模板使用的是html形式,电子签名格式使用的是Base64格式。
- 准备html合同模板
合同模板,在公众中获取。 - 添加java后端依赖
完整的依赖包,点击蓝字,在公众号中获取。 - html模板+model数据,生成pdf的工具类
注:
① FONT是黑体,每个window电脑基本上都有,目录都是一样的。FONT需要使用fontResolver.addFont(FONT…添加进去,不然可能汉字一偏空白。
② freeMarkDir是合同模板放置的位置,根据自己情况修改。
③ 使用的编码最好是"UTF-8",换一套环境后可能乱码。
public class JavaToPdfHtmlFreeMarker {
private final static Logger logger = LoggerFactory.getLogger(JavaToPdfHtmlFreeMarker.class);
private static final String FONT = "C:\\Windows\\Fonts\\simhei.ttf";
private static final String freeMarkDir = "D:\\app\\contractTemplate\\";
private static Configuration freemarkerCfg = null;
static {
freemarkerCfg =new Configuration();
//freemarker的模板目录
try {
freemarkerCfg.setDirectoryForTemplateLoading(new File(freeMarkDir));
freemarkerCfg.setEncoding(Locale.CHINA, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void createPdf1(String content,String dest) throws IOException, DocumentException, com.lowagie.text.DocumentException {
// String LOGO_PATH = "file:///C:/Users/86132/Desktop/";
ITextRenderer render = new ITextRenderer();
ITextFontResolver fontResolver = render.getFontResolver();
fontResolver.addFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 解析html生成pdf
render.setDocumentFromString(content);
//解决图片相对路径的问题
// render.getSharedContext().setBaseURL(LOGO_PATH);
render.layout();
render.createPDF(new FileOutputStream(dest));
}
/**
* freemarker渲染html
*/
public static String freeMarkerRender(Map<String, Object> data, String htmlTmp) {
Writer out = new StringWriter();
try {
// 获取模板,并设置编码方式
Template template = freemarkerCfg.getTemplate(htmlTmp,"UTF-8");
template.setEncoding("UTF-8");
// logger.info("template info --->" + template);
// 合并数据模型与模板
template.process(data, out); //将合并后的数据和模板写入到流中,这里使用的字符流
// logger.info("template info --->" + template);
// logger.info("out info --->" + out);
out.flush();
return out.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return null;
}
}
- 调用工具类生成pdf
// 模板名称
String HTML = "contract.html";
// 生成的pdf存放路径
String DEST = "D:\\app\\user_contract\\";
// 生成的pdf名称
String fileName = "合同D20210511SDNQB1.pdf"
public static void main(String[] args) throws IOException, DocumentException, InterruptedException {
Map<String,Object> data = new HashMap();
data.put("合同编号","D20210511SDNQB");
data.put("甲方姓名","小哈");
data.put<