1.前期准备
引入包
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
- itextpdf:核心包
- itext-asian:中文包,如果需要有中文字体,就需要有这个包
2.开发实施
创建打印基类
public abstract class BasePrintServiceImpl<T> {
//定义全局的字体静态变量
protected static Font titlefont; //标题字体
protected static Font textfont; //正文字体
/**
* 初始化字体
* STSong-Light:字体名称
* UniGB-UCS2-H:编码格式
*
*/
static {
try {
// 不同字体(这里定义为同一种字体:包含不同字号、不同style)
// STSong-Light:字体名称 UniGB-UCS2-H:编码格式
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// 初始化中文字体 Font.BOLD:加粗 Font.NORMAL:正常
titlefont = new Font(bfChinese, 22, Font.BOLD);
textfont = new Font(bfChinese, 10, Font.NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
}
// 生成pdf文件,并返回字节数据
byte[] generateByte(T entity, boolean isHeng) throws Exception {
// 1.新建document对象
Document document = new Document();// 建立一个Document对象
if (isHeng == true) {
// 自定义纸张大小,此处设置为横向的A4
Rectangle pageSize = new Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth());
pageSize.rotate();
document.setPageSize(pageSize);
} else {
// 页面大小为A4(默认值)
document = new Document(PageSize.A4);
}
// 字节数组输出流,将文档以字节数据(二进制)的形式响应回去
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, byteOut);
// 水印
//writer.setPageEvent(new Watermark(WATER_MAKER));
// 页眉/页脚
//writer.setPageEvent(new PdfHeaderFooter());
// 2.打开文档
document.open();
// 3.生成文档内容(调用子类的方法)
generateContent(entity, document);
// 4.关闭文档
document.close();
// 关闭
byteOut.close();
// 返回文档的字节数据
return byteOut.toByteArray();
}
// 子类中实现
protected abstract void generateContent(T entity, Document document) throws Exception;
/**
*
* @param value 单元格内容
* @param font 字体格式
* @param verticalAlignment 垂直对齐方式 (常用:Element.ALIGN_MIDDLE、Element.ALIGN_TOP)
* @param horizontalAlignment 水平对齐方式 (常用:Element.ALIGN_CENTER)
* @param colspan 跨列
* @param colspan 跨行
* @param fixedHeight 单元格高度
* @param paddingLeft 距左边的距离
* @return
*/
public PdfPCell createCell(String value, Font font, Integer verticalAlignment, Integer horizontalAlignment
, Integer colspan, Integer rowspan, Integer fixedHeight, Integer paddingLeft) {
PdfPCell cell = new PdfPCell();
cell.setPhrase(new Phrase(value, font));
cell.setVerticalAlignment(verticalAlignment);
cell.setHorizontalAlignment(horizontalAlignment);
cell.setColspan(colspan);
cell.setRowspan(rowspan);
cell.setPaddingLeft(fixedHeight);
cell.setFixedHeight(fixedHeight);
cell.setFixedHeight(paddingLeft);
// 边框颜色
cell.setBorderColor(BaseColor.BLUE);
// 设置背景颜色
cell.setBackgroundColor(BaseColor.ORANGE);
// 设置无边框
cell.setBorder(Rectangle.NO_BORDER);
return cell;
}
}
创建具体的打印实现类,实现打印的的业务逻辑
public class FiberContractPrintServiceImpl extends BasePrintServiceImpl<CustomerOpinionHandlingListResponse> {
// 调用父类的方法
public byte[] printContractByte(CustomerOpinionHandlingListResponse response) throws Exception {
return super.generateByte(response, false);
}
// 生成文档内容
@Override
protected void generateContent(CustomerOpinionHandlingListResponse response, Document document) throws Exception {
// 标题
Paragraph paragraph = new Paragraph("顾客意见处理单", titlefont_normal_20);
paragraph.setAlignment(1); //设置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //设置左缩进
paragraph.setIndentationRight(12); //设置右缩进
paragraph.setFirstLineIndent(24); //设置首行缩进
paragraph.setLeading(5f); //行间距
paragraph.setSpacingBefore(5f); //设置段落上空白
paragraph.setSpacingAfter(10f); //设置段落下空白
document.add(paragraph);
PdfPTable table1 = createTable(80, Element.ALIGN_CENTER, 500);
// 编号
table1.addCell(createCell("编号:", textfont, Element.ALIGN_LEFT, 40, true));
table1.addCell(createCell("HLJL/QMS.EMS05-001", textfont, Element.ALIGN_RIGHT, 40, true));
// 第一行:顾客名称+下单日期
table1.addCell(createCell("顾客名称", textfont, Element.ALIGN_CENTER, 10));
table1.addCell(createCell("江苏众彩纺织品有限公司", textfont, Element.ALIGN_LEFT, 30));
table1.addCell(createCell("下单日期", textfont, Element.ALIGN_CENTER, 10));
table1.addCell(createCell("20200724", textfont, Element.ALIGN_LEFT, 30));
document.add(table1);
}
}
扩展: iText输出中文的三种字体选择方式,其中如果要使用iTextAsian.jar中的字体,需要导入itext-asian
包
// 1、使用iTextAsian.jar中的字体
BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
// 2.使用Windows系统字体(TrueType)
BaseFont.createFont("C:/WINDOWS/Fonts/SIMYOU.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
// 3.使用资源字体(ClassPath)
BaseFont.createFont("/SIMYOU.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
水印:
给pdf添加文字水印
public class Watermark extends PdfPageEventHelper {
// 水印字体大小
Font FONT = new Font(Font.FontFamily.HELVETICA, 30, Font.BOLD, new GrayColor(0.95f));
// 水印内容
private String waterCont;
public Watermark(String waterCont) {
this.waterCont = waterCont;
}
@Override
public void onEndPage(PdfWriter writer, Document document) {
for(int i=0 ; i<5; i++) {
for(int j=0; j<5; j++) {
ColumnText.showTextAligned(writer.getDirectContentUnder(),
Element.ALIGN_CENTER,
new Phrase(this.waterCont == null ? "HELLO WORLD" : this.waterCont, FONT),
(50.5f+i*350),
(40.0f+j*150),
writer.getPageNumber() % 2 == 1 ? 45 : -45);
}
}
}
}
扩展:
-
cell.setVerticalAlignment(Element.ALIGN_TOP); 上对齐
-
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 中对齐
itext table的单元格边框设置:
itext table的单元格边框设置