java如何在pdf中生成表格

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

1、目标

在pdf中生成一个可变表头的表格,并向其中填充数据。通过泛型动态的生成表头,通过反射动态获取实体类(我这里是User)的get方法动态获得数据,从而达到动态生成表格。

每天生成一个文件夹存储生成的pdf文件(文件夹的命名是年月日时间戳),如:20151110

生成的文件可能在毫秒级别,故文件的命名规则是"到毫秒的时间戳-uuid",如:20151110100245690-ece540e5-7737-4ab7-b2d6-87bc23917c8c.pdf

通过读取PRoperties文件动态获取文件存储的跟目录。获取方式可查看:http://www.cnblogs.com/0201zcr/p/4700418.html

2、所需的jar

这里通过itex插件进行pdf的生成,需要的jar包括以下几个

3、编码实现

1)、实体类

packagecom.zcr.until;publicclassUser

{privateString name;privateintage ;privatefloatheight;privateString adress;privateString sex;privateString jj;publicString getJj()

{returnjj;

}publicvoidsetJj(String jj)

{this.jj =jj;

}publicUser()

{

}publicUser(String name,intage,floatheight,String adress,String sex,String jj)

{this.name =name;this.age =age;this.height =height;this.adress =adress;this.sex =sex;this.jj =jj;

}publicString getAdress()

{returnadress;

}publicvoidsetAdress(String adress)

{this.adress =adress;

}publicString getSex()

{returnsex;

}publicvoidsetSex(String sex)

{this.sex =sex;

}publicString getName() {returnname;

}publicvoidsetName(String name) {this.name =name;

}publicintgetAge() {returnage;

}publicvoidsetAge(intage) {this.age =age;

}publicfloatgetHeight() {returnheight;

}publicvoidsetHeight(floatheight) {this.height =height;

}

}

2)、properties文件

pdfPath=E\:/appDataPdf

3)、读取properties文件,获取pdf存储的路径

packagecom.zcr.until;importjava.io.BufferedInputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importjava.util.Properties;publicclassGetFilePlace

{/*** 读取文件,获取Excel保存的根目录

*@returnexcel保存的根目录*/publicString getFilePath()

{

String dir= System.getProperty("user.dir");//获得tomcat所在的工作路径//获取到存储了文件存储位置的filedir.properties 文件路径 --->java Project的文件路径String realDir = dir + File.separator + "src" + File.separator +"META-INF" + File.separator + "filedir.properties";

//Web project存储路径/*String realDir = dir.substring(0, dir.length()-4) + File.separator +"webapps" + File.separator + "generateExcels"

+ File.separator + "classes" + File.separator + "META-INF" + File.separator + "config" + File.separator + "filedir.properties";*/returnrealDir;

}/*** 获取filePath路径【properities文件】中key对应的值,

*@paramfilePath properities文件路径【包含properities文件】

*@paramkey 要查找的key值

*@returnkey对应的value*/publicString GetValueByKey(String filePath, String key)

{

Properties pps=newProperties();try{

InputStream in=newBufferedInputStream (newFileInputStream(filePath));

pps.load(in);

String value=pps.getProperty(key);

in.close();returnvalue;

}catch(IOException e) {

e.printStackTrace();returnnull;

}

}/*** 查询properities文件中可以对应的存储地点

*@paramkey 查询主键

*@returnkey对应的存储地址*/publicString getFileDirFromProperties(String key)

{returnGetValueByKey(getFilePath(),key);

}

}

4)、获取当天存在的文件路径,不存在则生成一个新的文件夹

packagecom.zcr.service;importjava.io.File;importjava.text.SimpleDateFormat;importjava.util.Calendar;publicclassGenerateFold

{/*** 查询当前生成的excel需要存在在哪个路径,如果存在则存储在相应的位置,否则生成改目录, 每天生成一个文件夹,文件夹的命名规则为 年月日的时间戳

*@paramfoldName 生成excel保存路径

*@return现在的excel需要保存路径*/publicString getFold(String foldName)

{

SimpleDateFormat format=newSimpleDateFormat("yyyyMMdd");

String todayStr=format.format(Calendar.getInstance().getTime());

String foldPath= foldName + File.separator +todayStr;

File file=newFile(foldPath);if(!file.exists() && !file.isDirectory())

{

System.out.println("不存在");

file.mkdirs();

}else{

System.out.println("存在");

}returnfoldPath;

}

}

5)、生成文件的名字

packagecom.zcr.until;importjava.io.File;importjava.text.SimpleDateFormat;importjava.util.Calendar;importjava.util.UUID;/*** 生成文件名字

*@authorzcr

**/publicclassGenerateFileName

