利用OpenPDF导出pdf报表文件
导入需要的包
以gradle构建的项目为例
implementation group: 'com.github.librepdf', name: 'openpdf', version: '1.3.35'
implementation group: 'com.github.librepdf', name: 'openpdf-fonts-extra', version: '1.3.35'
如果以其他形式构建,可以在Maven Repository上查找所需要的包
编写工具类PdfUtils
首先要放入字体文件,如下,在电脑上找到想用的字体文件,右键复制将文件拷至项目目录下
import com.lowagie.text.Font;
import com.lowagie.text.Rectangle;
import com.lowagie.text.*;
import com.lowagie.text.alignment.HorizontalAlignment;
import com.lowagie.text.alignment.VerticalAlignment;
import com.lowagie.text.pdf.*;
import java.awt.*;
import java.io.IOException;
import static com.lowagie.text.Font.BOLD;
public class PdfUtils {
public static BaseFont MSYH;
public static BaseFont MSYHL;
public static Font MSYHL_TEXT_BOLD;
public static Font MSYHL_TEXT;
static {
try {
MSYH = BaseFont.createFont("fonts/msyh.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
MSYHL = BaseFont.createFont("fonts/msyhl.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
MSYHL_TEXT_BOLD = new Font(MSYHL, 10, BOLD);
MSYHL_TEXT = new Font(MSYHL, 10f);
} catch (IOException ex) {
ex.printStackTrace();
}
}
//为页面设置水印
public static void addWaterMark(Document document, PdfWriter writer) {
writer.setPageEvent(new PdfPageEventHelper(){
@Override
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte waterMar = writer.getDirectContentUnder();
String text = "XXXXXXXXXXXXX";
addTextFullWaterMark(waterMar, text, MSYH);
}
});
}
//为页面设置页脚
public static void addFooter(Document document) {
HeaderFooter footer = new HeaderFooter(true);
footer.setAlignment(Element.ALIGN_CENTER);
footer.setBorder(Rectangle.NO_BORDER);
document.setFooter(footer);
}
//设置表格样式
public static void setTableStyle(Table table, int[] widths) {
// 设置表格宽度为100%
table.setWidth(100);
// 表格在页面水平方向的对齐方式
table.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 设置表格边框(仅最外层边框为Table的边框,内部边框属于Cell),同样用四个bit位分别表示上(0001)、下(0010)、左(0100)、右(1000)四个边
table.setBorder(Rectangle.NO_BORDER);
// 表格边框宽度
// table.setBorderWidth(1);
// 设置该值可以让文字与底部表格线留出一定空间
table.setPadding(0.6f);
if (widths != null){
//设置宽度
table.setWidths(widths);
}
// 以下两行一般同时使用:设置默认Cell,使用默认Cell填充空的Cell
table.setDefaultCell(createCell(""));
table.setAutoFillEmptyCells(true);
//单元格设置不分页
table.setCellsFitPage(true);
}
public static void addTextFullWaterMark(PdfContentByte waterMar, String text, BaseFont bfChinese) {
waterMar.beginText();
PdfGState gs = new PdfGState();
// 设置填充字体不透明度为0.2f
gs.setFillOpacity(0.2f);
waterMar.setFontAndSize(bfChinese, 12);
// 设置透明度
waterMar.setGState(gs);
// 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
float height = waterMar.getPdfWriter().getPageSize().getHeight();
float width = waterMar.getPdfWriter().getPageSize().getWidth();
for (int x = -80; x <= width; x += 300) {
for (int y = -90; y <= height; y += 300) {
waterMar.showTextAligned(Element.ALIGN_RIGHT, text, x, y, 35);
}
}
// 设置水印颜色
waterMar.setColorFill(Color.GRAY);
//结束设置
waterMar.endText();
waterMar.stroke();
}
/**
* 设置表格的数据单元格样式
*
* @param text 单元格内容
*/
public static Cell createCell(String text) {
return createCell(text, 1);
}
/**
* 设置表格的数据单元格样式
*
* @param text 文本
* @param colSpan colSpan
* @return Cell
*/
public static Cell createCell(String text, int colSpan) {
return createCell(text, colSpan, HorizontalAlignment.LEFT);
}
/**
* 设置表格的数据单元格样式
*
* @param text 文本
* @param colSpan colSpan
* @param font 字体
* @return Cell
*/
public static Cell createCell(String text, int colSpan, Font font) {
return createCell(text, colSpan, HorizontalAlignment.LEFT, true, font);
}
/**
* 设置表格的数据单元格样式
*
* @param text 文本
* @param isBold 是否粗体
* @return Cell
*/
public static Cell createCell(String text, boolean isBold) {
return createCell(text, 1, HorizontalAlignment.LEFT, isBold, null);
}
/**
* 设置表格的数据单元格样式
*
* @param text 文本
* @param colSpan colSpan
* @param horizontalAlign 水平对齐方式
* @return Cell
*/
public static Cell createCell(String text, int colSpan, HorizontalAlignment horizontalAlign) {
return createCell(text, colSpan, horizontalAlign, true, null);
}
/**
* 设置表格的数据单元格样式
*
* @param text 文本
* @param colSpan colSpan
* @param horizontalAlign 水平对齐方式
* @param isBold 是否粗体
* @param font 字体
* @return Cell
*/
public static Cell createCell(String text, int colSpan, HorizontalAlignment horizontalAlign, boolean isBold, Font font) {
Font realFont = isBold ? new Font(MSYHL, 10f, BOLD) : new Font(MSYHL, 10f);
if(font != null){
realFont = font;
}
Paragraph paragraph = new Paragraph(text, realFont);
paragraph.setLeading(18, 18);
Cell cell = new Cell(paragraph);
cell.setColspan(colSpan);
// 设置水平对齐方式
cell.setHorizontalAlignment(horizontalAlign);
// 设置垂直对齐方式
cell.setVerticalAlignment(VerticalAlignment.CENTER);
// 设置单元格边框颜色,同样用四个bit位分别表示上(0001)、下(0010)、左(0100)、右(1000)四个边
cell.setBorder(Rectangle.BOX);
cell.setBorderWidth(1);
return cell;
}
}
导出pdf文件
@Test
public void exportPdf() throws Exception {
String pdfFile = "E:\\TableExample.pdf";
// 设置第一页为A3大小
Document document = new Document(PageSize.A3);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
//添加水印
PdfUtils.addWaterMark(document, writer);
// 添加页脚
PdfUtils.addFooter(document);
// 打开文档
document.open();
// 绘制第一页的表格内容
addTable(document);
// 关闭文档流
document.close();
System.out.println("=========done=========");
}
private static void addTable(Document document) {
Paragraph title = new Paragraph("大标题", new Font(PdfUtils.MSYH, 16, BOLD));
title.setLeading(60);
title.setAlignment(Element.ALIGN_CENTER);
document.add(title);
Paragraph tableTopText = new Paragraph("其余标题", new Font(PdfUtils.MSYH, 13, BOLD));
tableTopText.setSpacingBefore(45);
tableTopText.setAlignment(Element.ALIGN_LEFT);
document.add(tableTopText);
Table table = new Table(5);
int[] widths = new int[]{11, 20, 20, 20, 29};
PdfUtils.setTableStyle(table, widths);
table.addCell(PdfUtils.createCell("序号", 1, HorizontalAlignment.CENTER));
table.addCell(PdfUtils.createCell("编号", 1, HorizontalAlignment.CENTER));
table.addCell(PdfUtils.createCell("名称", 1, HorizontalAlignment.CENTER));
table.addCell(PdfUtils.createCell("模式", 1, HorizontalAlignment.CENTER));
table.addCell(PdfUtils.createCell("详情", 1, HorizontalAlignment.CENTER));
for (int i = 0; i < 500; i++){
table.addCell(PdfUtils.createCell(String.valueOf(i + 1), false));
table.addCell(PdfUtils.createCell("11111111111111111111", false));
table.addCell(PdfUtils.createCell("人工智能", false));
table.addCell(PdfUtils.createCell("混合模式", false));
table.addCell(PdfUtils.createCell("人工智能................", false));
}
document.add(table);
}
这样导出的文档是竖向的,如果想要导出横向的文档,可在设置页面的时候设置为横向的Document document = new Document(PageSize.*A3*.rotate());
优雅的在项目中使用
generatePdf(new PdfContentInfo(), new ExportPdfModel<>(province, list), PageSize.A3, new TestPdfHandler(), "导出错误");
/**
* Title:生成pdf文件
*
* @param <E>
* @param info 生成文件信息
* @param data 用于填充的数据
* @param handler 填充数据的handler
* @param msg 错误日志输出信息
* @return
* @throws CommonException
*/
protected <E> File generatePdf(PdfContentInfo info, E data, Rectangle pageSize,
DocumentWithDataHandler<E> handler, String msg) throws CommonException {
try {
return PdfTemplateHelper.generatePdf(info, data, pageSize, handler);
} catch (Exception e) {
logger.error(msg, e);
throw new CommonException(errorMessage);
}
}
public class PdfTemplateHelper {
public static <E> File generatePdf(PdfContentInfo info, E data, Rectangle pageSize, DocumentWithDataHandler<E> handler) throws Exception {
AssertUtil.notNull(info, "info can not be null.");
File file = new File(getSavePath(info) + "/" + getFileName(info));
// 文件存在,不重新生成,直接返回
if (!info.isAlwaysNew() && file.exists()) return file;
Document document = new Document(pageSize);
PdfWriter writer = null;
try {
writer = PdfWriter.getInstance(document, new FileOutputStream(file));
//添加水印
PdfUtils.addWaterMark(document, writer);
// 添加页脚
PdfUtils.addFooter(document);
// 打开文档
document.open();
//写入数据
handler.fillDocument(document, data);
}finally {
document.close();
}
return file;
}
protected static Resource getResource(AbstractContentInfo info) {
return (new DefaultResourceLoader()).getResource(info.getTemplateUrl());
}
protected static String getFileName(AbstractContentInfo info) {
return hasText(info.getFileName()) ? info.getFileName() : FileTools.generateUUIDName((String)null);
}
protected static String getSavePath(AbstractContentInfo info) {
return hasText(info.getSavePath()) ? info.getSavePath() : FileHelper.getTmpPath();
}
}
import com.lowagie.text.Document;
public interface DocumentWithDataHandler<E> {
/**
* 填充pdf数据的回调接口
*
* @param document
* 待填充的pdf
* @param data
* 用于填充的数据
* @throws Exception
*/
public void fillDocument(Document document, E data) throws Exception;
}
import com.lowagie.text.*;
import com.lowagie.text.alignment.HorizontalAlignment;
import java.util.List;
import static com.lowagie.text.Font.BOLD;
public class TestPdfHandler implements DocumentWithDataHandler<ExportPdfModel> {
@Override
public void fillDocument(Document document, ExportPdfModel data) throws Exception {
Paragraph title = new Paragraph(data.getProvince() + "考勤信息", new Font(PdfUtils.MSYH, 16, BOLD));
title.setLeading(60);
title.setAlignment(Element.ALIGN_CENTER);
document.add(title);
Paragraph tableTopText = new Paragraph("部门盖章:", new Font(PdfUtils.MSYH, 13, BOLD));
tableTopText.setSpacingBefore(45);
tableTopText.setAlignment(Element.ALIGN_LEFT);
document.add(tableTopText);
Table table = new Table(5);
int[] widths = new int[]{11, 20, 20, 20, 29};
PdfUtils.setTableStyle(table, widths);
table.addCell(PdfUtils.createCell("序号", 1, HorizontalAlignment.CENTER));
table.addCell(PdfUtils.createCell("编号", 1, HorizontalAlignment.CENTER));
table.addCell(PdfUtils.createCell("名称", 1, HorizontalAlignment.CENTER));
table.addCell(PdfUtils.createCell("模式", 1, HorizontalAlignment.CENTER));
table.addCell(PdfUtils.createCell("详情", 1, HorizontalAlignment.CENTER));
for (int i = 0; i < 500; i++){
table.addCell(PdfUtils.createCell(String.valueOf(i + 1), false));
table.addCell(PdfUtils.createCell("11111111111111111111", false));
table.addCell(PdfUtils.createCell("人工智能", false));
table.addCell(PdfUtils.createCell("混合模式", false));
table.addCell(PdfUtils.createCell("人工智能................", false));
}
document.add(table);
}
}
附代码中使用到的model
ExportPdfModel
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class ExportPdfModel<T> extends BaseModel {
private String province;
private List<T> data;
}
PdfContentInfo
public class PdfContentInfo extends AbstractContentInfo {
private List<String> fonts;
public PdfContentInfo() {
}
public List<String> getFonts() {
return this.fonts;
}
public PdfContentInfo setFonts(List<String> fonts) {
this.fonts = fonts;
return this;
}
}
AbstractContentInfo
public abstract class AbstractContentInfo extends BaseModel {
protected String templateUrl;
protected String templateEncoding;
protected String savePath;
protected String fileName;
protected boolean alwaysNew = true;
}