1.编辑模板
1.使用Adobe Acrobat 9 Pro软件编辑模板。
2.使用word设计模板并转换成pdf,使用Adobe Acrobat 9 Pro导入pdf文件,点击“表单”—>“添加或编辑域”。域的名称要记住,名称代表要插入的字段。
2.导入pom依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<!--字体集-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
3.server层代码
@Service
@Slf4j
public class PdfService {
public void generateTempPDF(HttpServletResponse response, FieldVo fieldVo) throws Exception {
PdfReader reader = null;
PdfStamper ps = null;
OutputStream fos = null;
ByteArrayOutputStream bos = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
String fileName = "E:\\时间证书下载(2).pdf";
//模板绝对路径--服务器
// String fileName = "/app/file/pdf/KDDLR_Receipt_Template.pdf";
reader = new PdfReader(fileName);
bos = new ByteArrayOutputStream();
ps = new PdfStamper(reader, bos);
// 使用中文字体(具体填入模板的字体在Adobe Acrobat软件中可以设置)
BaseFont bf = BaseFont.createFont("/fonts/STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
fontList.add(bf);
AcroFields fields = ps.getAcroFields();
fields.setSubstitutionFonts(fontList);
fillData(fields, data(fieldVo)); //填充模板
//必须要调用这个,否则文档不会生成的
ps.setFormFlattening(true);
if(ps != null){
ps.close();
}
//生成pdf路径存放的路径
fos = response.getOutputStream();
fos.write(bos.toByteArray());
}catch (Exception e){
e.printStackTrace();
log.error("异常:{",e.getMessage()+e.getCause()+"}");
}finally {
if(fos!=null){
fos.flush();
fos.close();
}
if (bos != null){
bos.close();
}
if(reader != null){
reader.close();
}
}
}
/**
* 填充模板中的数据
*/
public void fillData(AcroFields fields, Map<String, String> data) {
try {
for (String key : data.keySet()) {
String value = data.get(key);
// 为字段赋值,注意字段名称是区分大小写的
fields.setField(key, value);
}
} catch (Exception e) {
e.printStackTrace();
log.error("异常:{",e.getMessage()+e.getCause()+"}");
}
}
/**
* 填充数据源
* 其中data存放的key值与pdf模板中的文本域值相对应
*/
public Map<String, String> data(FieldVo fieldVo){
// 构造数据 , key要与模板中的别名一一对应
Map<String, String> paramters = new HashMap();
paramters.put("name",fieldVo.getName());
paramters.put("sex",fieldVo.getSex());
return paramters;
}
}
4.controller层代码
@RestController("/pdf")
public class PdfController {
@Autowired
private PdfService reportPrint;
@GetMapping("/export")
public void export(HttpServletResponse response, FieldVo fieldVo) {
response.setHeader("content-disposition","attachment;fileName="+"下载时的文件名.pdf");
try {
reportPrint.generateTempPDF(response,fieldVo);
} catch (Exception e) {
e.printStackTrace();
}
}
}
5.vo类
这个是填充到模板中内容,可自行添加。
/**
* 填充模板的内容
*/
@Data
public class FieldVo {
private String name;
private String sex;
}
6.字体导入
配置所需字体包,可以在本地C:\Windows\Fonts中拷贝需要使用的字体包。
参考文章
SpringBoot使用模板动态导出PDF使用itextpdf