最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java在pdf中生成表格的方法

 更新時(shí)間:2015年11月27日 17:18:44   作者:WhyWin  
這篇文章主要介紹了java在pdf中生成表格的方法,需要的朋友可以參考下

1、目標(biāo)

  在pdf中生成一個(gè)可變表頭的表格,并向其中填充數(shù)據(jù)。通過泛型動(dòng)態(tài)的生成表頭,通過反射動(dòng)態(tài)獲取實(shí)體類(我這里是User)的get方法動(dòng)態(tài)獲得數(shù)據(jù),從而達(dá)到動(dòng)態(tài)生成表格。

  每天生成一個(gè)文件夾存儲(chǔ)生成的pdf文件(文件夾的命名是年月日時(shí)間戳),如:20151110

  生成的文件可能在毫秒級(jí)別,故文件的命名規(guī)則是"到毫秒的時(shí)間戳-uuid",如:20151110100245690-ece540e5-7737-4ab7-b2d6-87bc23917c8c.pdf

  通過讀取properties文件動(dòng)態(tài)獲取文件存儲(chǔ)的跟目錄。

2、所需的jar

  這里通過itex插件進(jìn)行pdf的生成,需要的jar包括以下幾個(gè)

3、編碼實(shí)現(xiàn)

1)、實(shí)體類

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.name = 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文件

pdfPath=E\:/appDataPdf
3)、讀取properties文件,獲取pdf存儲(chǔ)的路徑

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 
{
 /**
 * 讀取文件,獲取excel保存的根目錄
 * @return excel保存的根目錄
 */
 public String getFilePath()
 {
 String dir = System.getProperty("user.dir"); //獲得tomcat所在的工作路徑 
 
 //獲取到存儲(chǔ)了文件存儲(chǔ)位置的filedir.properties 文件路徑 --->java Project的文件路徑
 String realDir = dir + File.separator + "src" + File.separator +"META-INF" + File.separator + "filedir.properties";
 
     //Web project存儲(chǔ)路徑
 /*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";
 */
 return realDir;
 }
 
 /**
 * 獲取filePath路徑【properities文件】中key對應(yīng)的值,
 * @param filePath properities文件路徑【包含properities文件】
 * @param key 要查找的key值
 * @return key對應(yīng)的value
 */
 public String GetValueByKey(String filePath, String key) 
 {
  Properties pps = new Properties();
  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;
  }
 }
 
 /**
 * 查詢properities文件中可以對應(yīng)的存儲(chǔ)地點(diǎn)
 * @param key 查詢主鍵
 * @return key對應(yīng)的存儲(chǔ)地址
 */
 public String getFileDirFromProperties(String key)
 {
 return GetValueByKey(getFilePath(),key);
 }

}

4)、獲取當(dāng)天存在的文件路徑,不存在則生成一個(gè)新的文件夾

package com.zcr.service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class GenerateFold
{
 /**
 * 查詢當(dāng)前生成的excel需要存在在哪個(gè)路徑,如果存在則存儲(chǔ)在相應(yīng)的位置,否則生成改目錄, 每天生成一個(gè)文件夾,文件夾的命名規(guī)則為 年月日的時(shí)間戳
 * @param foldName 生成excel保存路徑
 * @return  現(xiàn)在的excel需要保存路徑
 */
 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("不存在");
  file.mkdirs();
 }
 else
 {
  System.out.println("存在");
 }
 return foldPath;
 }

}

5)、生成文件的名字

package com.zcr.until;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.UUID;

/**
 * 生成文件名字
 * @author zcr
 *
 */
public class GenerateFileName
{
 /**
 * 根據(jù)文件類別生成文件的名字,文件的命名規(guī)則是:文件目錄/生成時(shí)間-uuid(全球唯一編碼).文件類別
 * @param fileDir 文件的存儲(chǔ)路徑
 * @param fileType 文件的類別
 * @return   文件的名字 
 */
 public String generateFileName(String fileDir,String fileType)
 {
 String saveFileName = "";
 SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSS");
 saveFileName += format.format(Calendar.getInstance().getTime());
 
 UUID uuid = UUID.randomUUID(); //全球唯一編碼
 
 saveFileName += "-" + uuid.toString();
 saveFileName += "." + fileType;
 
 saveFileName = fileDir + File.separator + saveFileName;
 
 return saveFileName;
 }
}

6)、生成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;

/**
 * 生成pdf
 * @author zcr
 * 
 */
public class CreatePdf
{
 Document document = new Document();// 建立一個(gè)Document對象

 private static Font headfont;// 設(shè)置字體大小
 private static Font keyfont;// 設(shè)置字體大小
 private static Font textfont;// 設(shè)置字體大小

