一:工程截圖:
二:項目運行截圖:
三:源代碼:
Book.java
package com.iText.bean;public class Book {private int bookId;// 圖書編號private String name;// 圖書名稱private String author;// 圖書作者private float price;// 圖書價格private String isbn;// 圖書ISBNprivate String pubName;// 圖書出版社private byte[] preface;// 封面圖片public Book() {super();}public Book(int bookId, String name, String author, float price,String isbn, String pubName, byte[] preface) {super();this.bookId = bookId;this.name = name;this.author = author;this.price = price;this.isbn = isbn;this.pubName = pubName;this.preface = preface;}public int getBookId() {return bookId;}public void setBookId(int bookId) {this.bookId = bookId;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}public String getIsbn() {return isbn;}public void setIsbn(String isbn) {this.isbn = isbn;}public String getPubName() {return pubName;}public void setPubName(String pubName) {this.pubName = pubName;}public byte[] getPreface() {return preface;}public void setPreface(byte[] preface) {this.preface = preface;}}
Student.java
package com.iText.bean;import java.util.Date;public class Student {private long id;// 學號private String name;// 姓名private int age;// 年齡private boolean sex;// 性別private Date birthday;// 出生日期public Student() {super();}public Student(long id, String name, int age, boolean sex, Date birthday) {super();this.id = id;this.name = name;this.age = age;this.sex = sex;this.birthday = birthday;}public long getId() {return id;}public void setId(long id) {this.id = id;}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 boolean getSex() {return sex;}public void setSex(boolean sex) {this.sex = sex;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}}
StrHelp.java
package com.iText.util;import java.io.UnsupportedEncodingException;
/*** 以上是兩個幫助封裝類,都是為了對付iText的中文問題的* @author zhaoxinguo**/
public class StrHelp {public static String getChinese(String s) {try {return new String(s.getBytes("gb2312"), "iso-8859-1");} catch (UnsupportedEncodingException e) {return s;}}}
PdfParagraph.java
package com.iText.util;import java.io.IOException;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Chunk;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.BaseFont;/*** 下載地址:http://sourceforge.net/projects/itext/files/latest/download* * @author zhaoxinguo* */
public class PdfParagraph extends Paragraph {/*** */private static final long serialVersionUID = 8852816419489363243L;public PdfParagraph(String content) {super(content, getChineseFont(12, false));}public PdfParagraph(String content, int fontSize, boolean isBold) {super(content, getChineseFont(fontSize, isBold));}// 設置字體-返回中文字體protected static Font getChineseFont(int nfontsize, boolean isBold) {BaseFont bfChinese;Font fontChinese = null;try {bfChinese = BaseFont.createFont("c://windows//fonts//simsun.ttc,1",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);if (isBold) {fontChinese = new Font(bfChinese, nfontsize, Font.BOLD);} else {fontChinese = new Font(bfChinese, nfontsize, Font.NORMAL);}} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return fontChinese;}// 轉化中文protected Cell ChangeCell(String str, int nfontsize, boolean isBold)throws IOException, BadElementException, DocumentException {Phrase ph = ChangeChinese(str, nfontsize, isBold);Cell cell = new Cell(ph);return cell;}// 轉化中文protected Chunk ChangeChunk(String str, int nfontsize, boolean isBold)throws IOException, BadElementException, DocumentException {Font FontChinese = getChineseFont(nfontsize, isBold);Chunk chunk = new Chunk(str, FontChinese);return chunk;}// 轉化中文protected Phrase ChangeChinese(String str, int nfontsize, boolean isBold)throws IOException, BadElementException, DocumentException {Font FontChinese = getChineseFont(nfontsize, isBold);Phrase ph = new Phrase(str, FontChinese);return ph;}}
ExportPdf.java
package com.iText.util;import java.awt.Color;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;import javax.swing.JOptionPane;import com.iText.bean.Book;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;/*** 利用開源組件IText2.0.4動態導出PDF文檔 轉載時請保留以下信息,注明出處!* * @author zhaoxinguo* @version v1.0* @param <T>應用泛型,代表任意一個符合javabean風格的類* 注意這里為了簡單起見,boolean型的屬性xxx的get器方式為getXxx(),而不是isXxx()* byte[]表圖片數據,注意合適的大小*/
public class ExportPdf<T> {public void exportPdf(Collection<T> dataset, OutputStream out) {exportPdf("測試iText導出PDF文檔", null, dataset, out, "yyyy-MM-dd");}public void exportPdf(String[] headers, Collection<T> dataset,OutputStream out) {exportPdf("測試iText導出PDF文檔", headers, dataset, out, "yyyy-MM-dd");}public void exportPdf(String[] headers, Collection<T> dataset,OutputStream out, String pattern) {exportPdf("測試iText導出PDF文檔", headers, dataset, out, pattern);}/*** 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中并且符號一定條件的數據以PDF 的形式輸出到指定IO設備上* * @param title* 表格標題名* @param headers表格屬性列名數組* @param dataset需要顯示的數據集合* ,集合中一定要放置符合javabean風格的類的對象。此方法支持的javabean屬性的數據類型有基本數據類型及String* ,Date,byte[](圖片數據)* @param out與輸出設備關聯的流對象* ,可以將PDF文檔導出到本地文件或者網絡中* @param pattern如果有時間數據* ,設定輸出格式。默認為"yyy-MM-dd"*/public void exportPdf(String title, String[] headers,Collection<T> dataset, OutputStream out, String pattern) {// 作為報表的PDF文件,一定要適合打印機的輸出打印Rectangle rectPageSize = new Rectangle(PageSize.A4);// 定義A4頁面大小// rectPageSize = rectPageSize.rotate();// 加上這句可以實現A4頁面的橫置Document document = new Document(rectPageSize, 50, 50, 50, 50);// 其余4個參數,設置了頁面的4個邊距try {// 將PDF文檔寫出到out所關聯IO設備上的書寫對象PdfWriter.getInstance(document, out);// 添加文檔元數據信息document.addTitle(StrHelp.getChinese(title));document.addSubject("export information");document.addAuthor("leno");document.addCreator("leno");document.addKeywords("pdf itext");// 定義頁頭和頁尾HeaderFooter header = new HeaderFooter(new PdfParagraph(title, 20,true), false);header.setAlignment(Element.ALIGN_CENTER);HeaderFooter footer = new HeaderFooter(new Phrase("This is page "), new Phrase("."));footer.setAlignment(Element.ALIGN_CENTER);document.setHeader(header);document.setFooter(footer);// 打開PDF文檔document.open();// 添加一張表格,使用Table或者PdfPTable// Table table = new Table(headers.length);// table.setWidth(16*headers.length);// //table.setWidths(new float[]{20,20,20,30});// table.setCellsFitPage(true);// table.setAutoFillEmptyCells(true);// table.setAlignment(Table.ALIGN_CENTER);// table.setBackgroundColor(Color.yellow);// table.setBorderColor(Color.green);PdfPTable table = new PdfPTable(headers.length);// table.setHorizontalAlignment(Element.ALIGN_CENTER);table.setWidthPercentage(16 * headers.length);// 產生表格標題行for (int i = 0; i < headers.length; i++) {PdfPCell cell = new PdfPCell(new PdfParagraph(headers[i], 14,true));cell.setHorizontalAlignment(Cell.ALIGN_CENTER);cell.setVerticalAlignment(Cell.ALIGN_MIDDLE);cell.setBackgroundColor(Color.cyan);cell.setBorderColor(Color.green);table.addCell(cell);}// 遍歷集合數據,產生數據行Iterator<T> it = dataset.iterator();int index = 0;while (it.hasNext()) {index++;T t = (T) it.next();// 利用反射,根據javabean屬性的先后順序,動態調用getXxx()方法得到屬性值Field[] fields = t.getClass().getDeclaredFields();for (short i = 0; i < fields.length; i++) {PdfPCell cell = null;Field field = fields[i];String fieldName = field.getName();String getMethodName = "get"+ fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1);try {Class tCls = t.getClass();Method getMethod = tCls.getMethod(getMethodName,new Class[] {});Object value = getMethod.invoke(t, new Object[] {});// 判斷值的類型后進行強制類型轉換String textValue = null;if (value instanceof Boolean) {boolean bValue = (Boolean) value;textValue = "男";if (!bValue) {textValue = "女";}} else if (value instanceof Date) {Date date = (Date) value;SimpleDateFormat sdf = new SimpleDateFormat(pattern);textValue = sdf.format(date);} else if (value instanceof byte[]) {byte[] bsValue = (byte[]) value;Image img = Image.getInstance(bsValue);cell = new PdfPCell(img);} else {textValue = value.toString();}// 如果不是圖片數據,就當做文本處理if (textValue != null) {cell = new PdfPCell(new PdfParagraph(textValue));}cell.setHorizontalAlignment(Cell.ALIGN_CENTER);cell.setVerticalAlignment(Cell.ALIGN_MIDDLE);cell.setBorderColor(Color.green);table.addCell(cell);} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {// 清理資源}}}document.add(table);document.close();} catch (DocumentException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void main(String[] args) throws Exception {// 測試學生/*ExportPdf<Student> ex = new ExportPdf<Student>();String[] headers = { "學號", "姓名", "年齡", "性別", "出生日期" };java.util.List<Student> dataset = new ArrayList<Student>();dataset.add(new Student(10000001, "張三", 20, true, new Date()));dataset.add(new Student(20000002, "李四", 24, false, new Date()));dataset.add(new Student(30000003, "王五", 22, true, new Date()));OutputStream out = new FileOutputStream("E://Student.pdf");ex.exportPdf(headers, dataset, out);out.close();JOptionPane.showMessageDialog(null, "pdf導出成功!");*//****************************************************************************/// 測試圖書ExportPdf<Book> ex2 = new ExportPdf<Book>();String[] headers2 = { "圖書編號", "圖書名稱", "圖書作者", "圖書價格", "圖書ISBN","圖書出版社", "封面圖片" };java.util.List<Book> dataset2 = new ArrayList<Book>();try {BufferedInputStream bis = new BufferedInputStream(new FileInputStream("book_1.jpg"));byte[] buf = new byte[bis.available()];while ((bis.read(buf)) != -1) {//}dataset2.add(new Book(1, "jsp", "leno", 300.33f, "1234567","清華出版社", buf));dataset2.add(new Book(2, "java編程思想", "brucl", 300.33f, "1234567","陽光出版社", buf));dataset2.add(new Book(3, "DOM藝術", "lenotang", 300.33f, "1234567","清華出版社", buf));dataset2.add(new Book(4, "c++經典", "leno", 400.33f, "1234567","清華出版社", buf));dataset2.add(new Book(5, "c#入門", "leno", 300.33f, "1234567","湯春秀出版社", buf));OutputStream out2 = new FileOutputStream("E://Book.pdf");ex2.exportPdf(headers2, dataset2, out2);out2.close();JOptionPane.showMessageDialog(null, "pdf導出成功!");System.out.println("pdf導出成功!");} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}