利用若依@Excel注解导出PDF工具类
1.pom依赖
<!--PDF导出-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!-- pdf 加权限 添加以下包不然会报错-->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.47</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcmail-jdk15on</artifactId>
<version>1.47</version>
</dependency>
2.PDFBuilder
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.IOException;
public class PDFBuilder extends PdfPageEventHelper {
public String header = "";
public int presentFontSize = 12;
public PdfTemplate total;
public BaseFont bf = null;
public Font fontDetail = null;
public PDFBuilder() {
}
public void setHeader(String header) {
this.header = header;
}
public void onOpenDocument(PdfWriter writer, Document document) {
total = writer.getDirectContent().createTemplate(50, 50);
}
public void onEndPage(PdfWriter writer, Document document) {
this.addPage(writer, document);
}
public void addPage(PdfWriter writer, Document document){
try {
if (bf == null) {
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
}
if (fontDetail == null) {
fontDetail = new Font(bf, presentFontSize, Font.NORMAL);
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_LEFT, new Phrase(header, fontDetail),
document.left(), document.top() + 20, 0);
int pageS = writer.getPageNumber();
String foot1 = "第 " + pageS + " 页 / 共";
Phrase footer = new Phrase(foot1, fontDetail);
float len = bf.getWidthPoint(foot1, presentFontSize);
PdfContentByte cb = writer.getDirectContent();
ColumnText
.showTextAligned(
cb,
Element.ALIGN_CENTER,
footer,
(document.rightMargin() + document.right()
+ document.leftMargin() - document.left() - len) / 2.0F + 20F,
document.bottom() - 20, 0);
cb.addTemplate(total, (document.rightMargin() + document.right()
+ document.leftMargin() - document.left()) / 2.0F + 20F,
document.bottom() - 20);
}
public void onCloseDocument(PdfWriter writer, Document document) {
total.beginText();
total.setFontAndSize(bf, presentFontSize);
String foot2 = " " + (writer.getPageNumber()) + " 页";
total.showText(foot2);
total.endText();
total.closePath();
}
}
3.PDFUtil
package com.bims.common.utils.poi;
import com.bims.common.annotation.Excel;
import com.bims.common.annotation.Excels;
import com.bims.common.config.Global;
import com.bims.common.core.domain.AjaxResult;
import com.bims.common.utils.DateUtils;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PDFUtil<T> {
private static final Logger log = LoggerFactory.getLogger(PDFUtil.class);
private static Font headfont;
private static Font keyfont;
private static Font textfont;
public Class<T> clazz;
public PDFUtil(Class<T> clazz) {
this.clazz = clazz;
}
private String title;
private List<T> list;
private Excel.Type type;
private List<Object[]> fields;
static {
BaseFont bfChinese;
try {
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);
headfont = new Font(bfChinese, 24, Font.BOLD, BaseColor.BLACK);
keyfont = new Font(bfChinese, 12, Font.BOLD, BaseColor.BLACK);
textfont = new Font(bfChinese, 10, Font.NORMAL, BaseColor.BLACK);
} catch (Exception e) {
e.printStackTrace();
}
}
public AjaxResult exportPdf(List<T> list, String title) throws Exception {
this.init(list, title, Excel.Type.EXPORT);
return exportPdf();
}
public static void main(String[] args) throws Exception {
List<String> header = new ArrayList<String>();
PdfPTable table = PDFUtil.createTable(15);
table.addCell(PDFUtil.createHeadCell("年后", 15));
for (int i = 0; i < 15; i++) {
header.add("你好啊" + i);
table.addCell(PDFUtil.createTitleCell_1("a" + i));
}
for (int i = 0; i < 200; i++) {
if (header != null && header.size() > 0) {
for (String str : header) {
table.addCell(PDFUtil.createCell_1(str + "b"));
}
}
}
String output = "C:\\Users\\10910\\Desktop\\" + new SimpleDateFormat("mmsss").format(new Date()) + ".pdf";
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(output)));
PDFUtil.exportPdf(out, table, "客服中心报表系统,导出工号969");
System.out.println("完成");
}
public AjaxResult exportPdf() throws Exception {
List<String> header = new ArrayList<String>();
int length = fields.size();
PdfPTable table = PDFUtil.createTable(length);
table.addCell(PDFUtil.createHeadCell(this.title, length));
for (Object[] os : fields) {
Excel excel = (Excel) os[1];
table.addCell(PDFUtil.createTitleCell_1(excel.name()));
}
if (Excel.Type.EXPORT.equals(type)) {
table = fillPdfData(table);
}
String fileName = encodingFilename(this.title);
String output = getAbsoluteFile(fileName);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(output)));
PDFUtil.exportPdf(out, table, "");
return AjaxResult.success(fileName);
}
public String encodingFilename(String filename) {
filename = UUID.randomUUID().toString() + "_" + filename + ".pdf";
return filename;
}
public String getAbsoluteFile(String filename) {
String downloadPath = Global.getDownloadPath() + filename;
File desc = new File(downloadPath);
if (!desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
return downloadPath;
}
public PdfPTable fillPdfData(PdfPTable table) {
for (int i = 0; i < this.list.size(); i++) {
T vo = (T) list.get(i);
for (Object[] os : fields) {
Field field = (Field) os[0];
Excel excel = (Excel) os[1];
field.setAccessible(true);
table = addCell(excel, table, vo, field);
}
}
return table;
}
public PdfPTable addCell(Excel attr, PdfPTable table, T vo, Field field) {
try {
if (attr.isExport()) {
Object value = getTargetValue(vo, field, attr);
String dateFormat = attr.dateFormat();
String readConverterExp = attr.readConverterExp();
if (com.bims.common.utils.StringUtils.isNotEmpty(dateFormat) && com.bims.common.utils.StringUtils.isNotNull(value)) {
table.addCell(PDFUtil.createCell_1(DateUtils.parseDateToStr(dateFormat, (Date) value)));
} else if (com.bims.common.utils.StringUtils.isNotEmpty(readConverterExp) && com.bims.common.utils.StringUtils.isNotNull(value)) {
table.addCell(PDFUtil.createCell_1(convertByExp(String.valueOf(value), readConverterExp)));
} else {
if (Excel.ColumnType.STRING == attr.cellType()) {
table.addCell(PDFUtil.createCell_1(com.bims.common.utils.StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix()));
} else if (Excel.ColumnType.NUMERIC == attr.cellType()) {
table.addCell(PDFUtil.createCell_1(value + ""));
}
}
}
} catch (Exception e) {
log.error("导出PDF失败{}", e);
}
return table;
}
public static String convertByExp(String propertyValue, String converterExp) throws Exception {
try {
String[] convertSource = converterExp.split(",");
for (String item : convertSource) {
String[] itemArray = item.split("=");
if (itemArray[0].equals(propertyValue)) {
return itemArray[1];
}
}
} catch (Exception e) {
throw e;
}
return propertyValue;
}
private Object getTargetValue(T vo, Field field, Excel excel) throws Exception {
Object o = field.get(vo);
if (com.bims.common.utils.StringUtils.isNotEmpty(excel.targetAttr())) {
String target = excel.targetAttr();
if (target.indexOf(".") > -1) {
String[] targets = target.split("[.]");
for (String name : targets) {
o = getValue(o, name);
}
} else {
o = getValue(o, target);
}
}
return o;
}
private Object getValue(Object o, String name) throws Exception {
if (com.bims.common.utils.StringUtils.isNotEmpty(name)) {
Class<?> clazz = o.getClass();
String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
Method method = clazz.getMethod(methodName);
o = method.invoke(o);
}
return o;
}
public void init(List<T> list, String title, Excel.Type type) {
if (list == null) {
list = new ArrayList<T>();
}
this.list = list;
this.title = title;
this.type = type;
createExcelField();
}
private void createExcelField() {
this.fields = new ArrayList<Object[]>();
List<Field> tempFields = new ArrayList<>();
tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
for (Field field : tempFields) {
if (field.isAnnotationPresent(Excel.class)) {
putToField(field, field.getAnnotation(Excel.class));
}
if (field.isAnnotationPresent(Excels.class)) {
Excels attrs = field.getAnnotation(Excels.class);
Excel[] excels = attrs.value();
for (Excel excel : excels) {
putToField(field, excel);
}
}
}
}
private void putToField(Field field, Excel attr) {
if (attr != null && (attr.type() == Excel.Type.ALL || attr.type() == type)) {
this.fields.add(new Object[]{field, attr});
}
}
public static PdfPCell createTitleCell_1(String value) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, keyfont));
cell.setBackgroundColor(new BaseColor(29, 181, 238));
return cell;
}
public static PdfPCell createTitleCell_2(String value) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, keyfont));
cell.setBackgroundColor(new BaseColor(29, 181, 238));
cell.setColspan(1);
cell.setRowspan(3);
cell.setFixedHeight(105);
return cell;
}
public static PdfPCell createCell_1(String value) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, textfont));
cell.setBackgroundColor(new BaseColor(255, 255, 255));
cell.setColspan(1);
return cell;
}
public static PdfPCell createCell_2(String value) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, textfont));
cell.setBackgroundColor(new BaseColor(255, 255, 255));
cell.setColspan(1);
cell.setRowspan(3);
cell.setFixedHeight(105);
return cell;
}
public static PdfPCell createCell_3(String value) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, textfont));
cell.setBackgroundColor(new BaseColor(255, 255, 255));
cell.setColspan(2);
cell.setFixedHeight(35);
return cell;
}
public static PdfPCell createCell_4(String value) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, textfont));
cell.setBackgroundColor(new BaseColor(255, 255, 255));
cell.setColspan(4);
cell.setRowspan(3);
cell.setFixedHeight(105);
return cell;
}
public static PdfPTable createTable(int colNumber) {
int widths[] = new int[colNumber];
for (int i = 0; i < widths.length; i++) {
widths[i] = 35 * 5 / colNumber;
}
PdfPTable baseTable = new PdfPTable(colNumber);
baseTable.setWidthPercentage(100);
baseTable.setSpacingBefore(10);
try {
baseTable.setWidths(widths);
} catch (DocumentException e) {
e.printStackTrace();
}
return baseTable;
}
public static void addmark(String input, BufferedOutputStream out,
String imgPath, String texMark) throws Exception {
try {
PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, out);
byte[] ownerPassword = UUID.randomUUID().toString().replaceAll("-", "").getBytes();
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_COPY, PdfWriter.ENCRYPTION_AES_128);
if (StringUtils.isNotEmpty(imgPath)) {
addPageMark(imgPath, reader, stamper);
}
if (StringUtils.isNotEmpty(texMark)) {
addWatermark(stamper, texMark);
}
stamper.close();
reader.close();
File file = new File(input);
if (file.exists()) {
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void addmark(String input, BufferedOutputStream out, String texMark) throws Exception {
addmark(input, out, "", texMark);
}
public static void addPageMark(String realPath, PdfReader reader,
PdfStamper stamper) {
int total = reader.getNumberOfPages();
try {
Image image = Image.getInstance(realPath);
image.setAbsolutePosition(350, 200);
image.scaleToFit(160, 70);
PdfContentByte content = stamper.getOverContent(total);
content.addImage(image);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void addWatermark(PdfStamper pdfStamper, String waterMarkName)
throws Exception {
PdfContentByte content;
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);
Rectangle pageRect;
PdfGState gs = new PdfGState();
try {
if (base == null || pdfStamper == null) {
return;
}
gs.setFillOpacity(0.3f);
gs.setStrokeOpacity(0.3f);
int toPage = pdfStamper.getReader().getNumberOfPages();
for (int i = 1; i <= toPage; i++) {
pageRect = pdfStamper.getReader().getPageSizeWithRotation(i);
content = pdfStamper.getOverContent(i);
content.saveState();
content.setGState(gs);
content.beginText();
content.setColorFill(BaseColor.GRAY);
content.setFontAndSize(base, 20);
int hnum = 4;
int wnum = 4;
float h = pageRect.getHeight() / hnum;
float w = pageRect.getWidth() / wnum;
for (int k = 1; k < hnum; k++) {
for (int j = 1; j < wnum; j++) {
content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, w * j, k * h, 45);
}
}
content.endText();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static PdfPCell createHeadCell(String value, int number) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(15);
cell.setHorizontalAlignment(15);
cell.setColspan(number);
cell.setPhrase(new Phrase(value, headfont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPadding(10.0f);
cell.setBorder(0);
cell.setPaddingTop(5.0f);
cell.setPaddingBottom(18.0f);
return cell;
}
public static PdfPCell createCell(String value) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, textfont));
cell.setBackgroundColor(new BaseColor(255, 255, 255));
cell.setColspan(1);
cell.setFixedHeight(35);
return cell;
}
public static void exportPdf(BufferedOutputStream out,
PdfPTable pdfPTable, String realPath, String texmark)
throws IOException, Exception {
String lsfile = setTableData(pdfPTable);
try {
PDFUtil.addmark(lsfile, out, realPath, texmark);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
public static void exportPdf(BufferedOutputStream out,
PdfPTable pdfPTable, String texmark)
throws IOException, Exception {
String lsfile = setTableData(pdfPTable);
try {
PDFUtil.addmark(lsfile, out, "", texmark);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
public static void setTableData(PdfPTable table, OutputStream outputStream) {
try {
Document document = new Document();
Rectangle pageSize = new Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth());
pageSize.rotate();
document.setPageSize(pageSize);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
PDFBuilder builder = new PDFBuilder();
writer.setPageEvent(builder);
document.open();
document.add(table);
document.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String setTableData(PdfPTable table) {
String out = UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";
FileOutputStream fileIo = null;
try {
Document document = new Document();
Rectangle pageSize = new Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth());
pageSize.rotate();
document.setPageSize(pageSize);
fileIo = new FileOutputStream(out);
PdfWriter writer = PdfWriter.getInstance(document, fileIo);
PDFBuilder builder = new PDFBuilder();
writer.setPageEvent(builder);
document.open();
document.add(table);
document.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileIo != null) {
try {
fileIo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return out;
}
public static PdfPTable getPdfPTable(List<List<String>> list, String search, List<String> header) {
int size = header.size();
PdfPTable table = createPdfPTable(size);
setPdfPTableSearch(table, search, size);
setPdfPTableSimpleHead(table, header);
setPdfPTableSimpleData(table, list);
return table;
}
public static PdfPTable createPdfPTable(int size) {
PdfPTable table = PDFUtil.createTable(size);
return table;
}
public static PdfPTable setPdfPTableSearch(PdfPTable table, String search,
int size) {
table.addCell(PDFUtil.createHeadCell(search, size));
return table;
}
public static PdfPTable setPdfPTableSimpleHead(PdfPTable table, List<String> header) {
if (header != null && header.size() > 0) {
for (String str : header) {
table.addCell(PDFUtil.createCell_1(str));
}
}
return table;
}
public static PdfPTable setPdfPTableSimpleData(PdfPTable table, List<List<String>> list) {
if (list != null && list.size() > 0) {
for (List<String> ls : list) {
if (ls != null && ls.size() > 0) {
for (String str : ls) {
table.addCell(PDFUtil.createCell_1(str));
}
}
}
}
return table;
}
public static PdfPTable setPdfPTableMergeData(PdfPTable table, List<List<String>> list, int coIndex, int cols, List<Boolean> isrow) {
List<PdfPCell> box = new ArrayList<PdfPCell>();
int[] index = getIndex(new int[cols]);
int rowspan = -1;
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
List<String> list2 = list.get(i);
if (list2 != null && list2.size() > 0) {
for (int j = 0; j < list2.size(); j++) {
String value = list2.get(j);
PdfPCell createCell = createCell(value);
Boolean boolean1 = isrow.get(j);
if (j == coIndex) {
int rowspan2 = getRowspan(list, i, j, value, 0, true);
if (rowspan == -1) {
if (rowspan2 == 1) {
table.addCell(createCell);
rowspan = 1;
} else {
rowspan = rowspan2;
index[j] = i + rowspan2 - 1;
createCell.setRowspan(rowspan2);
createCell.setFixedHeight(rowspan2 * 35);
box.add(createCell);
}
} else if (rowspan == 1) {
if (rowspan2 == 1) {
table.addCell(createCell);
rowspan = 1;
} else {
rowspan = rowspan2;
index[j] = i + rowspan2 - 1;
createCell.setRowspan(rowspan2);
createCell.setFixedHeight(rowspan2 * 35);
box.add(createCell);
}
} else {
int l = index[j];
if (l == -1) {
if (rowspan2 == 1) {
table.addCell(createCell);
} else {
index[j] = i + rowspan2 - 1;
createCell.setRowspan(rowspan2);
createCell.setFixedHeight(rowspan2 * 35);
box.add(createCell);
}
} else {
}
}
} else if (j > coIndex) {
if (boolean1) {
if (rowspan <= 1) {
table.addCell(createCell);
} else {
int l = index[j];
int rowspan2 = getRowspan(list, i, j, value, rowspan, false);
if (l == -1) {
if (rowspan2 == 1) {
box.add(createCell);
} else {
index[j] = i + rowspan2 - 1;
createCell.setRowspan(rowspan2);
createCell.setFixedHeight(rowspan2 * 35);
box.add(createCell);
}
} else {
if (i == index[j]) {
index[j] = -1;
}
}
}
} else {
if (rowspan <= 1) {
table.addCell(createCell);
} else {
box.add(createCell);
}
}
if (index[coIndex] == i && j == list2.size() - 1) {
index = getIndex(index);
if (box != null && box.size() > 0) {
for (int k = 0; k < box.size(); k++) {
PdfPCell pdfPCell = box.get(k);
table.addCell(pdfPCell);
;
}
}
box = new ArrayList<PdfPCell>();
rowspan = -1;
}
} else {
if (rowspan <= 1) {
table.addCell(createCell);
} else {
box.add(createCell);
}
}
}
}
}
}
return table;
}
private static int[] getIndex(int[] index) {
for (int i = 0; i < index.length; i++) {
index[i] = -1;
}
return index;
}
public static int getInt(String str) {
int re = 1;
try {
re = Integer.parseInt(str);
} catch (Exception e) {
}
return re;
}
public static int getRowspan(List<List<String>> list, int hang, int lie, String value, int limit, boolean fla) {
int coun = 1;
for (int i = hang + 1; i < list.size(); i++) {
String check = "";
List<String> list2 = list.get(i);
if (list2 != null && list2.size() > 0) {
if (StringUtils.isNotEmpty(list2.get(lie))) {
check = list2.get(lie);
}
}
if (value.endsWith(check)) {
coun++;
} else {
if (!fla && coun > limit) {
coun = limit;
}
return coun;
}
}
if (!fla && coun > limit) {
coun = limit;
}
return coun;
}
}
4.使用方式
PDFUtil<实体类> util = new PDFUtil<实体类>(实体类.class);
return util.exportPdf(list, "文件名称");