{/*** 根据文件类别生成文件的名字,文件的命名规则是:文件目录/生成时间-uuid(全球唯一编码).文件类别

*@paramfileDir 文件的存储路径

*@paramfileType 文件的类别

*@return文件的名字*/publicString generateFileName(String fileDir,String fileType)

{

String saveFileName= "";

SimpleDateFormat format=newSimpleDateFormat("yyyyMMddHHmmssSS");

saveFileName+=format.format(Calendar.getInstance().getTime());

UUID uuid= UUID.randomUUID();//全球唯一编码saveFileName+= "-" +uuid.toString();

saveFileName+= "." +fileType;

saveFileName= fileDir + File.separator +saveFileName;returnsaveFileName;

}}

6)、生成pdf

packagecom.zcr.service;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;importjava.util.ArrayList;importjava.util.List;importcom.lowagie.text.Document;importcom.lowagie.text.DocumentException;importcom.lowagie.text.Element;importcom.lowagie.text.Font;importcom.lowagie.text.PageSize;importcom.lowagie.text.Phrase;importcom.lowagie.text.pdf.BaseFont;importcom.lowagie.text.pdf.PdfPCell;importcom.lowagie.text.pdf.PdfPTable;importcom.lowagie.text.pdf.PdfWriter;importcom.zcr.until.GenerateFileName;importcom.zcr.until.GetFilePlace;importcom.zcr.until.User;/*** 生成pdf

*@authorzcr

**/publicclassCreatePdf

{

Document document=newDocument();//建立一个Document对象privatestaticFont headfont;//设置字体大小privatestaticFont keyfont;//设置字体大小privatestaticFont textfont;//设置字体大小static{//中文格式BaseFont bfChinese;try{//设置中文显示bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);

headfont=newFont(bfChinese, 10, Font.BOLD);//设置字体大小keyfont =newFont(bfChinese, 8, Font.BOLD);//设置字体大小textfont =newFont(bfChinese, 8, Font.NORMAL);//设置字体大小}catch(Exception e)

{

e.printStackTrace();

}

}/*** 文成文件

*@paramfile 待生成的文件名*/publicCreatePdf(File file)

{

document.setPageSize(PageSize.A4);//设置页面大小try{

PdfWriter.getInstance(document,newFileOutputStream(file));

document.open();

}catch(Exception e)

{

e.printStackTrace();

}

}publicCreatePdf()

{

}publicvoidinitFile(File file)

{

document.setPageSize(PageSize.A4);//设置页面大小try{

PdfWriter.getInstance(document,newFileOutputStream(file));

document.open();

}catch(Exception e)

{

e.printStackTrace();

}

}intmaxWidth = 520;/*** 为表格添加一个内容

*@paramvalue 值

*@paramfont 字体

*@paramalign 对齐方式

*@return添加的文本框*/publicPdfPCell createCell(String value, Font font,intalign)

{

PdfPCell cell=newPdfPCell();

cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

cell.setHorizontalAlignment(align);

cell.setPhrase(newPhrase(value, font));returncell;

}/*** 为表格添加一个内容

*@paramvalue 值

*@paramfont 字体

*@return添加的文本框*/publicPdfPCell createCell(String value, Font font)

{

PdfPCell cell=newPdfPCell();

cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

cell.setHorizontalAlignment(Element.ALIGN_CENTER);

cell.setPhrase(newPhrase(value, font));returncell;

}/*** 为表格添加一个内容

*@paramvalue 值

*@paramfont 字体

*@paramalign 对齐方式

*@paramcolspan 占多少列

*@return添加的文本框*/publicPdfPCell createCell(String value, Font font,intalign,intcolspan)

{

PdfPCell cell=newPdfPCell();

cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

cell.setHorizontalAlignment(align);

cell.setColspan(colspan);

cell.setPhrase(newPhrase(value, font));returncell;

}/*** 为表格添加一个内容

*@paramvalue 值

*@paramfont 字体

*@paramalign 对齐方式

*@paramcolspan 占多少列

*@paramboderFlag 是否有有边框

*@return添加的文本框*/publicPdfPCell createCell(String value, Font font,intalign,intcolspan,booleanboderFlag)

{

PdfPCell cell=newPdfPCell();

cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

cell.setHorizontalAlignment(align);

cell.setColspan(colspan);

cell.setPhrase(newPhrase(value, font));

cell.setPadding(3.0f);if(!boderFlag)

{

cell.setBorder(0);

cell.setPaddingTop(15.0f);

cell.setPaddingBottom(8.0f);

}returncell;

}/*** 创建一个表格对象

*@paramcolNumber 表格的列数

*@return生成的表格对象*/publicPdfPTable createTable(intcolNumber)

