之前项目中一直采用的PDF固定模板,在模板中填充值的方式在线生成PDF供用户下载,这种方法在使用过程中有一弊端,就是当填充数据较少但模板的文本框过大时将导致留白过多,影响美观,故上网查阅相关资料,采用Itext中table的格式可有效解决这一问题,部分代码如下,希望可以帮到跟我遇到同样问题的你。
web项目前端采用的Extjs后台采用的是Java,前端数据传到后台,调用toPDF()方法:
public String toPDF() {
String rootPath = ServletActionContext.getServletContext().getRealPath("/");
try {
ViewKtZds[] zdsArr = new ViewKtZds[(datas.size())];
for(int i=0; i < datas.size(); i++){
JSONObject zdsJson = JSONObject.fromObject(datas.get(i));
ViewKtZds zds = (ViewKtZds) JSONObject.toBean(zdsJson,ViewKtZds.class);
zdsArr[i] = zds;
}
String url = this.createPDF(rootPath,zdsArr);
this.setSuccess(true);
this.setMsg(url);
} catch (SecurityException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return "pdf";
}
其中rootPath是目录,zdsArr是前台传来的数据。
//pdf动态生成table方法
public String createPDF(String rootPath, ViewKtZds[] zdsArr) throws DocumentException, IOException{
//设置字体格式
BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// com.itextpdf.text.Font FontChinese24 = new com.itextpdf.text.Font(bfChinese,24,com.itextpdf.text.Font.BOLD);
com.itextpdf.text.Font FontChinese18 = new com.itextpdf.text.Font(bfChinese,18,com.itextpdf.text.Font.BOLD);
// com.itextpdf.text.Font FontChinese16= new com.itextpdf.text.Font(bfChinese,16,com.itextpdf.text.Font.BOLD);
com.itextpdf.text.Font FontChinese12Bold = new com.itextpdf.text.Font(bfChinese,12,com.itextpdf.text.Font.BOLD);
com.itextpdf.text.Font FontChi