一:工程截图:

二:项目运行截图:

三:源代码:

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();}}
}

Java和iText导出pdf文档相关推荐

  1. 【PDF】java使用Itext生成pdf文档--详解

    [API接口] 一.Itext简介 API地址:javadoc/index.html:如 D:/MyJAR/原JAR包/PDF/itext-5.5.3/itextpdf-5.5.3-javadoc/i ...

  2. java使用iText生成pdf文档的对齐方式

    一.前言 在企业的信息系统中,报表处理一直占比较重要的作用,本文将介绍一种生成PDF报表的Java组件--iText.通过在服务器端使用Jsp或JavaBean生成PDF报表,客户端采用超级连接显示或 ...

  3. Java:iText生成pdf文档

    依赖 <!-- pdf:start --> <dependency><groupId>com.itextpdf</groupId><artifac ...

  4. java用iText导出word文档

    1.需要导入的jar包 2.导出word并下载其实是分两步的. 第一步是将需要导出的数据导出(上传)到服务器上 第二步是将服务器上的文档下载到本地 3. 第一步.上传文档 (1)设置响应信息以及构造上 ...

  5. java pdf 首行缩进_java使用iText生成pdf文档的对齐方式

    一.前言 在企业的信息系统中,报表处理一直占比较重要的作用,本文将介绍一种生成PDF报表的Java组件--iText.通过在服务器端使用Jsp或JavaBean生成PDF报表,客户端采用超级连接显示或 ...

  6. Java导出PDF文档(模板导出和自定义)

    项目场景: 需要导出PDF文档,支持模板导出和自定义文档格式. 场景分析: PDF模板创建可使用表单域创建表单字段,引入数据填充,或者根据实际需要生成html转换成pdf. 解决方案: PDF模板可以 ...

  7. java 使用itext 导出pdf 控制图片的大小

    在使用itext 导出pdf 的过程中,可能会遇到这样的需求,就是导出文字加图片.使用我们前面写的程序,确实是可以导出图片,如果针对于类似简历的需求,图片填充单元格,会满足效果,如下图所示: 但在实际 ...

  8. itext操作pdf文档

    关于itext操作pdf文档 pdf基本操作 自己点击链接去看下就会了 java使用itext生成pdf 再不行,去看官方文档 itext Api 直接找到com.itextpdf.text.pdf这 ...

  9. java 使用itext导出PDF文件,中文不显示问题解决

    之前写的java 使用itext 导出pdf 发现有个问题,在今天使用的时候,发现一个问题,就是当单元格中写中文的时候,导出来的pdf中文不显示. java 使用itext导出PDF文件,图片文字左右 ...

最新文章

  1. 查看核心交换机CPU时的几个参数~~
  2. python开发网页有优势吗_Python用来做Web开发的优势有哪些
  3. Qt for ios 无证书真机调试
  4. FL2440移植LINUX-3.4.2 -- 按键驱动和触摸屏驱动移植
  5. corba的兴衰_数据科学薪酬的兴衰
  6. 一个会“说话”的油箱盖,告诉你每一滴油的去向
  7. Oracle 10g ORA-12154: TNS: could not resolve the connect identifier specified 问题解决!
  8. bat脚本交互输入_windows 10 如何设定计划任务自动执行 python 脚本?
  9. Svn常见问题及相关原因
  10. C语言编程题:(C语言)分糖果 通俗易懂
  11. ug打开服务器文件保存不了,UG编程时突然提示保存不了,你该怎么办,看这里...
  12. Python基础知识——变量与运算符
  13. 港科夜闻|香港科大汪扬教授轻松访谈:对话西泽投资管理主席刘央女士,倾听她跌宕起伏的30年投资生涯...
  14. 计算机磁盘管理和容量不一致,官方数据:为什么硬盘可用容量显示错误,以及硬盘容量与实际情况不符的原因...
  15. 程序员不可不知的版权协议
  16. 什么是MES生产管理和生产制造执行系统?有哪些系统模块组成?
  17. 用强化学习玩《超级马里奥》
  18. 《大型网站技术架构》——第一章 大型网站架构演化
  19. 西门子PLC S7-1200和Labview以太网通讯通讯周期20MS
  20. Drupal 系列一:如何快速学习 Drupal

热门文章

  1. JVM垃圾回收机制学习
  2. linux vi使用手册,史上最全VIM使用手册
  3. MFC之CAsyncSocket详解
  4. 蓝图中实现人物移动2
  5. qt for v210
  6. 点云数据生成三维模型_可直接编辑的高质量3D生成模型:三维深度生成方法SDM-NET...
  7. 智能机器人及其应用ppt课件_一文了解!伺服系统机理及其在工业机器人等领域的应用...
  8. .net开源框架简介和通用技术选型建议
  9. 一步步编写操作系统 46 linux的elf可执行文件格式1
  10. oracle 游标 904,如何解决Oracle数据库游标连接超出问题