{

PdfPTable table=newPdfPTable(colNumber);try{

table.setTotalWidth(maxWidth);

table.setLockedWidth(true);

table.setHorizontalAlignment(Element.ALIGN_CENTER);

table.getDefaultCell().setBorder(1);

}catch(Exception e)

{

e.printStackTrace();

}returntable;

}publicPdfPTable createTable(float[] widths)

{

PdfPTable table=newPdfPTable(widths);try{

table.setTotalWidth(maxWidth);

table.setLockedWidth(true);

table.setHorizontalAlignment(Element.ALIGN_CENTER);

table.getDefaultCell().setBorder(1);

}catch(Exception e)

{

e.printStackTrace();

}returntable;

}publicPdfPTable createBlankTable()

{

PdfPTable table=newPdfPTable(1);

table.getDefaultCell().setBorder(0);

table.addCell(createCell("", keyfont));

table.setSpacingAfter(20.0f);

table.setSpacingBefore(20.0f);returntable;

}public<T>voidgeneratePDF(String [] head,List<T> list,intcolNum)

{

Class classType= list.get(0).getClass();//创建一个只有5列的表格PdfPTable table =createTable(colNum);//添加备注,靠左,不显示边框table.addCell(createCell("APP信息列表:", keyfont, Element.ALIGN_LEFT, colNum,false));//设置表头for(inti = 0 ; i < colNum ; i++)

{

table.addCell(createCell(head[i], keyfont, Element.ALIGN_CENTER));

}if(null!= list && list.size() > 0)

{intsize =list.size();for(inti = 0 ; i < size ; i++)

{

T t=list.get(i);for(intj = 0 ; j < colNum ; j ++)

{//获得首字母String firstLetter = head[j].substring(0,1).toUpperCase();//获得get方法,getName,getAge等String getMethodName = "get" + firstLetter + head[j].substring(1);

Method method;try{//通过反射获得相应的get方法,用于获得相应的属性值method = classType.getMethod(getMethodName,newClass[]{});try{

System.out.print(getMethodName+":" + method.invoke(t,newClass[]{}) +",");//添加数据table.addCell(createCell(method.invoke(t,newClass[]{}).toString(), textfont));

}catch(IllegalArgumentException e)

{

e.printStackTrace();

}catch(IllegalaccessException e)

{

e.printStackTrace();

}catch(InvocationTargetException e)

{

e.printStackTrace();

}

}catch(SecurityException e)

{

e.printStackTrace();

}catch(NoSuchMethodException e)

{

e.printStackTrace();

}

}

System.out.println("");

}

}try{//将表格添加到文档中document.add(table);

}catch(DocumentException e)

{

e.printStackTrace();

}//关闭流document.close();

}/*** 提供外界调用的接口,生成以head为表头,list为数据的pdf

*@paramhead //数据表头

*@paramlist //数据

*@return//excel所在的路径*/public<T> String generatePDFs(String [] head,List<T>list)

{finalString FilePath = "pdfPath";

String saveFilePathAndName= "";//获得存储的根目录String savePath =newGetFilePlace().getFileDirFromProperties(FilePath);//获得当天存储的路径,不存在则生成当天的文件夹String realSavePath =newGenerateFold().getFold(savePath);

saveFilePathAndName=newGenerateFileName().generateFileName(realSavePath,"pdf");

File file=newFile(saveFilePathAndName);try{

file.createNewFile();

}catch(IOException e1)

{//TODO Auto-generated catch blocke1.printStackTrace();

}

initFile(file);try{

file.createNewFile();//生成一个pdf文件}catch(IOException e)

{//TODO Auto-generated catch blocke.printStackTrace();

}newCreatePdf(file).generatePDF(head,list,head.length);returnsaveFilePathAndName;

}}

7)、测评函数

publicstaticvoidmain(String[] args)

{

System.out.println("begin");

String [] head= {"name","sex","adress","height","age","jj"};

List<User> list =newArrayList<User>();

User user1=newUser("zhangsan",1,1.1f,"北京","男","AA");

User user2=newUser("lisi",22222,3.2f,"上海","女","BB");

list.add(user1);

list.add(user2);

String filePath=newCreatePdf().generatePDFs(head,list);

System.out.println(filePath);

System.out.println("end");

}

8)、测试结果

9)、文件内容如下

4、其他相关链接

生成可变表头excel:http://www.cnblogs.com/0201zcr/p/4950619.html

读取excel:http://www.cnblogs.com/0201zcr/p/4656779.html

致谢:感谢您的阅读!

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航