第一次写博客,有很多不足的地方请多多指教,话不多说,直接上代码。
1.建立PDF模板
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import java.awt.Color;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* <p>Title: 生成PDF文件</p>
* <p>Description: 本实例通过使用iText包生成一个表格的PDF文件</p>
* <p>Copyright: Copyright (c) 2018</p>
* <p>Filename: DbspreadDataPDF.java</p>
* @author ly
* @version 1.0
*/
public class DbspreadDataPDF {
/**
*<br>方法说明:写PDF文件
*<br>输入参数:
*<br>返回类型:
*@param pdfname 文件名称
*@param headName 表头名称
*@param headcount 表头信息
*@param list 数据源
*@param names 对应数据源的属性
*/
public void write(HttpServletRequest request, HttpServletResponse response,String pdfname,String headName,String headcount[],List<Map<String, Object>> list,String[] names){
try{
Document document=new Document(PageSize.A4, 50, 50, 100, 50);
Rectangle pageRect=document.getPageSize();
response.setContentType("application/x-msdownload;charset=UTF-8");
response.setHeader("Content-Disposition","attachment;filename="+pdfname+"");
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
//创建汉字字体
BaseFont bfSong = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
Font fontSong = new Font(bfSong, 10, Font.NORMAL);
// 为页增加页头信息
HeaderFooter header = new HeaderFooter(new Phrase(""+headName+"",fontSong), false);
header.setBorder(2);
header.setAlignment(Element.ALIGN_RIGHT);
document.setHeader(header);
// 为页增加页脚信息
HeaderFooter footer = new HeaderFooter(new Phrase("第 ",fontSong),new Phrase(" 页",fontSong));
footer.setAlignment(Element.ALIGN_CENTER);
footer.setBorder(1);
document.setFooter(footer);
// 打开文档
document.open();
//构造表格
Table table = new Table(headcount.length);
table.setAlignment(Element.ALIGN_MIDDLE);
table.setBorder(Rectangle.NO_BORDER);
int hws[] = new int[headcount.length] ;
for (int i = 0; i < headcount.length; i++) {
hws[i]=20;
}
table.setWidths(hws);
table.setWidth(100);
//表头信息
for (String i : headcount) {
Cell cellleft= new Cell(new Phrase(i,new Font(bfSong, 10, Font.ITALIC,new Color(0,0,255))));
cellleft.setUseAscender(true);
cellleft.setColspan(1);
cellleft.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置字体垂直居中;
cellleft.setHorizontalAlignment(Element.ALIGN_CENTER);//设置字体水平居中,只能通过cell来居中;
table.addCell(cellleft);
}
//收货和订货人信息,表体内容
for (Map<String, Object> map : list) {
for (int i = 0; i < names.length; i++) {
if (map.get(names[i]) != null) {
Cell cellleft= new Cell(new Phrase(map.get(names[i]).toString(),fontSong));
cellleft.setUseAscender(true);
cellleft.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置字体垂直居中;
cellleft.setHorizontalAlignment(Element.ALIGN_CENTER);//设置字体水平居中,只能通过cell来居中;
table.addCell(cellleft);
}else{
Cell cellleft= new Cell(new Phrase("",fontSong));
cellleft.setUseAscender(true);
cellleft.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置字体垂直居中;
cellleft.setHorizontalAlignment(Element.ALIGN_CENTER);//设置字体水平居中,只能通过cell来居中;
table.addCell(cellleft);
}
}
}
//将表格添加到文本中
document.add(table);
//关闭文本,释放资源
document.close();
}catch(Exception e){
System.out.println(e);
}
}
}
2.我们写一个测试类
public static void main(String[] args) {
List<T> list=new ArrayList<T>(); //建立一个list集合,将你的数据源存储到改历史集合中
List<Map<String, Object>> dbServicestypesMaplist = new ArrayList<Map<String,Object>>();
dbServicestypesMaplist = BeanToMapUtil.convertListBean2ListMap(list,A.class);//将list集合转换成list map集合
DbspreadDataPDF dbspreadDataPDF=new DbspreadDataPDF();
String pdfname = Sys.getCtime()+".pdf";
String headName="用户统计";
String[] headcount={"编号","用户名","地址","手机号"};
String[] names={"sid","username","address","phone"};
dbspreadDataPDF.write(request, response, pdfname, headName, headcount, dbServicestypesMaplist, names);
}
3.Map 对象与 JavaBean 对象互转工具类
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Map 对象与 JavaBean 对象互转工具类
*/
public class BeanToMapUtil<T> {
private BeanToMapUtil()
{
// 私有的构造方法
}
/**
* 将一个 JavaBean 对象转化为一个 Map
*
* @param bean
* @return
* @throws IntrospectionException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static Map<String, Object> convertBean2Map(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
Class<? extends Object> type = bean.getClass();
Map<String, Object> returnMap = new HashMap<>();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!"class".equals(propertyName)) {
if (propertyName.contains("time")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null) {
Timestamp ts = Timestamp.valueOf(result.toString());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
result = sdf.format(ts);
returnMap.put(propertyName, result);
} else {
returnMap.put(propertyName, null);
}
} else {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null) {
returnMap.put(propertyName, result);
} else {
returnMap.put(propertyName, null);
}
}
}
}
return returnMap;
}
/**
* 将 List<JavaBean>对象转化为List<Map>
*
* @param beanList
* @return
* @throws Exception
*/
public static <T> List<Map<String, Object>> convertListBean2ListMap(List<T> beanList, Class<T> T) throws Exception {
List<Map<String, Object>> mapList = new ArrayList<>();
for (int i = 0, n = beanList.size(); i < n; i++) {
Object bean = beanList.get(i);
Map<String, Object> map = convertBean2Map(bean);
mapList.add(map);
}
return mapList;
}
}