java根据模板生成pdf文件(itextpdf)

更新时间:2023-07-31 06:06:38 阅读: 评论:0

java根据模板⽣成pdf⽂件(itextpdf)⾸先准备模板:
组名组呼1.⽤Adobe Acrobat DC软件打开你的pdf模板⽂件点击准备表单;
2.编辑表单的属性和格式
3.最后点击保存,然后把模板⽂件放到resources⽂件夹下
4.再l⽂件中引⼊iTextPdf的依赖
<!-- ⽣成pdf⽂件 -->
<dependency>
旅游规划
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
清明谚语</dependency>
<!-- 识别中⽂汉字 -->
<dependency>
关于改变的名言<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
5.创建⼀个⼯具类PdfUtils,⽤下⾯的⽅法来根据模板⽣成pdf⽂件 ,传⼊包含模板中所有表单属性的Map和模板⽂件的路径即可⽣成pdf⽂
/**
* 根据模板创建⽣成pdf
* @param map 模板中的表单数据 key-表单属性值;value-值
* @param templatePath 模板路径
* @return 返回⽣成的pdf⽂件路径
*/
public static String createPdfByTemplate(Map<String,Object> map,String templatePath) {
PdfReader reader;
ByteArrayOutputStream bos;
PdfStamper stamper;
/
/⽣成的pdf⽂件存放地址要确保⽂件夹的存在
String newPdfPath = "src/main/resources/static/temporary/"+(System.currentTimeMillis())+".pdf";
try {
//设置字体是必须要的,不然没法向模板pdf⾥写值
BaFont bfChine = ateFont("STSong-Light", "UniGB-UCS2-H", BaFont.NOT_EMBEDDED);            // 读取pdf模板
reader = new PdfReader(templatePath);
bos = new ByteArrayOutputStream();
燕窝什么时候吃
stamper = new PdfStamper(reader, bos);
//拿到pdf模板中的表单属性
AcroFields form = AcroFields();
//设置字体
10月26
form.addSubstitutionFont(bfChine);
美的成语java.util.Iterator<String> it = Fields().keySet().iterator();字谜大全及答案100个
//遍历表单属性,对每个属性赋值
while (it.hasNext()) {
String name = it.next().toString();
String value = (name)!=(name).toString():null;
System.out.println(name+"------"+value);
form.tField(name,value);
}
// 如果为fal那么⽣成的PDF⽂件还能编辑,⼀定要设为true
stamper.tFormFlattening(true);
stamper.clo();
Document doc = new Document();
File file = new File(newPdfPath);
PdfCopy copy = new PdfCopy(doc, new FileOutputStream(file));
doc.open();
PdfImportedPage importPage = ImportedPage(new ByteArray()), 1);
copy.addPage(importPage);
doc.clo();
} catch (IOException e) {
throw new BaException("⽣成电⼦协议失败,请联系管理员");
} catch (DocumentException e) {
throw new BaException("⽣成电⼦协议失败,请联系管理员");
}
return newPdfPath;
}
6.试例:
//⽣成电⼦协议
Map<String, Object> tAgreementApplyMap =ansBean2Map(tAgreementApplyElecDTO);
String tAgreementElecPath = atePdfByTemplate(tAgreementApplyMap,"src/main/resources/static/模板.pdf");
⽣成的⽂件如下:

本文发布于:2023-07-31 06:06:38,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/1124441.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:模板   表单   属性   确保
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图