需要这四个包
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import com.growatt.oss.method.OUtils;
import com.growatt.oss.method.pdf.PDFUtils;
import com.growatt.oss.system.StaticParamUtils;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;
/**
* itext5工具类
* @author tsp
*
*/
public class iTextUtils {
//副标题缩进
public static final int TITLE_RETRACT_FIVE = 75;
public static final int TITLE_RETRACT_LOSE_ZERO = -30;
/**
* 基础信息
* @param document
* @param startDate 开始时间
* @param endDate 结束数据 没有就输出1
* @param userDeviceType 用户类型
* @param areaId 区域
* @param countryId 国家
* @throws DocumentException
* @throws IOException
*/
public static void getConText(Document document,String startDate,String endDate,
String userDeviceType,String areaId,String countryId,String themeName,int retract) throws DocumentException, IOException{
//获取系统日期
SimpleDateFormat sFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date(System.currentTimeMillis());
String date_time = sFormat.format(date);
String title_name = themeName+"_"+date_time;
BaseFont bfChinese = iTextUtils.getBaseFont(); //设置中文字体
Font title_font = new Font(bfChinese,20,Font.BOLD); //标题字体
Font normal_font1 = new Font(bfChinese,12,Font.NORMAL); //数据字体
Font normal_font2 = new Font(bfChinese,12,Font.BOLD); //数据字体
Paragraph title = new Paragraph(title_name,title_font); //添加标题字体
title.setAlignment(1); //文本居中
document.add(title);
iTextUtils.getBlank(document);
iTextUtils.getTitleBasic(document,"基础信息",retract); //添加副标题
List<Object> list = new ArrayList<Object>();
list.add("时间段");list.add("用户类型");list.add("区域/国家");list.add("生成报表日期");
if (endDate.equals("1")) {
list.add(startDate); //查询的日期
}else{
list.add(startDate+"~"+endDate); //查询的日期
}
if (!OUtils.isEmpty(userDeviceType)) {
String[] type = userDeviceType.split(",");
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < type.length; i++) {
switch (type[i]) {
case "0":
sb.append("光伏用户");
break;
case "1":
sb.append("离网储能用户");
break;
case "2":
sb.append("光伏+储能用户");
break;
case "3":
sb.append("储能用户");
break;
case "4":
sb.append("智慧家庭用户");
break;
case "5":
sb.append("自发自用用户");
break;
default:
if (type[i].equals("16")) {
sb.append("普通逆变器");
}else if (type[i].equals("17")) {
sb.append("MIX");
}else if (type[i].equals("18")) {
sb.append("MAX");
}else if (type[i].equals("19")) {
sb.append("SPA");
}else if (type[i].equals("22")) {
sb.append("TLX");
}else if (type[i].equals("96")) {
sb.append("储能机");
}
break;
}
sb.append(" \n");
}
list.add(sb.toString());
}else{
list.add("不限");
}
if (!OUtils.isEmpty(areaId)||!OUtils.isEmpty(countryId)) {
countryId = StaticParamUtils.getCountryText(OUtils.parseInt(countryId), "cn");//获取国家名字
areaId = StaticParamUtils.getAreaText(OUtils.parseInt(areaId), "cn");//获取区域名字
list.add(areaId+"/"+countryId);
}else{
list.add("不限");
}
list.add(date_time);
PdfPTable table = new PdfPTable(4);
for (int i = 0; i < list.size(); i++) {
PdfPCell cell = new PdfPCell();
String chunlName = (String)list.get(i);
Chunk chunk = null;
if (i<4) {
chunk = new Chunk(chunlName,normal_font2); //文本块
}else{
chunk = new Chunk(chunlName,normal_font1); //文本块
}
cell.addElement(chunk);
cell.setBorder(0);
cell.setUseDescender(true);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);//设置字体水平居中
table.addCell(cell);
}
if (retract < 0) {
table.setWidthPercentage(108);
}
float[] columnWidths = {1f,0.6f,0.6f,0.6f};
table.setWidths(columnWidths);
document.add(table);
}
/**
* 添加副标题
* @param document 文档
* @param name 副标题名字
* @throws DocumentException
* @throws IOException
*/
public static void getTitleBasic(Document document, String name, int retract) throws DocumentException, IOException{
BaseFont bf = getBaseFont();
Font title_subheading_font = new Font(bf,17,Font.BOLD); //字体
Chunk temp_bule = new Chunk(" ",title_subheading_font); //文本蓝色小块
temp_bule.setBackground(new BaseColor(100 ,149 ,237)); //文本背景颜色
Chunk temp_blank = new Chunk(" ",title_subheading_font); //文本空白
Chunk temp_name = new Chunk(name,title_subheading_font); //文本标题文字
Paragraph paragraph = new Paragraph(); //段落
paragraph.add(temp_bule);
paragraph.add(temp_blank);
paragraph.add(temp_name);
paragraph.setFirstLineIndent(retract); //缩进
document.add(paragraph);
Font font = new Font(getBaseFont(),17,Font.BOLD);
Paragraph temp = new Paragraph(" ",font);
document.add(temp);
//getBlank(document); //添加空白段落
}
/**
* 添加图片
* @param charPath 图片路径和名称
* @param document
* @throws DocumentException
* @throws MalformedURLException
* @throws IOException
*/
public static void addChart(String charPath,Document document) throws DocumentException, MalformedURLException, IOException{
Image image = Image.getInstance(charPath);
image.scaleToFit(630f, 730f); //图片大小
image .setAlignment(Image.MIDDLE); //图片居中
document.add(image);
getDeleteFile(charPath); //删除存留在系统里的图片
}
/**
* 添加空表段落
* @param document
* @throws DocumentException
* @throws IOException
*/
public static void getBlank(Document document) throws DocumentException,IOException {
Font font = new Font(getBaseFont(),20,Font.BOLD);
Paragraph temp = new Paragraph(" ",font);
//Chunk temp = new Chunk(" ",FontFactory.getFont(FontFactory.HELVETICA, 20, Font.NORMAL)); //空白
document.add(temp);
}
/**
* 添加虚线
* @param document
* @throws DocumentException
* @throws IOException
*/
public static void getLineSeparator(Document document) throws DocumentException, IOException{
//1.线宽度
//2.直线长度,是个百分百,0-100之间
//3.直线颜色
//4.直线位置
//5.上下移动位置
LineSeparator line = new LineSeparator(1.2f,80,new BaseColor(190,190,190),1,0f); //虚线
Font line_font = new Font(getBaseFont(),26,Font.BOLD); //空白字体
Paragraph paragraph_temp = new Paragraph(" ",line_font); //空白段落
document.add(paragraph_temp);
document.add(line);
document.add(paragraph_temp);
}
/**
* 将两个图片并列在表格里
* @param document 文本
* @param listName 标题数组
* @param listPath 路径数组
* @param columnWidths 单元格大小数组
* @throws DocumentException
* @throws IOException
*/
public static void getTableAndImage(Document document,String[] listName, String[] listPath,float[] columnWidths) throws DocumentException, IOException{
PdfPTable table = new PdfPTable(4);
BaseFont bf = getBaseFont();
Font table_font = new Font(bf,14,Font.BOLD);
Chunk table_blank = new Chunk(" ",table_font); //文本空白
//空白
for (int i =0 ; i<4; i++) {
PdfPCell cell = new PdfPCell();
cell.addElement(table_blank);
cell.setBorderWidth(1.1f);
cell.setBorderColor(new BaseColor(190,190,190)); //边框颜色
if (i==0) {
cell.disableBorderSide(14);
}else if (i == 1) {
cell.disableBorderSide(6);
}else if (i == 2) {
cell.disableBorderSide(10);
}else if (i == 3){
cell.disableBorderSide(14);
}
table.addCell(cell);
}
Font title_subheading_font = new Font(bf,17,Font.BOLD);
Chunk temp_bule = new Chunk(" ",title_subheading_font); //文本蓝色小块
temp_bule.setBackground(new BaseColor(100 ,149 ,237)); //文本背景颜色
Chunk temp_blank = new Chunk(" ",title_subheading_font); //文本空白
for (int i =0 ; i<4; i++) {
PdfPCell cell = new PdfPCell();
if (i==0) {
Chunk temp_name = new Chunk(listName[0],title_subheading_font); //文本标题文字
Paragraph paragraph = new Paragraph();
paragraph.add(temp_bule);
paragraph.add(temp_blank);
paragraph.add(temp_name);
cell.addElement(paragraph);
cell.disableBorderSide(15);
}else if(i==3){
Chunk temp_name = new Chunk(listName[1],title_subheading_font); //文本标题文字
Paragraph paragraph = new Paragraph();
paragraph.add(temp_bule);
paragraph.add(temp_blank);
paragraph.add(temp_name);
cell.addElement(paragraph);
cell.disableBorderSide(15);
}else if(i==1){
cell.addElement(temp_blank);
cell.disableBorderSide(7);
}else if(i==2){
cell.addElement(temp_blank);
cell.disableBorderSide(11);
}
cell.setBorderWidth(1.1f);
cell.setBorderColor(new BaseColor(190,190,190)); //边框颜色
table.addCell(cell);
}
for (int i =0 ; i<4; i++) {
PdfPCell cell = new PdfPCell();
cell.addElement(temp_blank);
cell.setBorderWidth(1.1f);
cell.setBorderColor(new BaseColor(190,190,190)); //边框颜色
if (i==0) {
cell.disableBorderSide(15);
}else if(i==1){
cell.disableBorderSide(7);
}else if(i==2){
cell.disableBorderSide(11);
}else if(i==3){
cell.disableBorderSide(15);
}
table.addCell(cell);
}
for (int i =0 ; i<4; i++) {
PdfPCell cell = new PdfPCell();
if (i==0) {
Image image = Image.getInstance(listPath[0]);
cell.addElement(image);
cell.disableBorderSide(15);
}else if(i == 3){
Image image = Image.getInstance(listPath[1]);
cell.addElement(image);
cell.disableBorderSide(15);
}else if(i==1){
cell.disableBorderSide(7);
}else if(i==2){
cell.disableBorderSide(11);
}
cell.setBorderWidth(1.1f);
cell.setBorderColor(new BaseColor(190,190,190)); //边框颜色
table.addCell(cell);
}
//空白
for (int i =0 ; i<4; i++) {
PdfPCell cell = new PdfPCell();
cell.addElement(table_blank);
cell.setBorderWidth(1.1f);
cell.setBorderColor(new BaseColor(190,190,190)); //边框颜色
if (i==0) {
cell.disableBorderSide(13);
}else if(i == 1){
cell.disableBorderSide(5);
}else if(i == 2){
cell.disableBorderSide(9);
}else if(i == 3){
cell.disableBorderSide(13);
}
table.addCell(cell);
}
//单元格的大小
if (columnWidths.length != 0) {
float[] coloum = new float[4];
for(int i = 0; i<4; i++){
if (i == 0) {
coloum[i] = columnWidths[0];
}else if(i == 3){
coloum[i] = columnWidths[1];
}else{
coloum[i] = 0.1f;
}
}
table.setWidths(coloum);
}else{
float[] coloum = {1f,0.1f,0.1f,1f};
table.setWidths(coloum);
}
document.add(table);
iTextUtils.getBlank(document);
}
/**
* 创建有边框表格
* @param width 表格的大小 为null则默认大小
* @param list 数据
* @param count 列数
* @param document
* @throws DocumentException
* @throws IOException
*/
public static void getCreateTable(Document document,Integer width,List<?> list,int count) throws DocumentException, IOException{
BaseFont bfChinese = getBaseFont();
Font normal_font = new Font(bfChinese,10,Font.NORMAL);//数据字体
Font tetle_font = new Font(bfChinese,10,Font.BOLD);//数据字体
PdfPTable table = new PdfPTable(count);
for (int i = 0; i < list.size(); i++) {
PdfPCell cell = new PdfPCell();
String chunlName = list.get(i).toString();
if (i < count) {
Chunk chunk = new Chunk(chunlName,tetle_font); //标题
cell.addElement(chunk);
cell.setBackgroundColor(new BaseColor(232,232,232)); //背景
}else{
Chunk chunk = new Chunk(chunlName,normal_font); //文本块
cell.addElement(chunk);
}
cell.setBorderColor(new BaseColor(190,190,190)); //单元格边框颜色
cell.setUseDescender(true); //是否居中
table.addCell(cell);
}
table.setHorizontalAlignment(1);
//自动把列扩大缩小
if (count>=10) {
float[] columnWidths = new float[count];
for (int i = 0; i < count; i++) {
if (i>1) {
String name = (String)list.get(i);
int num = name.length();
if (num==4) {
columnWidths[i] = 0.75f;
}else if(num>4 && num<7){
columnWidths[i] = 1f;
}else if (num>6 && num<9) {
columnWidths[i] = 1.35f;
}
}else{
if (i == 0) {
columnWidths[i] = 0.4f;
}else{
columnWidths[i] = 1f;
}
}
}
table.setWidths(columnWidths);
}
if (width != null) { //为null则默认大小
table.setWidthPercentage(width);
}
document.add(table);
getBlank(document);
}
/**
* 用做设置生命周期导出
* 添加副标题
* @param document 文档
* @param name 副标题名字
* @throws DocumentException
* @throws IOException
*/
public static void getTitleBasic1(Document document, String name) throws DocumentException, IOException{
BaseFont bf = getBaseFont();
Font title_subheading_font = new Font(bf,12,Font.BOLD);
Paragraph paragraph = new Paragraph(name,title_subheading_font);
paragraph.setFirstLineIndent(10); //缩进
document.add(paragraph);
Paragraph temp = new Paragraph(" ",FontFactory.getFont(FontFactory.HELVETICA, 10, Font.NORMAL)); //空白
document.add(temp);
}
/**
* 关闭iText
* @param document 文档
* @param writer 书写器
* @throws DocumentException
* @throws FileNotFoundException
*/
public static void getAllClose(Document document, PdfWriter writer) throws DocumentException, FileNotFoundException{
//关闭文档
document.close();
//关闭书写器
writer.close();
}
/**
* 设置java适应字体
* @return
* @throws DocumentException
* @throws IOException
*/
public static BaseFont getBaseFont() throws DocumentException, IOException{
return BaseFont.createFont(PDFUtils.class.getResource("/pdf/simsun.ttc").getFile()+",1",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}
/**
* 删除图片
* @param path
*/
public static void getDeleteFile(String path){
try {
File file = new File(path);
file.delete();
} catch (Exception e) {
System.out.println("Exception occured");
e.printStackTrace();
}
}
/**
* 用户下载并把文件名输出为中文
* @param response
* @param file
* @param fileName
*/
public static void downLoadPDFFile(HttpServletResponse response,File file,String fileName){
try {
// response.setCharacterEncoding("UTF-8");
response.setContentType("application/pdf");// 设置输出格式头信息
// response.setHeader("Content-Disposition", "attachment; filename="+fileName+".pdf"+";target=_blank");
response.addHeader("Content-Disposition", "attachment; filename=" +new String(fileName.getBytes("utf-8"),"iso-8859-1")+ ".pdf");
OutputStream os;
os = response.getOutputStream();
FileUtils.copyFile(file, os);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 创建无边框表格
* @param document
* @param width
* @param list
* @param count
* @throws DocumentException
* @throws IOException
*/
public static void getCreateFramelessTable(Document document,List<?> list,int count) throws DocumentException, IOException{
Font normal_font = new Font(getBaseFont(),10,Font.NORMAL);//数据字体
PdfPTable table = new PdfPTable(count);
for (int i = 0; i < list.size(); i++) {
PdfPCell cell = new PdfPCell();
String chunlName = list.get(i).toString();
Chunk chunk = new Chunk(chunlName,normal_font);
cell.addElement(chunk);
cell.setBorderWidth(0); //边框代销 为0无边框
cell.setUseDescender(true); //是否居中
table.addCell(cell);
}
table.setWidthPercentage(100);
document.add(table);
}
/**
* 创建无左右边框的表格
* @param document
* @param width
* @param list
* @param count
* @throws DocumentException
* @throws IOException
*/
public static void getCreateFramelessAroundTable(Document document,List<?> list,int count) throws DocumentException, IOException{
Font normal_font = new Font(getBaseFont(),10,Font.NORMAL);//数据字体
PdfPTable table = new PdfPTable(count);
for (int i = 0; i < list.size(); i++) {
PdfPCell cell = new PdfPCell();
String chunlName = String.valueOf(list.get(i));
Chunk chunk = new Chunk(chunlName,normal_font);
cell.addElement(chunk);
cell.setBorderColor(new BaseColor(176,196,222)); //边框颜色
cell.disableBorderSide(12);
cell.setUseDescender(true); //是否居中
if (i<count) {
cell.setFixedHeight(22);
cell.setBackgroundColor(new BaseColor(176,196,222)); //背景色
}
table.addCell(cell);
}
table.setWidthPercentage(100);
document.add(table);
}
/**
* 判断为null
* @param s
* @return
*/
public static String isNull(Object o){
return o == null ? " " : o.toString();
}
}