需求说明
根据合同模板,将动态的合同标签,合同方以及合同签约时间等动态的生成pdf,供用户下载打印。
前期准备
安装 adobe acrobat dc
链接:https://pan.baidu.com/s/1t8wtckxn0ychjxzq8g6weq
提取码:j6b9
spring boot 集成
添加依赖
<dependency> <groupid>com.itextpdf</groupid> <artifactid>itextpdf</artifactid> <version>5.5.9</version> <scope>compile</scope> </dependency> <!--中文问题解决--> <dependency> <groupid>com.itextpdf</groupid> <artifactid>itext-asian</artifactid> <version>5.2.0</version> </dependency>
构建工具类
public class pdfutils { private static final logger log = loggerfactory.getlogger(pdfutils.class); /** * 根据pdf模板输出流 * @param templatefilename 模板文件名 * @param resultmap 包含文件字段名和值的map * @return 生成的文件字节流 */ public static bytearrayoutputstream createpdfstream(string templatefilename, map<string, string> resultmap){ bytearrayoutputstream ba = new bytearrayoutputstream(); pdfstamper stamp =null; pdfreader reader = null; try { reader = new pdfreader(templatefilename); stamp = new pdfstamper(reader, ba); //使用字体 basefont bf = basefont.createfont("stsongstd-light", "unigb-ucs2-h", basefont.not_embedded); /* 获取模版中的字段 */ acrofields form = stamp.getacrofields(); //填充表单 if (resultmap != null) { for (map.entry<string, string> entry : resultmap.entryset()) { form.setfieldproperty(entry.getkey(), "textfont", bf, null); form.setfield(entry.getkey(), entry.getvalue()!=null?entry.getvalue():""); } } //不能编辑 stamp.setformflattening(true); } catch (ioexception e) { log.error("文档构建i/o异常",e); } catch (documentexception e) { log.error("文档构建异常",e); } finally { if(stamp!=null){ try { stamp.close(); } catch (documentexception e) { log.error("流关闭错误",e); } catch (ioexception e) { log.error("流关闭错误",e); } } if(reader!=null){ reader.close(); } } return ba; } }
构建multipartfile
方便之后上传oss返回url
public uploadfilemodel createurl(string filepath, bytearrayoutputstream bytearrayoutputstream) throws urisyntaxexception { try{ byte[] pdfbytes = bytearrayoutputstream.tobytearray(); multipartfile multipartfile = new mockmultipartfile( "file", filepath, "application/pdf", pdfbytes ); return uploadfileutil.upload(multipartfile); } catch (exception e) { log.error("创建url时出错:" + e.getmessage()); } return null; }
编辑pdf模板
java代码设置对应form的key-value
pdf模板放在springboot 项目目录resources/static 目录下
public string createcontract(createcontractrequest request) { hashmap<string, string> map = new hashmap<>(); map.put("companyname",request.getcompanyname()); map.put("phone",request.getphone()); uploadfilemodel url = null; bytearrayoutputstream pdfstream = pdfutils.createpdfstream(userapplication.class.getresource("/").getpath() + "static/contract.pdf", map); try { url = createurl("合同.pdf", pdfstream); } catch (urisyntaxexception e) { throw new runtimeexception(e); } return url.geturl(); }
到此这篇关于springboot集成itextpdf实现根据模板动态生成pdf的文章就介绍到这了,更多相关springboot itextpdf生成pdf内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论