 static
 {
 //中文格式
 BaseFont bfChinese;
 try
 {
  // 設(shè)置中文顯示
  bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
  headfont = new Font(bfChinese, 10, Font.BOLD);// 設(shè)置字體大小
  keyfont = new Font(bfChinese, 8, Font.BOLD);// 設(shè)置字體大小
  textfont = new Font(bfChinese, 8, Font.NORMAL);// 設(shè)置字體大小
 }
 catch (Exception e)
 {
  e.printStackTrace();
 }
 }
 
 /**
 * 文成文件
 * @param file 待生成的文件名
 */
 public CreatePdf(File file)
 {
 document.setPageSize(PageSize.A4);// 設(shè)置頁面大小
 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);// 設(shè)置頁面大小
 try
 {
  PdfWriter.getInstance(document, new FileOutputStream(file));
  document.open();
 }
 catch (Exception e)
 {
  e.printStackTrace();
 }
 }
 

 int maxWidth = 520;
 
 /**
 * 為表格添加一個(gè)內(nèi)容
 * @param value  值
 * @param font  字體
 * @param align  對齊方式
 * @return  添加的文本框
 */
 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;
 }
 
 /**
 * 為表格添加一個(gè)內(nèi)容
 * @param value  值
 * @param font  字體
 * @return  添加的文本框
 */
 public PdfPCell createCell(String 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;
 }

 /**
 * 為表格添加一個(gè)內(nèi)容
 * @param value  值
 * @param font  字體
 * @param align  對齊方式
 * @param colspan 占多少列
 * @return  添加的文本框
 */
 public PdfPCell createCell(String value, Font font, int align, int colspan)
 {
 PdfPCell cell = new PdfPCell();
 cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
 cell.setHorizontalAlignment(align);
 cell.setColspan(colspan);
 cell.setPhrase(new Phrase(value, font));
 return cell;
 }
 
 /**
 * 為表格添加一個(gè)內(nèi)容
 * @param value  值
 * @param font  字體
 * @param align  對齊方式
 * @param colspan 占多少列
 * @param boderFlag 是否有有邊框
 * @return  添加的文本框
 */
 public PdfPCell createCell(String value, Font font, int align, int colspan,
  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;
 }

 /**
 * 創(chuàng)建一個(gè)表格對象
 * @param colNumber 表格的列數(shù)
 * @return  生成的表格對象
 */
 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).getClass();
 
 // 創(chuàng)建一個(gè)只有5列的表格
 PdfPTable table = createTable(colNum);

 // 添加備注,靠左,不顯示邊框
 table.addCell(createCell("APP信息列表:", keyfont, Element.ALIGN_LEFT, colNum,false));
 
 //設(shè)置表頭
 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 ++)
  {
   //獲得首字母
   String firstLetter = head[j].substring(0,1).toUpperCase(); 
   
   //獲得get方法,getName,getAge等
   String getMethodName = "get" + firstLetter + head[j].substring(1);
   
   Method method;
   try
   {
   //通過反射獲得相應(yīng)的get方法,用于獲得相應(yīng)的屬性值
   method = classType.getMethod(getMethodName, new Class[]{});
   try
   {
    System.out.print(getMethodName +":" + method.invoke(t, new Class[]{}) +",");
    //添加數(shù)據(jù)
    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
 {
  //將表格添加到文檔中
  document.add(table);
 }
 catch (DocumentException e)
 {
  e.printStackTrace();
 }
 
 //關(guān)閉流
 document.close();
 }
 
 
 /**
 * 提供外界調(diào)用的接口,生成以head為表頭,list為數(shù)據(jù)的pdf
 * @param head //數(shù)據(jù)表頭
 * @param list //數(shù)據(jù)
 * @return //excel所在的路徑
 */
 public <T> String generatePDFs(String [] head,List<T> list)
 {
 final String FilePath = "pdfPath";
 String saveFilePathAndName = "";
 
 //獲得存儲(chǔ)的根目錄
 String savePath = new GetFilePlace().getFileDirFromProperties(FilePath);
 
 //獲得當(dāng)天存儲(chǔ)的路徑,不存在則生成當(dāng)天的文件夾
 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(); //生成一個(gè)pdf文件
 }
 catch (IOException e)
 {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 new CreatePdf(file).generatePDF(head,list,head.length);
 
 return saveFilePathAndName;
 }

}

7)、測評(píng)函數(shù) 

 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,"北京","男","AA");
 User user2 = new User("lisi",22222,3.2f,"上海","女","BB");
 
 list.add(user1);
 list.add(user2);
 
 
 String filePath = new CreatePdf().generatePDFs(head,list);
 System.out.println(filePath);
 System.out.println("end");
 }

