项目场景:
需求:根据客户模板,生成对应PDF文件。
例如:客户的doc模板文件:
最终效果展示:
话不多说,上操作:
首先引入pdf相关的依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
1.创建测试实体类
import lombok.Data;
/**
* @author
* @create 2022-03-28 11:51
* @desc
**/
@Data
public class TestData {
private String c1;
private String c2;
private String c3;
private String c4;
private String c5;
}
2.页眉 pdf生成工具类(页眉/页脚)
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.IOException;
/**
* @description pdf生成工具(页眉/页脚)
* @version 1.0
* @author linhx
* @date 2021/10/11 14:20
*/
public class MyHeaderFooter extends PdfPageEventHelper {
// 总页数
PdfTemplate totalPage;
Font hfFont;
{
try {
hfFont = new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 8, Font.NORMAL);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 打开文档时,创建一个总页数的模版
@Override
public void onOpenDocument(PdfWriter writer, Document document) {
PdfContentByte cb =writer.getDirectContent();
totalPage = cb.createTemplate(30, 16);
}
// 一页加载完成触发,写入页眉和页脚
@Override
public void onEndPage(PdfWriter writer, Document document) {
PdfPTable table = new PdfPTable(3);
try {
table.setTotalWidth(PageSize.A4.getWidth() - 100);
table.setWidths(new int[] { 24, 24, 3});
table.setLockedWidth(true);
table.getDefaultCell().setFixedHeight(-10);
table.getDefaultCell().setBorder(Rectangle.BOTTOM);
table.addCell(new Paragraph("页眉", hfFont));// 可以直接使用addCell(str),不过不能指定字体,中文无法显示
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(new Paragraph("第" + writer.getPageNumber() + "页/", hfFont));
// 总页数
PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));
cell.setBorder(Rectangle.BOTTOM);
table.addCell(cell);
// 将页眉写到document中,位置可以指定,指定到下面就是页脚
table.writeSelectedRows(0, -1, 50,PageSize.A4.getHeight() - 20, writer.getDirectContent());
} catch (Exception de) {
throw new ExceptionConverter(de);
}
}
// 全部完成后,将总页数的pdf模版写到指定位置
@Override
public void onCloseDocument(PdfWriter writer, Document document) {
String text = "总" + (writer.getPageNumber()) + "页";
ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text,hfFont), 2, 2, 0);
}
}
3.图片水印工具类
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.IOException;
/**
* @author linhx
* @version 1.0
* @description 水印
* @date 2021/10/11 14:20
*/
public class Watermark extends PdfPageEventHelper {
Font FONT = new Font(Font.FontFamily.HELVETICA, 30, Font.BOLD, new GrayColor(0.95f));
//水印内容
private String waterCont;
public Watermark() {
}
public Watermark(String waterCont) {
this.waterCont = waterCont;
}
@Override
public void onEndPage(PdfWriter writer, Document document) {
try {
float pageWidth = document.right() + document.left();//获取pdf内容正文页面宽度
float pageHeight = document.top() + document.bottom();//获取pdf内容正文页面高度
//设置水印字体格式
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font waterMarkFont = new Font(base, 20, Font.BOLD, BaseColor.LIGHT_GRAY);
PdfContentByte waterMarkPdfContent = writer.getDirectContentUnder();
//水印图片1
Image image = Image.getInstance("D:/apache-tomcat-8.5.57/webapps/upload/tem_file/report/pdf/20220328/1.png");
//水印图片2(印章)
Image image2 = Image.getInstance("D:/apache-tomcat-8.5.57/webapps/upload/tem_file/report/pdf/20220328/2.png");
// set the first background
image.setAbsolutePosition(70, pageHeight - 33);
//X 值越小 靠右, Y值越小 靠上
image2.setAbsolutePosition(pageWidth - 120, pageHeight - 200);
// image of the absolute
//水印图片大小
image.scaleToFit(200, 45);
image2.scaleToFit(100, 100);
waterMarkPdfContent.addImage(image);
waterMarkPdfContent.addImage(image2);
} catch (DocumentException | IOException de) {
de.printStackTrace();
}
}
}
4.pdf工具类,main函数
import com.fjqwkj.cploan.commons.model.creditreport.TCreditReport;
import com.fjqwkj.cploan.commons.model.test.TestData;
import com.fjqwkj.cploan.commons.model.zxmain.TZxMain;
import com.fjqwkj.cploan.commons.utils.DateFormatUtil;
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 lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* @author linhx
* @version 1.0
* @description pdf生成工具
* @date 2021/10/11 14:20
*/
@Slf4j
public class PdfReportUtils {
// 定义全局的字体静态变量
private static Font titlefont;
private static Font headfont;
private static Font keyfont;
private static Font textfont;
// 最大宽度
private static int maxWidth = 520;
// 静态代码块
static {
try {
// 不同字体(这里定义为同一种字体:包含不同字号、不同style)
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 16, java.awt.Font.BOLD);
headfont = new Font(bfChinese, 14, java.awt.Font.BOLD);
keyfont = new Font(bfChinese, 10, java.awt.Font.BOLD);
textfont = new Font(bfChinese, 10, Font.NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
}
/**------------------------创建表格单元格的方法start----------------------------*/
/**
* 创建单元格(指定字体)
*
* @param value
* @param font
* @return
*/
public static PdfPCell createCell(String value, Font font) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 创建单元格(指定字体、水平居..)
*
* @param value
* @param font
* @param align
* @return
*/
public static PdfPCell createCell(String value, Font font, int align) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setPhrase(new Phrase(value, font));
cell.setPaddingTop(8.0f);
cell.setPaddingBottom(8.0f);
return cell;
}
/**
* 创建单元格(指定字体、水平居..、单元格跨x列合并)
*
* @param value
* @param font
* @param align
* @param colspan
* @return
*/
public static PdfPCell createCell(String value, Font font, int align, int colspan) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
cell.setPaddingTop(8.0f);
cell.setPaddingBottom(8.0f);
return cell;
}
/**
* 创建单元格(指定字体、水平居..、单元格跨x列合并、设置单元格内边距)
*
* @param value
* @param font
* @param align
* @param colspan
* @param boderFlag
* @return
*/
public static PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
cell.setPadding(3.0f);
if (!boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(15.0f);
cell.setPaddingBottom(8.0f);
} else if (boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(0.0f);
cell.setPaddingBottom(15.0f);
}
return cell;
}
/**
* 创建单元格(指定字体、水平..、边框宽度:0表示无边框、内边距)
*
* @param value
* @param font
* @param align
* @param borderWidth
* @param paddingSize
* @param flag
* @return
*/
public PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setPhrase(new Phrase(value, font));
cell.setBorderWidthLeft(borderWidth[0]);
cell.setBorderWidthRight(borderWidth[1]);
cell.setBorderWidthTop(borderWidth[2]);
cell.setBorderWidthBottom(borderWidth[3]);
cell.setPaddingTop(paddingSize[0]);
cell.setPaddingBottom(paddingSize[1]);
if (flag) {
cell.setColspan(2);
}
return cell;
}
/**------------------------创建表格单元格的方法end----------------------------*/
/**--------------------------创建表格的方法start------------------- ---------*/
/**
* 创建默认列宽,指定列数、水平(居中、右、左)的表格
*
* @param colNumber
* @param align
* @return
*/
public PdfPTable createTable(int colNumber, int align) {
PdfPTable table = new PdfPTable(colNumber);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(align);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* 创建指定列宽、列数的表格
*
* @param widths
* @return
*/
public static PdfPTable createTable(float[] widths) {
PdfPTable table = new PdfPTable(widths);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* 创建空白的表格
*
* @return
*/
public PdfPTable createBlankTable() {
PdfPTable table = new PdfPTable(1);
table.getDefaultCell().setBorder(0);
table.addCell(createCell("", keyfont));
table.setSpacingAfter(20.0f);
table.setSpacingBefore(20.0f);
return table;
}
/**--------------------------创建表格的方法end------------------- ---------*/
/**
* 单位代发工资回单
* @param title
* @param watermark
* @param path
* @param data
* @return
* @throws Exception
*/
public static File testGenerateReceiptPDF(String title, String watermark, String path, TestData data) throws Exception {
// 1.新建document对象
Document document = new Document(PageSize.A4);// 建立一个Document对象
// 2.建立一个书写器(Writer)与document对象关联
path = path + UUID.randomUUID() + ".pdf";
File file = new File(path);
file.createNewFile();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// 水印
writer.setPageEvent(new Watermark(watermark));
// 页眉/页脚
writer.setPageEvent(new MyHeaderFooter());
// 3.打开文档
document.open();
// 4.向文档中添加内容
new PdfReportUtils().testCreateReceiptPDF(document, title, data);
// 5.关闭文档
document.close();
return file;
}
/**
* 单位代发工资回单
* @param document
* @param title
* @param data
* @throws Exception
*/
private void testCreateReceiptPDF(Document document, String title, TestData data) throws Exception {
// 段落
Paragraph paragraph = new Paragraph(title, titlefont);
//设置文字居中 0靠左 1,居中 2,靠右
paragraph.setAlignment(1);
//设置左缩进
paragraph.setIndentationLeft(12);
//设置右缩进
paragraph.setIndentationRight(12);
//设置首行缩进
paragraph.setFirstLineIndent(24);
//行间距
paragraph.setLeading(20f);
//设置段落上空白
paragraph.setSpacingBefore(5f);
//设置段落下空白
paragraph.setSpacingAfter(10f);
// 表格
PdfPTable table = createTable(new float[]{120, 170, 140, 160, 70});
log.info("createReportPDF() - data: {}", data);
TestTableUtils.createReceiptTable(table, data);
document.add(paragraph);
document.add(table);
}
public static void main(String[] args) throws Exception {
List<TestData> list = new ArrayList<>();
TestData testData1 = new TestData();
testData1.setC1("2022-02-28");
testData1.setC2("工资");
testData1.setC3("10000.00");
testData1.setC4("6221840506013978868");
testData1.setC5("张三");
list.add(testData1);
String path = "D:/apache-tomcat-8.5.57/webapps/upload/tem_file/report/pdf/" + DateFormatUtil.format(new Date(), "yyyyMMdd") + "/";
File realFile = new File(path);
if (!realFile.exists()) {
realFile.mkdirs();
}
for (TestData data : list) {
File file = PdfReportUtils.testGenerateReceiptPDF("单位代发工资回单", "测试水印", path, data);
System.out.println("单位代发工资回单file = " + file);
}
}
}
5.模板数据填充类
import com.fjqwkj.cploan.commons.model.test.TestData;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPTable;
import org.apache.commons.lang3.StringUtils;
/**
* @author linhx
* @version 1.0
* @descriptio pdf生成工具
* @date 2021/10/11 14:20
*/
public class TestTableUtils {
/**
* 单位代发工资回单
* @param table
* @param data
* @return
*/
public static PdfPTable createReceiptTable(PdfPTable table, TestData data) {
return table01(table, data);
}
/**
* 单位代发工资回单
*
* @param table
* @param data
*/
private static PdfPTable table01(PdfPTable table, TestData data) {
table.addCell(PdfReportUtils.createCell("", headfont, Element.ALIGN_CENTER, 5, false));
table.addCell(PdfReportUtils.createCell("", headfont, Element.ALIGN_CENTER, 5, false));
table.addCell(PdfReportUtils.createCell("", headfont, Element.ALIGN_CENTER, 5, false));
table.addCell(PdfReportUtils.createCell("账号:", keyfont, Element.ALIGN_RIGHT,1,false));
table.addCell(PdfReportUtils.createCell("9010212030010000000000", textfont, Element.ALIGN_LEFT,1,false));
table.addCell(PdfReportUtils.createCell("户名:", keyfont, Element.ALIGN_RIGHT,1,false));
table.addCell(PdfReportUtils.createCell("福建某某科技有限公司", textfont, Element.ALIGN_LEFT,2,false));
table.addCell(PdfReportUtils.createCell("币种:", keyfont, Element.ALIGN_RIGHT,1,false));
table.addCell(PdfReportUtils.createCell("人民币", textfont, Element.ALIGN_LEFT,1,false));
table.addCell(PdfReportUtils.createCell("开户行:", keyfont, Element.ALIGN_RIGHT,1,false));
table.addCell(PdfReportUtils.createCell("福建XX银行股份有限公司东街支行", textfont, Element.ALIGN_LEFT,2,false));
table.addCell(PdfReportUtils.createCell("查询日期:", keyfont, Element.ALIGN_RIGHT,1,false));
table.addCell(PdfReportUtils.createCell("2022-03-28", textfont, Element.ALIGN_LEFT,1,false));
table.addCell(PdfReportUtils.createCell("", headfont, Element.ALIGN_CENTER, 5, false));
table.addCell(PdfReportUtils.createCell("交易日期", keyfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell("摘要", keyfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell("交易金额", keyfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell("收款账号", keyfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell("收款户名", keyfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC1()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC2()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC3()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC4()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC5()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC1()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC2()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC3()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC4()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty("王老虎"), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC1()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC2()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC3()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC4()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC5()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC1()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC2()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC3()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC4()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC5()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC1()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC2()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC3()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC4()), textfont, Element.ALIGN_CENTER));
table.addCell(PdfReportUtils.createCell(StringUtils.trimToEmpty(data.getC5()), textfont, Element.ALIGN_CENTER));
return table;
}
// 定义全局的字体静态变量
private static Font titlefont;
private static Font headfont;
private static Font keyfont;
private static Font textfont;
// 最大宽度
private static int maxWidth = 520;
// 静态代码块
static {
try {
// 不同字体(这里定义为同一种字体:包含不同字号、不同style)
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 16, java.awt.Font.BOLD);
headfont = new Font(bfChinese, 14, java.awt.Font.BOLD);
keyfont = new Font(bfChinese, 12, java.awt.Font.BOLD);
textfont = new Font(bfChinese, 12, Font.NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
}
}
6.执行PdfReportUtils.java的main函数测试
7.打开磁盘目录,看到pdf文件已经生成