1.自定义注解部分代码:
package com.fitk.emis.corp.export_Util.itextpdf.pdf;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)//表示这个注解只能用到属性
@Retention(RetentionPolicy.RUNTIME)//表示这个注解在运行时会存在,自定义注解一般设置为这个值
public @interface PdfColumn {
/**
* @Title: title
* @Description: 表头列名 必填
*/
public String title();
/**
* 序号,如果为负号,则代表有行重叠
*/
public int sort();
/**
当序号重复,就是行叠加
*/
public String sort_row() default "";
/**
* @Title: width
* @Description: 列宽 默认15
*/
public float width() default 0.15f;
/**
* @Title: width
* @Description: 列高 默认30
*/
public int height() default 30;
public enum Alignment {
LEFT(0), ALIGN_CENTER(1), RIGHT(2);
private int value;
private Alignment(int value) {
this.value = value;
}
public int getValue() {
return value;
}
};
/**
* @Title: alignment
* @Description: 文字样式 默认居中(Alignment.CENTER)
*/
public PdfColumn.Alignment alignment() default Alignment.ALIGN_CENTER;
// /**
// * @Title: boder
// * @Description: 单元格是否需要边框 环绕包围 默认true
// */
// public boolean boder() default true;
// public enum StyleColor {
// WHITE(0x9), BLACK(0x8), BLUE(0xc), RED(0xa), YELLOW(0xd);
// private int value;
//
// private StyleColor(int value) {
// this.value = value;
// }
// public int getValue() {
// return value;
// }
// };
// /**
// * @Title: styleColor
// * @Description: 单元格背景色 默认白色
// */
// public ExcelColumn.StyleColor styleColor() default ExcelColumn.StyleColor.WHITE;
//
// public enum FontColor {
// BLACK(0x8), BLUE(0xc), RED(0xa), YELLOW(0xd);
// private int value;
//
// private FontColor(int value) {
// this.value = value;
// }
// public int getValue() {
// return value;
// }
// };
// /**
// * @Title: fontColor
// * @Description: 文字颜色 默认黑色(FontColor.BLACK) 暂支持 BLACK BLUE RED YELLO
// */
// public ExcelColumn.FontColor fontColor() default ExcelColumn.FontColor.BLACK;
/**
* @Title: fontSize
* @Description: 字号大小 默认10
*/
public int fontSize() default 10;
/**
* @Title: fontName
* @Description: 字体 默认微软雅黑
*/
public String fontName() default "微软雅黑";
}
2.例子实体类部分
package com.fitk.emis.corp.entity.bmpl_old;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.fitk.emis.corp.export_Util.itextpdf.pdf.PdfColumn;
import com.fitk.emis.corp.service.my_join_exp.pdf.MyPdfColumn;
import lombok.Data;
import java.io.Serializable;
/**
* 用来查询检修记录表的,这里其实也可以当成检修线入库轴承对象
* @TableName V_OH_JX_RECORD
*/
@TableName(value ="V_OH_JX_RECORD")
@Data
public class list_v_oh_jxRecord implements Serializable {
//默认设置值
private static final String[] myTitle = new String[]{"轴承编号","检修自互检(标记,通气栓)","附件检修自互检","注脂(g)","注脂自互检","人工组装自互检","外圈外径(mm)","内圈内径(mm)"
,"后挡圈(mm)","挡油环(mm)","测量自互检"};
/**
*
*/
@MyPdfColumn(title = "NO.",sort=1)
private String no;
private String brgId;
/**
*
*/
@PdfColumn(title = "轴承编号",width = 30,sort=1,fontSize=10)
@MyPdfColumn(title = "轴承编号",sort=2)
private String zcbh;
/**
*
*/
@PdfColumn(title = "检修自互检(标记,通气栓)",width = 30,sort=2,fontSize=10)
private String face01Man;
/**
*
*/
@PdfColumn(title = "检修自互检(标记,通气栓)",width = 30,sort=3,fontSize=10)
private String face02Man;
//复检检修自互检 (暂时空着)
@PdfColumn(title = "附件检修自互检",width = 15,sort=4,fontSize=10)
private String fujian1_man;
/**
*
*/
@PdfColumn(title = "附件检修自互检",width = 15,sort=5,fontSize=10)
private String fujian2_man;
/**
*
*/
@PdfColumn(title = "注脂(g)",width = 15,sort=-6,fontSize=10,sort_row = "6_1")
private String oilWeightNqa;
/**
*
*/
@PdfColumn(title = "注脂(g)",width = 15,sort=-6,fontSize=10,sort_row = "6_2")
private String oilWeightNqb;
/**
*
*/
@PdfColumn(title = "注脂(g)",width = 15,sort=-6,fontSize=10,sort_row = "6_3")
private String oilWeightWq;
/**
*
*/
@PdfColumn(title = "注脂自互检",width = 15,sort=7,fontSize=10)
private String oil_zzzj;
@PdfColumn(title = "注脂自互检",width = 15,sort=8,fontSize=10)
private String oil_zzhj;
/**
*
*/
private String newOh;
/**
*
*/
@PdfColumn(title = "人工组装自互检",width = 30,sort=9,fontSize=10)
private String completeMan;
//互检暂时是空的
// @PdfColumn(title = "人工组装自互检",width = 15,sort=10,fontSize=10)
private String completeMan2;
/**
*
*/
@PdfColumn(title = "外圈外径(mm)",width = 15,sort=-10,fontSize=10,sort_row = "10_1")
private String wqwja;
/**
*
*/
@PdfColumn(title = "外圈外径(mm)",width = 15,sort=-10,fontSize=10,sort_row = "10_2")
private String wqwjb;
/**
*
*/
@MyPdfColumn(title = "外圈外径平均值(mm)",sort=3)
@PdfColumn(title = "外圈外径(mm)",width = 15,sort=-10,fontSize=10,sort_row = "10_3")
private String wqwjavg;
/**
*
*/
@PdfColumn(title = "内圈内径(mm)",width = 15,sort=-11,fontSize=10,sort_row = "11_1")
private String nqnja;
/**
*
*/
@PdfColumn(title = "内圈内径(mm)",width = 15,sort=-11,fontSize=10,sort_row = "11_2")
private String nqnjb;
/**
*
*/
@MyPdfColumn(title = "内圈内径平均值(mm)",sort=4)
@PdfColumn(title = "内圈内径(mm)",width = 15,sort=-11,fontSize=10,sort_row = "11_3")
private String nqnjavg;
/**
*
*/
@MyPdfColumn(title = "后挡圈(mm)",sort=5)
@PdfColumn(title = "后挡圈(mm)",width = 15,sort=12,fontSize=10)
private String hdqnj;
/**
*
*/
@MyPdfColumn(title = "挡油环(mm)",sort=6)
@PdfColumn(title = "挡油环(mm)",width = 15,sort=13,fontSize=10)
private String dyhnj;
//暂时为空
@PdfColumn(title = "测量自互检(mm)",width = 15,sort=14,fontSize=10)
private String clman;
@PdfColumn(title = "测量自互检(mm)",width = 15,sort=15,fontSize=10)
private String checkCjMan;
private String dyhwj;
/**
*
*/
private String hdqwj;
/**
*
*/
private String lastSysPk;
/**
*
*/
private String isSt;
/**
*
*/
private String isStDesc;
/**
*
*/
private String zcxh;
/**
*
*/
private String zcxhDesc;
/**
*
*/
private String zcxc;
/**
*
*/
private String zcxcDesc;
/**
*
*/
private String lieCode;
/**
*
*/
private String carCode;
/**
*
*/
private String informCode;
/**
*
*/
private String isAxes;
/**
*
*/
private String isAxesDesc;
/**
*
*/
private String axesCode;
/**
*
*/
private String wheelCode;
/**
*
*/
private String wheelDir;
/**
*
*/
private String woPk;
/**
*
*/
private String trainNo;
/**
*
*/
private String trainType;
/**
*
*/
private String carNo;
/**
*
*/
private String projectName;
/**
*
*/
private String woName;
/**
*
*/
private String wbsName;
/**
*
*/
private String jjPeople;
/**
*
*/
private String jjDate;
/**
*
*/
private String isTrans;
/**
*
*/
private String isTransDesc;
/**
*
*/
private String lastDt;
/**
*
*/
private String ticketPaper;
/**
*
*/
private String wheelNum;
/**
*
*/
private String repaireItemNum;
/**
*
*/
private String instanceName;
/**
*
*/
private String instanceSerialNum;
/**
*
*/
private String creationDate;
/**
*
*/
private String woXc;
public String getOilWeightNqa() {
return "A:"+oilWeightNqa;
}
public String getOilWeightNqb() {
return "B:"+ oilWeightNqb;
}
public String getOilWeightWq() {
return "中间:"+ oilWeightWq;
}
public String getWqwja() {
return "A:"+wqwja;
}
public String getWqwjb() {
return "B:"+wqwjb;
}
public String getWqwjavg() {
return "平均:"+wqwjavg;
}
public String getNqnja() {
return "A:"+nqnja;
}
public String getNqnjb() {
return "B:"+nqnjb;
}
public String getNqnjavg() {
return "平均:"+nqnjavg;
}
public String getDyhwj() {
return dyhwj;
}
public String getDyhnj() {
return dyhnj;
}
public String getHdqwj() {
return hdqwj;
}
public String getHdqnj() {
return hdqnj;
}
public String getCheckCjMan() {
return checkCjMan;
}
public String getCompleteMan() {
return completeMan;
}
public String getOil_zzzj() {
if(oil_zzzj==null){
return "点检";
}
return oil_zzzj;
}
public String getClman() {
if(clman==null){
return "点检";
}
return clman;
}
public static String[] getMyTitle() {
return myTitle;
}
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}
3.工具类,还没完善,有时间可以自己把一些参数提出来让调用者来设置减小耦合。
package com.fitk.emis.corp.export_Util.itextpdf.pdf;
import com.baomidou.mybatisplus.annotations.TableField;
import com.fitk.emis.corp.entity.bmpl_old.list_v_oh_jxRecord;
import com.fitk.emis.corp.entity.home.list_exp_col;
import com.itextpdf.text.*;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class CreatePDFUtils1<T> {
public Logger log = LoggerFactory.getLogger(CreatePDFUtils1.class);
public Document document;
public Class clazz;
//默认字体大小10
public Float font_size=10f;
//默认不加粗
public int font_sty=Font.NORMAL;
//创建字体(默认)
public BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
//字体大小加粗设置
public Font size14_Bfont=new Font(baseFont,14,Font.BOLD); //14号加租字体
public Font size14font=new Font(baseFont,14,Font.NORMAL); //14号正常字体
public Font size16font=new Font(baseFont,16,Font.NORMAL); //14号正常字体
public Font size18font=new Font(baseFont,18,Font.NORMAL); //14号正常字体
public Font size12_Bfont=new Font(baseFont,12,Font.BOLD); //12号加租字体
public Font size12font=new Font(baseFont,12,Font.NORMAL); //12号正常字体
public Font size11font=new Font(baseFont,10,Font.NORMAL); //11号正常字体
public Font size10_Bfont=new Font(baseFont,10,Font.BOLD); //10号加租字体
public Font size10font=new Font(baseFont,10,Font.NORMAL); //10号正常字体
public Font size8_Bfont=new Font(baseFont,8,Font.BOLD); //10号加租字体
public Font size8font=new Font(baseFont,8,Font.NORMAL); //10号正常字体
public Font size7_Bfont=new Font(baseFont,7,Font.BOLD); //7号加粗字体
public Font size7font=new Font(baseFont,7,Font.NORMAL); //7号正常字体
public Font size6_Bfont=new Font(baseFont,6,Font.BOLD); //6号加粗字体
public Font size6font=new Font(baseFont,6,Font.NORMAL); //6号正常字体
//默认字体
public Font size_natural=new Font(baseFont,font_size,font_sty);
//默认表头字体
public Font size_titleFont=new Font(baseFont,10,Font.NORMAL); //10号加租字体
//默认表尾字体
public Font size_footerFont=size8font;
//默认字段头字体
public Font size_filed_Header_font=size7font;
//默认内容体字体
public Font size_filed_Body_font=size7font;
//默认行高
public int row_Height=15;
//默认行高(表头)
public int row_Height_title=20;
//默认行高(数据字段表头)
public int row_Height_header=15;
//默认行高(数据)
public int row_Height_body=18;
//默认行高(表尾)
public int row_Height_footer=15;
//默认行宽占纸张比例 字段及数据部分
public int rowWidth=100;
//默认行宽占纸张比例 表头
public int rowWidth_level=100;
//默认行宽占纸张比例 表头
public int rowWidth_footer=100;
//左边距
public float marginLeft=36f;
//右边距
public float marginRight=36f;
//上边距
public float marginTop=36f;
//下边距
public float marginBottom=36f;
public CreatePDFUtils1() throws IOException, DocumentException {
}
/**
*
* @param str 字符串
* @param font 字体
* @param high 表格高度
* @Param alignCenter 是否水平居中
* @Param alignMidde 是否垂直居中
* @Param haveColor 是否有背景色(灰色)
* @return
*/
public static PdfPCell mircoSoftFont(String str,Font font,int high,boolean alignCenter,boolean alignMidde){
PdfPCell pdfPCell = new PdfPCell(new Phrase(str,font));
pdfPCell.setMinimumHeight(high);
pdfPCell.setUseAscender(true); // 设置可以居中
if (alignCenter){
pdfPCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
}
if (alignMidde){
pdfPCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
}
return pdfPCell;
}
/**
*
* @param str 字符串
* @param font 字体
* @param high 表格高度
* @Param alignCenter 是否水平居中
* @Param alignMidde 是否垂直居中
* @Param haveColor 是否有背景色(灰色)
* @return
*/
public static PdfPCell mircoSoftFont(String str,Font font,int high,boolean alignCenter,boolean alignMidde,boolean haveColor){
PdfPCell pdfPCell = new PdfPCell(new Phrase(str,font));
pdfPCell.setMinimumHeight(high);
pdfPCell.setUseAscender(true); // 设置可以居中
if (alignCenter){
pdfPCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
}
if (alignMidde){
pdfPCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
}
if (haveColor){
//颜色代码 RGB
pdfPCell.setBackgroundColor(new BaseColor(217,217,217));
}
return pdfPCell;
}
// public void createHardwarePDF(String outputPath, List<T> dataList,List<Map<String,String>> rowList,Class clazz,
// List<list_exp_col> list_Col, float columnWidths_all[])throws Exception{
//
//新建文档对象,页大小为A4纸,然后设置4个边距
document = new Document(PageSize.A4,20,20,30,30);
// //新建文档对象,页大小为A4纸,然后设置4个边距
// // new RectangleReadOnly(595.0F, 842.0F);
// document = new Document(new Rectangle(PageSize.A4.getHeight(),PageSize.A4.getWidth()));
// PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(outputPath));
// document.open();
//
// //创建字体
// BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
// //字体对象
// Font size14font = new Font(baseFont,14,Font.NORMAL); //大小为14的正常字体
// Font size10font = new Font(baseFont,10,Font.BOLD); //大小为10的粗体
//
// Font size6font = new Font(baseFont,6,Font.NORMAL); //大小为6的正常字体
//
// //添加标题
// //createHeaderLeaver(int rowWidth,int columns,float columnWidths[],int highs[],String text[],Font size_font)
// createHeaderLeaver(100,1,new float[]{1.0f},new int[]{50},new String[]{"这是一个标题"},size10font,true,true);
PdfPTable tableName = new PdfPTable(1);
tableName.setWidthPercentage(10); //设置标题长度占纸张比例
tableName.addCell(mircoSoftFont("个人信息",size14font,50,true,true));
document.add(tableName);
// //添加第二行的数据
// createHeaderLeaver(100,3,new float[]{0.18f,0.32f,0.5f},new int[]{50,50,50},new String[]{"第二行1","第二行2","第二行3"},size10font,false,true);
//
//
// //设置动态表(List《T》)
// //setDateList(100,4, new float[]{0.18f,0.32f,0.3f,0.2f}, new int[]{50,50,50,50}, new String[]{"序号","用户名","性别","年龄"}, size10font,dataList);
//
// int size = list_Col.size();
// int highs_title[]=new int[size];
// int highs[]=new int[size];
// float columnWidths[]= new float[size];
float columnWidths_body[]= new float[size];
//
// columnWidths=columnWidths_all;
//
// for (int tem=0;tem< size; tem++) {
// highs_title[tem]=15;
// highs[tem]=15;
// }
//
//
// /**
// * @Description: 创建数据字段头
// * @Param: rowWidth 一行总宽
// * @Param: columns 分割列数
// * @Param: columnWidths[] 列宽权重数组
// * @Param: highs_title[] 字段头行高数组
// * @Param: highs[] 内容行高数组
// * @Param: text[] 字段表头内容(这里动态取得数据库)
// * @Param: size_font_title 字段头字体类型
// * @Param: size_font_body 内容字体类型
// * @Param: List<Map<String,String>> rowList
// * @return:
// * @Author: sj
// * @Date: 2023/12/15/015
// */
(int columns, float columnWidths[] ,int highs[],
Font size_font [], List<Map<String,String>> rowList,List<list_exp_col> list_Col )
// //设置动态表(List《T》)
// setDateList (list_Col.size(),columnWidths,highs,
// size6font,size6font, rowList,list_Col);
//
PdfPTable secondRowTable = new PdfPTable(3); //三列的意思
secondRowTable.setWidthPercentage(90);
//这里的数组长度是上面创建的列数,数组的总和为1,就是按比例划分的意思
secondRowTable.setTotalWidth(new float[]{0.18f,0.32f,0.5f});
secondRowTable.addCell(mircoSoftFont(" 姓名: ",size10font,50,false,true));
secondRowTable.addCell(mircoSoftFont("李晓明",size10font,50,false,true));
secondRowTable.addCell(mircoSoftFont(" 出生日期: 1994年3月14日",size10font,50,false,true));
document.add(secondRowTable);
// //第三行数据
PdfPTable thirdRowTable = new PdfPTable(3);
thirdRowTable.setWidthPercentage(90);
thirdRowTable.setTotalWidth(new float[]{0.18f,0.32f,0.5f});
thirdRowTable.addCell(mircoSoftFont(" 名族:",size10font,50,false,true));
thirdRowTable.addCell(mircoSoftFont("汉族",size10font,50,false,true));
thirdRowTable.addCell(mircoSoftFont(" 联系电话: 13888880000",size10font,50,false,true));
document.add(thirdRowTable);
// //第四行数据
PdfPTable fourthRowTable = new PdfPTable(2);
fourthRowTable.setWidthPercentage(90);
fourthRowTable.setTotalWidth(new float[]{0.66f,0.34f});
fourthRowTable.addCell(mircoSoftFont(" 个人描述 :",size10font,175,false,false));
fourthRowTable.addCell(mircoSoftFont("个人特长 :",size10font,175,false,false));
document.add(fourthRowTable);
// //第五行
PdfPTable fifthDetailName = new PdfPTable(1);
fifthDetailName.setWidthPercentage(90);
fifthDetailName.addCell(mircoSoftFont("获奖记录 :",size14font,50,true,true));
document.add(fifthDetailName);
//第六行
PdfPTable sisthRowTalbe= new PdfPTable(1);
sisthRowTalbe.setWidthPercentage(90);
sisthRowTalbe.addCell(mircoSoftFont(" 联系地址: "+"广东省广州市天河区XXXXXXXXXXXXXXXXXX",size10font,50,false,true));
document.add(sisthRowTalbe);
PdfPTable seventhRowTalbe = new PdfPTable(1);
seventhRowTalbe.setWidthPercentage(90);
seventhRowTalbe.addCell(mircoSoftFont(" 毕业院校 ",size14font,60,true,true));document.add(seventhRowTalbe);
//第八行
PdfPTable eiththRowTalbe = new PdfPTable(3);
eiththRowTalbe.setWidthPercentage(90);
eiththRowTalbe.setTotalWidth(new float[]{0.3f,0.5f,0.2f});
eiththRowTalbe.addCell(mircoSoftFont(" 毕业学校",size10font,50,true,true,true));
eiththRowTalbe.addCell(mircoSoftFont(" 就读日期",size10font,50,true,true,true));
eiththRowTalbe.addCell(mircoSoftFont(" 联系人",size10font,50,true,true,true));
document.add(eiththRowTalbe);
//接下来加List
String school = "XXX学校";
String time = "201909 - 2022-06";
String name = "陈某";
for (int i = 0 ;i<4 ;i++){
PdfPTable tempTable = new PdfPTable(3);
tempTable.setWidthPercentage(90);
tempTable.setTotalWidth(new float[]{0.3f,0.5f,0.2f});
tempTable.addCell(mircoSoftFont(school,size10font,50,true,true));
tempTable.addCell(mircoSoftFont(time,size10font,50,true,true));
tempTable.addCell(mircoSoftFont(name,size10font,50,true,true));
document.add(tempTable);
}
// document.close();
// writer.close();
// }
/**
* @Description: 只有表头加内容的pdf
* @Param: outputPath 导出路径
* @Param: List<Map<String,String>> rowList 内容集合
* @Param: clazz 类型
* @Param: list_Col 数据库对应的字段及名称等
* @Param: columnWidths_all 行列宽
* @return:
* @Author: sj
* @Date: 2023/12/18/018
*/
public void createHardwarePDF(String outputPath, List<Map<String,String>> rowList,
List<list_exp_col> list_Col, float columnWidths_all[])throws Exception{
//默认a4纵向
rotate_a4_direction();
PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(outputPath));
document.open();
//设置行高 第一个表示数据表头行高,第二个表示数据体行高
int[] highs = {row_Height_header,row_Height_body};
//设置字体 第一个表示数据表头字体,第二个表示数据体字体
Font[] fonts = {size6_Bfont,size6font};
// (int columns, float columnWidths[] ,int highs[],
// Font size_font [], List<Map<String,String>> rowList,List<list_exp_col> list_Col )
//设置动态表(List《T》)
setDateList (list_Col.size(),columnWidths_all,highs,
fonts, rowList,list_Col);
document.close();
writer.close();
}
public void create_recordPDF(String outputPath,List<list_v_oh_jxRecord>list_v_oh_jxRecords)throws Exception{
list_v_oh_jxRecord list_v_oh_jxRecord1=null;
if(list_v_oh_jxRecords!=null&&list_v_oh_jxRecords.size()>0){
list_v_oh_jxRecord1 = list_v_oh_jxRecords.get(0);
}
//默认a4纵向,
// 这里是自定义了横向
rotate_a4_transverse(0f);
//创建文件里流
FileOutputStream fileOutputStream = createFileOutputStream(outputPath);
PdfWriter writer = PdfWriter.getInstance(document,fileOutputStream);
document.open();
Paragraph par_01 = new Paragraph("检修线轴承尺寸测量",size18font);
par_01.setSpacingAfter(9f);
par_01.setAlignment(Element.ALIGN_CENTER);//居中
//列号
String lieNo=list_v_oh_jxRecord1.getLieCode();
//通知号
String informCode=list_v_oh_jxRecord1.getInformCode();
//格式化日期格式
String last_dt=list_v_oh_jxRecord1.getLastDt();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date parse = null;
try {
parse = simpleDateFormat.parse(last_dt);
} catch (ParseException e) {
e.printStackTrace();
}
last_dt = simpleDateFormat.format(parse);
System.out.println("-----------------》"+last_dt);
// String text02="列号/通知号:"+lieNo+"/"+informCode+
// " 辆号:"+
// " 人员:"+
// " 日期:";
String text02="列号/通知号:"+lieNo+"/"+informCode+
" 辆号:"+
" "+
" 日期:"+last_dt;
log.info("text02---------------------------->"+text02);
Paragraph par_02 = new Paragraph(text02,size16font);
par_02.setSpacingAfter(7f);
document.addTitle("产线检修记录表");
document.add(par_01);
document.add(par_02);
//设置表头
PdfPTable thirdRowTable = new PdfPTable(11);
//设置一列总宽度 默认80f,咱总宽度比例。
thirdRowTable.setWidthPercentage(rowWidth);
//是否是数组行高
int[] highs_field_header = new int[]{30,30,30,30,30,30,30,30,30,30,30};
float[] columnWidths = new float[]{0.03f,0.03f,0.03f,0.03f,0.03f,0.03f,0.03f,0.03f,0.03f,0.03f,0.03f};
//字段头内容
String[] myTitle = list_v_oh_jxRecord.getMyTitle();
// String[]text=new String[]{"轴承编号","检修自互检(标记,通气栓)","附件检修自互检","注脂(g)","注脂自互检","人工组装自互检","外圈外径(mm)","内圈内径(mm)"
// ,"后挡圈(mm)","挡油环(mm)","测量自互检"};
boolean isHeightArr=true;
int height=highs_field_header[0];
try {
//设置列宽权重
thirdRowTable.setTotalWidth(columnWidths);
if(highs_field_header.length>1){
isHeightArr=true;
}
for (int i=0;i<columnWidths.length;i++){
//设置字段头列内容
thirdRowTable.addCell(mircoSoftFont(myTitle[i],size11font,highs_field_header[i],true,true));
}
document.add(thirdRowTable);
} catch (DocumentException e) {
e.printStackTrace();
}
//加动态数据
//设置表头
//设置列数
int lieColums=15;
//数组行宽
//int[] highs_field_data = new int[]{40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40};
int[] highs_field_data = new int[]{40,40,40,40,40,40,40,40,40,40,40,40,40,40,40};
int hight_title=50;
int hight_body=50;
// float[] columnWidths_data = new float[]{0.03f,0.015f,0.015f,0.015f,0.015f,0.03f,0.015f,0.015f,0.015f,0.015f,
// 0.03f,0.03f,0.03f,0.03f,0.015f,0.015f};
float[] columnWidths_data = new float[]{0.03f,0.015f,0.015f,0.015f,0.015f,0.03f,0.015f,0.015f,0.03f,
0.03f,0.03f,0.03f,0.03f,0.015f,0.015f};
try {
for (int j=0;j<list_v_oh_jxRecords.size();j++){
PdfPTable thirdRowTable_data = new PdfPTable(lieColums);
//设置一列总宽度 默认80f,咱总宽度比例。
thirdRowTable_data.setWidthPercentage(rowWidth);
//设置列宽权重
thirdRowTable_data.setTotalWidth(columnWidths_data);
// String text_data="";
PdfColumn pdfColumn;
//每一行数据
list_v_oh_jxRecord list_v_oh_jxRecord = list_v_oh_jxRecords.get(j);
Class aClass = list_v_oh_jxRecord.getClass();
//遍历每个属性
//有问题,String数组对象创建后,就是全局的,即使下次创建他也不会没继续创建。
//List<String[]>fileSort_name=new ArrayList<>(lieColums);
List<String[]>fileSort_name=new ArrayList<>();
//以列的方式存放字段内容
//这个string数组会牵动全局,其实一直是一个数组操作,是同一个对象
//String many_row[]=new String[3];
Field[] fields = aClass.getDeclaredFields();
for (Field field : fields) {
System.out.println("PdfColumn--------------------->"+field.isAnnotationPresent(PdfColumn.class));
if(field.isAnnotationPresent(PdfColumn.class)){
pdfColumn = field.getAnnotation(PdfColumn.class);
//叠加行
if(pdfColumn.sort()<0){
//第一个值是list的小标,第二个值是string数组的下标
String[] split = pdfColumn.sort_row().split("_");
int index=Integer.parseInt(split[0]) - 1;
int String_index=Integer.parseInt(split[1])-1;
//fileSort_name.add(Integer.parseInt(split[0])-1,null);
try {
//空的话会抛出异常
if(fileSort_name.get(index)!=null){
//不是第一次插入,那就取出来继续存
fileSort_name.get(index)[String_index]=field.getName();
}
}catch (Exception e){
//只有限制最大插入16条
if(pdfColumn.sort()*(-1)<=16){
//第一次插入
String many_row[]=new String[3];
many_row[String_index]=field.getName();
fileSort_name.add(index,many_row);
}
}
}else {
fileSort_name.add(pdfColumn.sort()-1,new String[]{ field.getName()});
}
}
}
// fileSort_name = fileSort_name.subList(0, 16);
//3 , 6 ,7特殊处理
for (int i=0;i<fileSort_name.size();i++){
//这是一行数据中的每列数据,应该都是一个数据,多个数据就是行叠加
String[] Column_field = fileSort_name.get(i);
if(Column_field.length>1){
PdfPTable pdfPTable=new PdfPTable(1);
for (int k=0;k<Column_field.length;k++){
String getMethodName = "get" + Column_field[k].substring(0, 1).toUpperCase() + Column_field[k].substring(1);
Method method = aClass.getMethod(getMethodName);
String value = (String)method.invoke(list_v_oh_jxRecord);
PdfPCell pdfPCell = mircoSoftFont(value, size11font, hight_body/3, false, true);
if(k==0){
pdfPCell.disableBorderSide(13);
}else if(k==1){
pdfPCell.disableBorderSide(12);
}else {
pdfPCell.disableBorderSide(14);
}
pdfPTable.addCell(pdfPCell);
}
thirdRowTable_data.addCell(pdfPTable);
}else {
//设置字段头列内容
String getMethodName = "get" + Column_field[0].substring(0, 1).toUpperCase() + Column_field[0].substring(1);
Method method = aClass.getMethod(getMethodName);
String value="";
if(method.invoke(list_v_oh_jxRecord)!=null){
value=(String)method.invoke(list_v_oh_jxRecord);
}
thirdRowTable_data.addCell(mircoSoftFont(value,size11font,hight_body,false,true));
}
//
// if(i==5 || i==10 ||i==11){
// PdfPTable pdfPTable=new PdfPTable(1);
// //mircoSoftFont(text_data,size10font,highs_field_header[i],true,true);
// PdfPCell pdfPCell01 = mircoSoftFont("1", size10font, 10, true, true);
// PdfPCell pdfPCell02 = mircoSoftFont("2", size10font, 10, true, true);
// PdfPCell pdfPCell03 = mircoSoftFont("3", size10font, 10, true, true);
// //thirdRowTable_data.addCell(pdfPTable);
// pdfPCell01.disableBorderSide(13);
// pdfPCell02.disableBorderSide(12);
// pdfPCell03.disableBorderSide(14);
// pdfPTable.addCell(pdfPCell01);
// pdfPTable.addCell(pdfPCell02);
// pdfPTable.addCell(pdfPCell03);
// thirdRowTable_data.addCell(pdfPTable);
// }else {
// //设置字段头列内容
// thirdRowTable_data.addCell(mircoSoftFont(text_data,size10font,highs_field_data[i],true,true));
// }
}
document.add(thirdRowTable_data);
}
} catch (DocumentException e) {
e.printStackTrace();
}
fileOutputStream.flush();
document.close();
writer.close();
fileOutputStream.close();
}
/**
* @Description: 自定义多行表头
* @Param: outputPath 导出路径
* @Param: List<Map<String,String>> rowList 内容集合
* @Param: clazz 类型
* @Param: list_Col 数据库对应的字段及名称等
* @Param: columnWidths_all 行列宽(动态数据部分)
* @Param: highs_header[] 表头行高
* @Param: columnWidths_header ArrayList<Float[]> 表格列宽
* @Param: columnText_header《内容》 ArrayList<String[]> 表格列宽
* @Param: columnWidth_footer 表尾列宽
* @Param: columnText_footer 表尾内容
* @return:
* @Author: sj
* @Date: 2023/12/18/018
*/
public void createHardwarePDF(String outputPath, List<Map<String,String>> rowList,
List<list_exp_col> list_Col, float columnWidths_all[],
int highs_header[] ,ArrayList<float[]>columnWidths_header,ArrayList<String[]>columnText_header,
float [] columnWidth_footer,String[] columnText_footer)throws Exception{
//默认a4纵向,
// 这里是自定义了横向
rotate_a4_transverse();
//创建文件里流
FileOutputStream fileOutputStream = createFileOutputStream(outputPath);
PdfWriter writer = PdfWriter.getInstance(document,fileOutputStream);
document.open();
//设置表头
//几层表头
int level = highs_header.length;
for (int i=0;i<level;i++){
//列宽权重
float[] rowWidth = columnWidths_header.get(i);
//一行数据
String[] rowText = columnText_header.get(i);
//默认字号size14font
//添加第几行行的数据
createHeaderLeaver(rowWidth_level,rowWidth.length,rowWidth,new int[]{highs_header[i]},rowText
,size_titleFont,true,true);
}
float columnWidths[]= columnWidths_all;
//设置行高 第一个表示数据表头行高,第二个表示数据体行高
int[] highs = {row_Height_header,row_Height_body};
//设置字体 第一个表示数据表头字体,第二个表示数据体字体
Font[] fonts = {size_filed_Header_font,size_filed_Body_font};
// (int columns, float columnWidths[] ,int highs[],
// Font size_font [], List<Map<String,String>> rowList,List<list_exp_col> list_Col )
//设置动态表(List《T》)
setDateList (list_Col.size(),columnWidths,highs,
fonts, rowList,list_Col);
//设置表尾
if (columnText_footer!=null && columnText_footer.length>0){
createHeaderLeaver(rowWidth_footer,1,columnWidth_footer,new int[]{70},columnText_footer
,size_footerFont,true,true);
}
fileOutputStream.flush();
document.close();
writer.close();
fileOutputStream.close();
}
/**
* @Description: 创建一行数据表头
* @Param: columns 分割列数
* @Param: columnWidths[] 列宽权重数组
* @Param: highs[] 行高数组
* @Param: text[] 文本内容
* @return: size_font 字体类型
* @Author: sj
* @Date: 2023/12/15/015
*/
public void createHeaderLeaver(int rowWidth,int columns,float columnWidths[],int highs[],String text[],Font size_font,
Boolean alignCenter,Boolean alignMidde){
PdfPTable thirdRowTable = new PdfPTable(columns);
//设置一列总宽度 默认80f,咱总宽度比例。
thirdRowTable.setWidthPercentage(rowWidth);
//是否是数组行高
boolean isHeightArr=false;
int height=highs[0];
try {
//设置列宽权重
thirdRowTable.setTotalWidth(columnWidths);
if(highs.length>1){
isHeightArr=true;
}
for (int i=0;i<columns;i++){
//如果是数组
if (isHeightArr){
height=highs[i];
}
//设置列内容
thirdRowTable.addCell(mircoSoftFont(text[i],size_font,height,alignCenter,alignMidde));
}
document.add(thirdRowTable);
} catch (DocumentException e) {
e.printStackTrace();
}
}
/**
* @Description: 创建动态数据表
* @Param: columns 分割列数
* @Param: columnWidths[] 列宽权重数组
* @Param: highs_title[] 字段头行高数组
* @Param: highs[] 内容行高数组
* @Param: text[] 字段表头内容
* @return: size_font 字体类型
* @Author: sj
* @Date: 2023/12/15/015
*/
public void setDateList(int rowWidth,int columns, float columnWidths[], int highs[], String text[], Font size_font,List<T> dataList){
PdfPTable thirdRowTable = new PdfPTable(columns);
//设置一列总宽度 默认80f,咱总宽度比例。
thirdRowTable.setWidthPercentage(rowWidth);
//thirdRowTable.setTotalWidth(new float[]{0.18f,0.32f,0.5f});
try {
//设置列宽权重
thirdRowTable.setTotalWidth(columnWidths);
//设置字段头
for (int i=0;i<columns;i++){
//设置列内容
thirdRowTable.addCell(mircoSoftFont(text[i],size_font,highs[i],false,true));
}
document.add(thirdRowTable);
//遍历每个list,存入每行
for (int i=0;i<dataList.size();i++){
PdfPTable thirdRowTable_date = new PdfPTable(columns);
thirdRowTable_date.setTotalWidth(columnWidths);
//设置一列总宽度 默认80f,咱总宽度比例。
thirdRowTable_date.setWidthPercentage(rowWidth);
T t = dataList.get(i);
Class<?> aClass = t.getClass();
//获取字段名称集合
Field[] declaredFields = aClass.getDeclaredFields();
int index=0;
for (Field declaredField : declaredFields) {
//标有TableField注解的属性不写入pdf
boolean annotationPresent = declaredField.isAnnotationPresent(TableField.class);
if(annotationPresent){
continue;
}
String fieldName = declaredField.getName();
//获取get方法名
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
//另外一种手动拼get方法的方式获取值
//得到对应的方法
Method getMethod = null;
try {
getMethod = aClass.getMethod(getMethodName, new Class[] {});
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
//执行方法,得到返回值
Object value = null;
try {
value = getMethod.invoke(t, new Object[] {});
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
String textValue="";
if (value != null) {
textValue = value.toString();
System.out.println("getMethodName------>" +getMethodName);
System.out.println("getMethodName_value------>" +textValue);
}
thirdRowTable_date.addCell(mircoSoftFont(textValue,size_font,highs[index],false,true));
index++;
//设置列内容
// thirdRowTable.addCell(mircoSoftFont(,size_font,highs[i],false,true));
}
document.add(thirdRowTable_date);
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
/**
* @Description: 创建动态数据表
* @Param: rowWidth 一行总宽
* @Param: columns 分割列数
* @Param: columnWidths[] 列宽权重数组
* @Param: highs_title[] 字段头行高数组
* @Param: highs[] 第一个值存字段头行高,第二个值存内容行高
* @Param: text[] 字段表头内容(这里动态取得数据库)
* @Param: size_font_title 字段头字体类型 size_font【】数组一起存了
* @Param: size_font_body 内容字体类型
* @Param: List<Map<String,String>> rowList 表数据
* @return:
* @Author: sj
* @Date: 2023/12/15/015
*/
public void setDateList(int columns, float columnWidths[] ,int highs[],
Font size_font [], List<Map<String,String>> rowList,List<list_exp_col> list_Col ){
PdfPTable thirdRowTable = new PdfPTable(columns);
//设置一列总宽度 默认80f,咱总宽度比例。
thirdRowTable.setWidthPercentage(this.rowWidth);
//thirdRowTable.setTotalWidth(new float[]{0.18f,0.32f,0.5f});
try {
//设置列宽权重
thirdRowTable.setTotalWidth(columnWidths);
//设置字段头
for (int i=0;i<list_Col.size();i++){
//设置列内容
thirdRowTable.addCell(mircoSoftFont(list_Col.get(i).getCol_name(),size_font[0],highs[0],false,true));
}
document.add(thirdRowTable);
//遍历每个list,存入每行
for (int i=0;i<rowList.size();i++){
PdfPTable thirdRowTable_date = new PdfPTable(columns);
thirdRowTable_date.setTotalWidth(columnWidths);
//设置一列总宽度 默认80f,咱总宽度比例。
thirdRowTable_date.setWidthPercentage(rowWidth);
Map<String, String> map = rowList.get(i);
// //获取字段名称集合
// Field[] declaredFields = clazz.getDeclaredFields();
//遍历每个字段,同一行的每一列
for (int j=0;j<list_Col.size();j++){
String textValue = map.get(list_Col.get(j).getCol_key());
if(textValue!=null){
thirdRowTable_date.addCell(mircoSoftFont(textValue,size_font[1],highs[1],false,true));
}
}
document.add(thirdRowTable_date);
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
//设置横向a4
public FileOutputStream createFileOutputStream(String filePath_name){
//导出
File file=new File(filePath_name);
FileOutputStream out=null;
try {
if (file == null) {
file.createNewFile();
log.info("文件不存在,创建新文件:" + filePath_name);
} else {
log.info("文件存在:" + filePath_name);
}
out=new FileOutputStream(file);
}catch (IOException e){
e.printStackTrace();
log.info("Output is closed ");
}
return out;
}
// //左边距
// private float marginLeft=36f;
// //右边距
// private float marginRight=36f;
// //上边距
// private float marginTop=36f;
// //下边距
// private float marginBottom=36f;
//设置横向a4
public void rotate_a4_transverse(){
document = new Document(new Rectangle(PageSize.A4.getHeight(),PageSize.A4.getWidth()));
}
//设置横向a4(自定义上边距)
public void rotate_a4_transverse( float marginTop){
this.marginTop=marginTop;
document = new Document(new Rectangle(PageSize.A4.getHeight(),PageSize.A4.getWidth())
,marginLeft,marginRight,marginTop,marginBottom);
}
//设置纵向格式a4
public void rotate_a4_direction(){
document = new Document(PageSize.A4);
}
/**
* @Description:
* @Param: response 请求
* @Param: as_Src_File 文件路径
* @Param: as_SaveAs_Name 文件名称
* @return:
* @Author: sj
* @Date: 2023/12/19/019
*/
public void down_pdf(HttpServletResponse response, String as_Src_File, String as_SaveAs_Name) throws IOException {
String ls_FileName = as_SaveAs_Name + ".pdf";
String dfileName = new String(ls_FileName.getBytes("gb2312"), "iso8859-1");
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
System.out.println("exp FileName = " + dfileName);
response.setHeader("Content-Disposition", "attachment;filename=" + dfileName);
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(as_Src_File);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("expStdFile OK");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
5.接口代码
/**
* @Description: 导出pdf格式
* @Param:
* @return:
* @Author: sj
* @Date: 2023/12/18/018
*/
@RequestMapping(value = "/home_exp_pdf_record", method = RequestMethod.POST)
@ResponseBody
public String downAndExp_pdf_record(HttpServletRequest request, @RequestParam Map<String, String> inMap , HttpServletResponse response) {
// Map<String, String> myMap=new HashMap<>();
// myMap.put("brg_ids","00052229,00052225,00052219,00052218,00052217,00052216,00052214,00052213");
String brg_ids = inMap.get("brg_ids");
String[] brg_idArr = brg_ids.split(",");
System.out.println("inMap-------------------->"+inMap);
//文件路径
//本地文件地址
String filePath="D:\\apache-tomcat-8.5.32-x64\\webapps\\bmpl\\downPdf\\";
//服务器文件地址
//String filePath="E:\\apache-tomcat-8.5.32-x64\\webapps\\bmpl\\downPdf\\";
//文件名称
String fileName="";
List<list_v_oh_jxRecord>list_v_oh_jxRecords= bmplOldService.get_List_v_oh_jxRecord(brg_idArr);
list_v_oh_jxRecord list_v_oh_jxRecord = list_v_oh_jxRecords.get(0);
String zcbh = list_v_oh_jxRecord.getZcbh();
String lastDt = list_v_oh_jxRecord.getLastDt();
String format1="";
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
try {
Date parse = format.parse(lastDt);
format1 = format.format(parse);
} catch (ParseException e) {
e.printStackTrace();
}
fileName=zcbh+"("+format1+")"+"产线检修记录表.pdf";
list_v_oh_jxRecords.forEach(ent->{
System.out.println("-------------------------->"+ent.toString());
});
try {
new CreatePDFUtils1().create_recordPDF(filePath+fileName,list_v_oh_jxRecords);
} catch (Exception e) {
e.printStackTrace();
return "error";
}
return "OK"+filePath+fileName;
}