第一次写博客,有很多不足的地方请多多指教,话不多说,直接上代码。

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

java导出表格PDF相关推荐

  1. java导出各种PDF文件(图片、表格、字体)

    java导出PDF文件(插入图片,表格,字体) 业务需求:需要根据系统里的各种数据动态生成PDF会议材料. 最终呈现图 思路 因为会议材料涉及各种数据,图片.同时还要有表格及字体样式的要求,所以需要用 ...

  2. java 导出表格打包zip文件下载_asyExcel导出excel并打包成zip压缩包下载

    假期期间自己在家撸码,刚好用到了导出,导出来之后是多个文件,所以需要打成压缩包并下载来给客户.查阅了一些资料,把这段代码贴在这,相当于有个记录吧. package com.business.testE ...

  3. java导出模板 pdf设置字体_有哪些相见恨晚的PPT模板网站?

    是时候祭出我用了好久的神器了! 作为公司的御用PPT写手,我曾经徘徊于各种形状和动画效果中,每每熬了一个通宵做出来的PPT,还得花几天时间来修改. 直到后来,我发现了这几个神器,PPT制作的效率提升了 ...

  4. java导出表格vsd_java 实现vsd转换为其它格式

    import java.io.File; import com.jacob.activeX.*; import com.jacob.com.Dispatch; import com.jacob.com ...

  5. java导出表格_java怎么导出excel表格

    import com.spire.xls.ExcelVersion; import com.spire.xls.Workbook; import com.spire.xls.Worksheet; pu ...

  6. java导出表格vsd_java - 如何使用Apache POI将vsd / vsdx文件转换为图像(例如jpg png) - 堆栈内存溢出...

    我正在使用apache poi读取doc / docx文件. 现在,我可以从文档文件中提取段落和图片. 当我的doc文件中有vsd时,如何将vsd转换为png图像? 我尝试了这个: private b ...

  7. java 导出表格打包zip文件下载_POI多个工作簿导出表格打包ZIP下载

    首先获得workbook集合对象 public static void zipFiles(List srcfile, File zipfile,String fileName) { try { Zip ...

  8. Java代码实现PDF中表格导出到Excel

    表格常见于 PDF 发票和财务报告中.您可能会遇到需要将 PDF 表格数据导出到 Excel 中的情况,以便您可以使用 MS Excel 提供的工具对数据进行分析.本文介绍了如何使用 Spire.Of ...

  9. java导出PDF、iText5导出漂亮表格PDF、导出指定格式水印PDF

    我们在项目当中经常要导出pdf文档,pdf文档还要按一定的格式导出,以下介绍导出pdf文档功能: 1)支持A4纸大小导出 2)指定文字显示的位置 3)支持表格展示数据 4)添加水印 开源下载 java ...

最新文章

  1. python计算机_基础python计算机知识
  2. 根据经纬度计算范围_遗传算法可视化项目(插曲):关于距离的计算
  3. Spring【AOP模块】就是这么简单
  4. python计算某年某月多少天_Python编程实现输入某年某月某日计算出这一天是该年第几天的方法...
  5. Java后台与VUE跨域交接
  6. python分支语句_Python中分支语句与循环语句实例详解
  7. 为什么只看重结果_买家下单最看重的三项服务,做好这三点,让你的销量涨涨涨...
  8. kafka基本概念和hello world搭建
  9. atom配置python环境_用Python制作网站Django实操与开发环境配置
  10. mysql id自动增长_MySQL中的6种约束,你掌握了几种?
  11. python学习手册记录
  12. Unity3D 性能优化
  13. python3 数据挖掘 之 爬取 智联招聘网站来巩固pandas
  14. Windows10无法启动windows安全中心服务怎么办?
  15. 工作一年心路历程及个人感悟
  16. 安卓10源码添加系统服务后配置SeLinux让其拥有Sdcard读写权限
  17. win10亮度怎么调_笔记本屏幕亮度怎么调
  18. 浏览器放大缩小,页面布局不变,浏览器放大百分比,页面放大到左上角,浏览器缩小百分比,页面缩小至中间(类似csdn官网效果)
  19. 少年碎碎念:《WHOLENESS》
  20. 计算机网络安全工作室介绍,计算机网络技术专业 “网络工作室”做法简介

热门文章

  1. 揭阳市、汕尾市楹联学会举行上巳雅集暨“大洋杯” 征联颁奖典礼
  2. 计算机专业中真理的作用,马克思主义哲学对计算机专业学习的指导作用.doc
  3. 汉塞尔曼的奇妙时事通讯:2013年10月14日
  4. 无字天书之Python爬虫第一页
  5. ubuntu 学习资料整理
  6. 要如何禁止键盘钩子?
  7. 半入耳的蓝牙耳机哪个好?半入耳式蓝牙耳机排名
  8. 都1202年了,阿里五岳版的《Java开发手册》你还没拜读过?
  9. 【线性回归】复习笔记
  10. 线jsp版泰囧表情的生成器代码,不用PS也能恶搞。