1. Target
Generate a table with variable headers in the PDF and populate it with data. Dynamically generating tables are achieved by dynamically fetching the entity class (I here is user) by using a generic dynamic generation header to obtain the data in a dynamic way.
Generate one Folder store per day (name of the folder is the date of year), such as: 20151110
The generated file may be at the millisecond level, so the file's naming rule is "to the time stamp-uuid in milliseconds", such as: 20151110100245690-ece540e5-7737-4ab7-b2d6-87bc23917c8c.pdf
Dynamically obtain the directory of the file store by reading the properties file.
2, the required jar
Here through the Itex Plug-ins for PDF generation, the need for the jar includes the following several
3, coding implementation
1), Entity class
Package com.zcr.until;
public class User {private String name;
private int age;
private float height;
Private String adress;
Private String sex;
Private String JJ;
Public String GETJJ () {return JJ;
public void Setjj (String jj) {this.jj = JJ; Public user () {} public user (String name,int age,float height,string adress,string sex,string JJ) {This.nam
e = name;
This.age = age;
This.height = height;
this.adress = adress;
This.sex = sex;
THIS.JJ = JJ;
Public String getadress () {return adress;
} public void Setadress (String adress) {this.adress = adress;
Public String Getsex () {return sex;
} public void Setsex (String sex) {this.sex = sex;
Public String GetName () {return name;
public void SetName (String name) {this.name = name;
public int getage () {return age;
public void Setage (int age) {this.age = age;
public float getheight () {return height; } public void SetHeight (Float height) {this.height = height;
}
}
2), properties file
Pdfpath=e\:/appdatapdf
3, read the properties file, get the PDF storage path
Package com.zcr.until;
Import Java.io.BufferedInputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.util.Properties; public class Getfileplace {/** * Read the file, get the root directory saved by Excel * @return Excel saved root/public String GetFilePath () {St Ring dir = System.getproperty ("User.dir"); Get Tomcat's working path//Get to the Filedir.properties file path where the file storage location is stored--->java project's file path String realdir = dir + File.sepa
Rator + "src" + file.separator + "Meta-inf" + file.separator + "filedir.properties"; WEB Project Storage path/*string Realdir = dir.substring (0, Dir.length ()-4) + File.separator + "WebApps" + file.separator + "ge Nerateexcels "+ file.separator +" classes "+ File.separator +" Meta-inf "+ file.separator +" config "+ File.separat
or + "filedir.properties";
* * return realdir; /** * Gets the value of key in FilePath path "Properities file", * @param filePath properities file path "contains properities file" * @param key to find
Key value * @return key corresponding to value/public String Getvaluebykey (string filePath, String key) {Properties pps = new Prope
Rties ();
try {inputstream in = new Bufferedinputstream (new FileInputStream (FilePath));
Pps.load (in);
String value = Pps.getproperty (key);
In.close ();
return value;
}catch (IOException e) {e.printstacktrace ();
return null; }/** * Query properities file can be the corresponding storage location * @param key Query primary key * @return key corresponding to the storage address * * Public String GETFILEDIRFROMPR
Operties (String key) {return Getvaluebykey (GetFilePath (), key);
}
}
4, get the file path that exists on the day, do not exist to generate a new folder
Package com.zcr.service;
Import Java.io.File;
Import Java.text.SimpleDateFormat;
Import Java.util.Calendar;
public class Generatefold
{
/**
* Query which path the currently generated Excel needs to exist, if it exists, store it in the appropriate location, or generate a change directory, generate a folder every day, and the folder's naming rules are Time Stamp
* @param foldname Build Excel save path
* @return now Excel needs to save the path/public
String Getfold ( String foldname)
{
SimpleDateFormat format = new SimpleDateFormat ("YyyyMMdd");
String todaystr = Format.format (Calendar.getinstance (). GetTime ());
String Foldpath = foldname + File.separator + todaystr;
File File = new file (Foldpath);
if (!file.exists () &&!file.isdirectory ())
{
System.out.println ("does not exist");
File.mkdirs ();
}
else
{
System.out.println ("exist");
}
Return Foldpath
}
}
5), the name of the generated file
Package com.zcr.until;
Import Java.io.File;
Import Java.text.SimpleDateFormat;
Import Java.util.Calendar;
Import Java.util.UUID;
/**
* Generate file name
* @author ZCR
* */public
class Generatefilename
{
/**
* The name of the file is generated from the file category, and the naming rule for the file is: File directory/build time-uuid (globally unique encoding). File category *
@param filedir file storage path
* @param fileType file category
* the name of the @return file
//Public String generatefilename (string filedir,string fileType)
{
string Savefilename = "";
SimpleDateFormat format = new SimpleDateFormat ("Yyyymmddhhmmssss");
Savefilename + + Format.format (calendar.getinstance (). GetTime ());
UUID uuid = Uuid.randomuuid (); The world's only code Savefilename + +
+ uuid.tostring ();
Savefilename + = "." + FileType;
Savefilename = filedir + File.separator + savefilename;
Return Savefilename
}
}
6), generate PDF
Package com.zcr.service;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;
Import java.util.ArrayList;
Import java.util.List;
Import com.lowagie.text.Document;
Import com.lowagie.text.DocumentException;
Import com.lowagie.text.Element;
Import Com.lowagie.text.Font;
Import com.lowagie.text.PageSize;
Import Com.lowagie.text.Phrase;
Import Com.lowagie.text.pdf.BaseFont;
Import Com.lowagie.text.pdf.PdfPCell;
Import com.lowagie.text.pdf.PdfPTable;
Import Com.lowagie.text.pdf.PdfWriter;
Import Com.zcr.until.GenerateFileName;
Import Com.zcr.until.GetFilePlace;
Import Com.zcr.until.User; /** * Generates PDF * @author ZCR * * */public class CreatePDF {Document document = new document ();//Create a Document object Priva
Te static font headfont;//set font size private static font keyfont;//set font size private static font textfont;//set Font size static
{///Chinese format basefont Bfchinese; try {//Set Chinese display Bfchinese = Basefont.createfont ("Stsong-light", "unigb-ucs2-h", basefont.not_embedded); Headfont = new Font (Bfchinese, font.bold);/set Font size Keyfont = new Font (Bfchinese, 8, font.bold);/Set Font size TEXTFO
NT = new Font (Bfchinese, 8, font.normal);//Set Font size} catch (Exception e) {e.printstacktrace (); }/** * Wencheng files * @param file file to be generated * * * Public createpdf (file file) {document.setpagesize (PAGESIZE.A4);//Set
Page size try {pdfwriter.getinstance (document, new FileOutputStream (file));
Document.open ();
catch (Exception e) {e.printstacktrace ();
} public CreatePDF () {} public void Initfile (file file) {document.setpagesize (PAGESIZE.A4);//Set Page size
try {pdfwriter.getinstance (document, new FileOutputStream (file));
Document.open ();
catch (Exception e) {e.printstacktrace ();
an int maxwidth = 520; /** * Add a content to the table * @param value * @param font font * @param align Alignment * @Return Added text box */public Pdfpcell Createcell (String value, font font, int align) {pdfpcell cell = new Pdfpcell ();
Cell.setverticalalignment (Element.align_middle);
Cell.sethorizontalalignment (align);
Cell.setphrase (New Phrase (value, font));
return cell; /** * Add a content to the table * @param value * @param font font * @return added textbox * * Public Pdfpcell Createcell (St
Ring value, font font) {Pdfpcell cell = new Pdfpcell ();
Cell.setverticalalignment (Element.align_middle);
Cell.sethorizontalalignment (Element.align_center);
Cell.setphrase (New Phrase (value, font));
return cell; /** * Add a content to the table * @param value * @param font font * @param align alignment * @param colspan how many columns * @retu RN Added text box */public Pdfpcell Createcell (String value, font font, int align, int colspan) {Pdfpcell cell = new Pd
Fpcell ();
Cell.setverticalalignment (Element.align_middle);
Cell.sethorizontalalignment (align);
Cell.setcolspan (colspan); Cell.setphrASE (new Phrase (value, font));
return cell; /** * Add a content to the table * @param value * @param font font * @param align alignment * @param colspan how many columns * @par Am Boderflag a text box with a border * @return added */public Pdfpcell Createcell (String value, font font, int align, int colspa
N, Boolean boderflag) {Pdfpcell cell = new Pdfpcell ();
Cell.setverticalalignment (Element.align_middle);
Cell.sethorizontalalignment (align);
Cell.setcolspan (colspan);
Cell.setphrase (New Phrase (value, font));
Cell.setpadding (3.0f);
if (!boderflag) {cell.setborder (0);
Cell.setpaddingtop (15.0f);
Cell.setpaddingbottom (8.0f);
} return cell;
/** * Create a Table object * @param the number of columns in colnumber table * @return generated Table object/public pdfptable createtable (int colnumber)
{pdfptable table = new pdfptable (colnumber);
try {table.settotalwidth (maxwidth);
Table.setlockedwidth (TRUE);
Table.sethorizontalalignment (Element.align_center); Table.getdefaultcell (). SetBorder (1);
catch (Exception e) {e.printstacktrace ();
return table;
Public pdfptable createtable (float[] widths) {pdfptable table = new pdfptable (widths);
try {table.settotalwidth (maxwidth);
Table.setlockedwidth (TRUE);
Table.sethorizontalalignment (Element.align_center);
Table.getdefaultcell (). SetBorder (1);
catch (Exception e) {e.printstacktrace ();
return table;
Public pdfptable createblanktable () {pdfptable table = new pdfptable (1);
Table.getdefaultcell (). SetBorder (0);
Table.addcell (Createcell ("", Keyfont));
Table.setspacingafter (20.0f);
Table.setspacingbefore (20.0f);
return table; } public <T> void Generatepdf (String [] head,list<t> list,int colnum) {Class ClassType = list.get (0). GE
Tclass ();
Create a table with only 5 columns pdfptable table = createtable (colnum);
Add notes, left, do not display borders Table.addcell (Createcell ("app info list:", Keyfont, Element.align_left, Colnum,false)); Sets the table header for (int i = 0; i < ColnUm;
i++) {Table.addcell (Createcell (head[i), Keyfont, Element.align_center));
} if (null!= list && list.size () > 0) {int size = List.size ();
for (int i = 0; i < size; i++) {T t = list.get (i);
for (int j = 0; J < Colnum J + +) {//Get the first letter String Firstletter = head[j].substring (0,1). toUpperCase ();
Gets the Get method, Getname,getage etc. String getmethodname = "getting" + Firstletter + head[j].substring (1);
Method method;
try {//The corresponding Get method is obtained by reflection, which is used to obtain the corresponding property value methods = Classtype.getmethod (Getmethodname, New class[]{});
try {System.out.print (getmethodname + ":" + method.invoke (t, new class[]{}) + ",");
Add Data Table.addcell (Createcell (Method.invoke (t, new class[]{}). 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 {//Add a table to the document Document.add (table);
catch (Documentexception e) {e.printstacktrace ();
}//Close stream document.close ();
/** * Provides an externally invoked interface to generate a PDF with head header, list as data @param head//Data header * @param list//data * @return//excel Path
Public <T> string Generatepdfs (string [] head,list<t> List) {final String FilePath = "Pdfpath";
String savefilepathandname = "";
Gets the stored root string savepath = new Getfileplace (). Getfiledirfromproperties (FilePath);
Gets the path stored for the day, does not exist, generates the day's folder String Realsavepath = new Generatefold (). Getfold (Savepath);
Savefilepathandname = new Generatefilename (). Generatefilename (Realsavepath, "pdf"); File file= new File (savefilepathandname);
try {file.createnewfile ();
catch (IOException E1) {//TODO auto-generated catch block E1.printstacktrace ();
} initfile (file); try {file.createnewfile ();//Generate a PDF file} catch (IOException e) {//TODO auto-generated catch block e.pr
Intstacktrace ();
New CreatePDF (file). generatepdf (Head,list,head.length);
return savefilepathandname;
}
}
7), evaluation function
public static void Main (string[] args)
{
System.out.println ("Begin");
String [] head = {' name ', ' sex ', ' adress ', ' height ', ' age ', ' JJ '};
list<user> list = new arraylist<user> ();
User User1 = new User ("Zhangsan", 1,1.1f, "Beijing", "male", "AA");
User User2 = New User ("Lisi", 22222,3.2f, "Shanghai", "female", "BB");
List.add (user1);
List.add (user2);
String FilePath = new CreatePDF (). Generatepdfs (head,list);
System.out.println (FilePath);
System.out.println ("End");
}
8), test results
9), the contents of the document are as follows
Java how to generate a table in the PDF, I believe that through this simple example demo with a general understanding, we can go to experiment to see if it will achieve the desired results.