8)、測試結(jié)果

9)、文件內(nèi)容如下

4、其他相關(guān)鏈接

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

讀取excel:java使用POI批量導(dǎo)入excel數(shù)據(jù)的方法

java如何在pdf中生成表格,我相信通過這個(gè)簡單實(shí)例演示有了大概的認(rèn)識(shí),大家可以動(dòng)手去試驗(yàn)一下,看看會(huì)不會(huì)達(dá)到預(yù)想的效果。

相關(guān)文章

  • java多態(tài)實(shí)現(xiàn)電子寵物系統(tǒng)

    java多態(tài)實(shí)現(xiàn)電子寵物系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了java多態(tài)實(shí)現(xiàn)電子寵物系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • Java Reflect如何利用反射獲取屬性上的注解

    Java Reflect如何利用反射獲取屬性上的注解

    AnnotatedElement接口是Java反射機(jī)制的一部分,用于讀取運(yùn)行中程序的注釋信息,通過getAnnotation、getAnnotations、isAnnotationPresent和getDeclaredAnnotations方法,可以訪問和判斷注解,Field類實(shí)現(xiàn)了該接口
    2024-09-09
  • springmvc重定向?qū)崿F(xiàn)方法解析

    springmvc重定向?qū)崿F(xiàn)方法解析

    這篇文章主要介紹了springmvc重定向?qū)崿F(xiàn)方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-01-01
  • SpringCloud?Nacos?+?Ribbon?調(diào)用服務(wù)的實(shí)現(xiàn)方式(兩種)

    SpringCloud?Nacos?+?Ribbon?調(diào)用服務(wù)的實(shí)現(xiàn)方式(兩種)

    這篇文章主要介紹了SpringCloud?Nacos?+?Ribbon?調(diào)用服務(wù)的兩種方法,分別是通過代碼的方式調(diào)用服務(wù)和通過注解方式調(diào)用服務(wù),每種方式給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-03-03
  • Spring體系的各種啟動(dòng)流程詳解

    Spring體系的各種啟動(dòng)流程詳解

    這篇文章主要給大家介紹了關(guān)于Spring體系的各種啟動(dòng)流程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • 還在用if(obj!=null)做非空判斷,帶你快速上手Optional

    還在用if(obj!=null)做非空判斷,帶你快速上手Optional

    這篇文章主要介紹了還在用if(obj!=null)做非空判斷,帶你快速上手Optional,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • java直接插入排序示例

    java直接插入排序示例

    這篇文章主要介紹了java直接插入排序示例,插入排序的比較次數(shù)仍然是n的平方,但在一般情況下,它要比冒泡排序快一倍,比選擇排序還要快一點(diǎn)。它常常被用在復(fù)雜排序算法的最后階段,比如快速排序。
    2014-05-05
  • Idea Project文件目錄不見了,只剩External Libraries和imi文件的解決

    Idea Project文件目錄不見了,只剩External Libraries和imi文件的解決

    這篇文章主要介紹了Idea Project文件目錄不見了,只剩External Libraries和imi文件的解決方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • Java圓通物流軌跡推送服務(wù)接口文檔及流程

    Java圓通物流軌跡推送服務(wù)接口文檔及流程

    這篇文章主要介紹了圓通物流軌跡推送服務(wù)接口Java文檔,主要用來接收圓通推送的訂單狀態(tài),本文給大家分享詳細(xì)流程,感興趣的朋友跟隨小編一起看看吧
    2022-02-02
  • 詳解Java數(shù)據(jù)庫連接池

    詳解Java數(shù)據(jù)庫連接池

    今天繼續(xù)Java的課題,兩天沒有做任何事情,過了個(gè)自在的周末,但是不知道為什么總是有點(diǎn)淡淡的憂桑.之前游戲服務(wù)器的數(shù)據(jù)源使用的是阿里巴巴的Druid,今天就大概說說數(shù)據(jù)源,給個(gè)實(shí)例,需要的朋友可以參考下
    2021-06-06

最新評(píng)論

石首市| 莱芜市| 西乌| 阳山县| 从化市| 南和县| 简阳市| 略阳县| 衡阳市| 德钦县| 临桂县| 永川市| 渝北区| 平遥县| 宜丰县| 周口市| 安宁市| 博湖县| 石渠县| 瑞昌市| 云霄县| 临清市| 会泽县| 龙游县| 平潭县| 安徽省| 双江| 池州市| 龙游县| 普兰店市| 张家口市| 徐汇区| 正宁县| 德江县| 湖州市| 浪卡子县| 阳江市| 搜索| 开封市| 新源县| 青河县|