首先依赖包
我是spring boot项目,在pom.xml中添加依赖
<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>
下面是生成PDF代码
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.draw.LineSeparator;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class PDFReport {
// 定义全局的字体静态变量
private static Font titlefont;
private static Font headfont;
private static Font keyfont;
private static Font textfont;
private static Font firstLevel;
private static Font secondLevel;
private static Font threeLevel;
private static Font timefont;
// 最大宽度
private static int maxWidth = 500;
// 静态代码块
static {
try {
// 不同字体(这里定义为同一种字体:包含不同字号、不同style)
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 18, Font.NORMAL);
headfont = new Font(bfChinese, 12, Font.BOLD);
keyfont = new Font(bfChinese, 10, Font.BOLD);
textfont = new Font(bfChinese, 8, Font.NORMAL);
firstLevel = new Font(bfChinese, 10, Font.NORMAL);
secondLevel = new Font(bfChinese, 8, Font.BOLD);
threeLevel = new Font(bfChinese, 8, Font.NORMAL);
timefont = new Font(bfChinese, 6, Font.BOLD);
} catch (Exception e) {
e.printStackTrace();
}
}
// 生成PDF文件
public static void generatePDF() throws Exception {
// 生成文件地址
String pdfPath ="D://"+ new Random().nextInt(99) + "-" + System.nanoTime() + ".pdf";
// 1.新建document对象
Document document = new Document(PageSize.A4);// 建立一个Document对象
// 2.建立一个书写器(Writer)与document对象关联
File file = new File(pdfPath);
file.createNewFile();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// 3.打开文档
document.open();
document.addTitle("标题");// 标题
document.addSubject("主题");// 主题
document.addKeywords("关键字");// 关键字
document.addCreator("创建者");// 创建者
// 段落
Paragraph paragraph = new Paragraph("文档标题", titlefont);
paragraph.setAlignment(1); //设置文字居中 0靠左 1,居中 2,靠右
// paragraph.setIndentationLeft(12); //设置左缩进
// paragraph.setIndentationRight(12); //设置右缩进
// paragraph.setFirstLineIndent(24); //设置首行缩进
paragraph.setLeading(20f); //行间距
paragraph.setSpacingBefore(5f); //设置段落上空白
paragraph.setSpacingAfter(10f); //设置段落下空白
document.add(paragraph);// 将内容添加进文档,必不可少,否则不显示相应内容
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
Paragraph time = new Paragraph("生成时间:" + sdf.format(d), timefont);
time.setAlignment(0); //设置文字居中 0靠左 1,居中 2,靠右
time.setLeading(20f); //行间距
time.setSpacingBefore(5f); //设置段落上空白
time.setSpacingAfter(3f); //设置段落下空白
document.add(time);// 将内容添加进文档
// 直线
Paragraph p1 = new Paragraph();
LineSeparator lineSeparator = new LineSeparator();
lineSeparator.setLineColor(new BaseColor(228, 228, 228));
p1.add(new Chunk(lineSeparator));
p1.setSpacingBefore(2f); //设置段落上空白
p1.setSpacingAfter(2f); //设置段落下空白
// 段落外框
ParagraphBorder border = new ParagraphBorder();
writer.setPageEvent(border);
border.setActive(true);
Paragraph title = new Paragraph();
title.setIndentationLeft(10); //设置左缩进
title.setSpacingBefore(10f); //设置段落上空白
title.setSpacingAfter(30f); //设置段落下空白
document.add(title);// 将内容添加进文档
border.setActive(false);
border.setActive(true, -5);
Paragraph baseInfo = new Paragraph("基础信息", firstLevel);
baseInfo.setIndentationLeft(12); //设置左缩进
baseInfo.setSpacingBefore(6f); //设置段落上空白
baseInfo.setSpacingAfter(20f); //设置段落下空白
document.add(baseInfo);// 将内容添加进文档
border.setActive(false, -5);
// 表格
PdfPTable pdfPTable = createTable(new float[]{20,30,60,70,80},520);
pdfPTable.addCell(createCell("标题1", secondLevel, Element.ALIGN_LEFT));
pdfPTable.addCell(createCell("标题2", secondLevel, Element.ALIGN_LEFT));
pdfPTable.addCell(createCell("标题3", secondLevel, Element.ALIGN_LEFT));
pdfPTable.addCell(createCell("标题4", secondLevel, Element.ALIGN_LEFT));
pdfPTable.addCell(createCell("标题5", secondLevel, Element.ALIGN_LEFT));
for (int i = 0; i < 20; i++) {
pdfPTable.addCell(createCell("内容"+(i+1), threeLevel, Element.ALIGN_LEFT));
}
document.add(pdfPTable);// 将内容添加进文档
document.add(new Chunk("\n\n")); // 换行
/**------------------------大框嵌套表格开始----------------------------*/
// 大表格
PdfPTable bigTable = createTable(new float[]{200},520);
// 标题表格
PdfPTable titleTable = createTable(new float[]{200},520);
PdfPCell cell = createCell("大标题", firstLevel, Element.ALIGN_LEFT);
cell.disableBorderSide(3); // 隐藏上下边框
cell.setPadding(15f);
cell.setPaddingLeft(15f); // 表格内边距
titleTable.addCell(cell);
// 内容表格
PdfPTable contentTable = createTable(new float[]{80, 200},500);
contentTable.addCell(createCell("标题1", secondLevel, Element.ALIGN_CENTER)); // 将单元格加入到表格中
contentTable.addCell(createCell("标题2", secondLevel, Element.ALIGN_CENTER)); // 将单元格加入到表格中
for (int i = 0; i <6 ; i++) {
contentTable.addCell(createCell("内容"+(i+1), threeLevel, Element.ALIGN_CENTER));
}
// 标题表格
PdfPTable tableHorizontal = createTable(new float[]{200},520);
PdfPCell cellHorizontal = createCell("横向列表", firstLevel, Element.ALIGN_LEFT);
cellHorizontal.disableBorderSide(3); // 隐藏上下边框
cellHorizontal.setPaddingLeft(15f); // 表格内边距
cell.setPadding(15f);
tableHorizontal.addCell(cell);
// 内容表格
PdfPTable contentHorizontal = createTable(new float[]{80, 200,80,200},500);
for (int i = 0; i <12 ; i++) {
if (i%2 == 0) {
contentHorizontal.addCell(createCell("标题"+(i+1), secondLevel, Element.ALIGN_CENTER)); // 将单元格加入到表格中
} else {
contentHorizontal.addCell(createCell("内容"+(i+1), threeLevel, Element.ALIGN_CENTER));
}
}
// 将标题内容添加
PdfPCell item = new PdfPCell();
item.setBorderColor(new BaseColor(155, 155, 155));
item.addElement(titleTable);
item.addElement(contentTable);
item.addElement(tableHorizontal);
item.addElement(contentHorizontal);
item.addElement(new Chunk("\n\n"));
bigTable.addCell(item);
document.add(bigTable);
/**------------------------大框嵌套表格结束----------------------------*/
// 关闭文档
document.close();
writer.close();
}
/**------------------------设置数据----------------------------*/
/**------------------------创建表格单元格的方法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_LEFT);
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.setPadding(5f); // 表格内边距
cell.setBorderColor(new BaseColor(155, 155, 155)); // 表格线条颜色
return cell;
}
/**
* 创建单元格(指定字体、水平..)
*
* @return
*/
public PdfPCell createCell() {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setBorderColor(new BaseColor(155, 155, 155));
return cell;
}
/**
* 创建单元格(指定字体、水平居..、单元格跨x列合并)
*
* @param value
* @param font
* @param align
* @param colspan
* @return
*/
public 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));
return cell;
}
/**
* 创建单元格(指定字体、水平居..、单元格跨x列合并、设置单元格内边距)
*
* @param value
* @param font
* @param align
* @param colspan
* @param boderFlag
* @return
*/
public 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 数组个数为列数,数组值为宽度比
* @param maxWidth 表格宽度
* @return
*/
public static PdfPTable createTable(float[] widths, int maxWidth) {
PdfPTable table = new PdfPTable(widths);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.setSplitLate(true);
table.setSplitRows(true);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* 创建空白的表格
*
* @return
*/
public static 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;
}
/**
* --------------------------创建段落外框------------------- ---------
*/
static class ParagraphBorder extends PdfPageEventHelper {
public boolean active = false;
public void setActive(boolean active) {
this.active = active;
}
public void setActive(boolean active, float offset) {
this.active = active;
this.offset = offset;
}
public float offset = -5;
public float startPosition;
@Override
public void onParagraph(PdfWriter writer, Document document, float paragraphPosition) {
this.startPosition = paragraphPosition;
}
@Override
public void onParagraphEnd(PdfWriter writer, Document document, float paragraphPosition) {
if (active) {
PdfContentByte cb = writer.getDirectContentUnder();
cb.setColorStroke(new BaseColor(155, 155, 155));
cb.rectangle(document.left(), paragraphPosition - offset,
document.right() - document.left(), startPosition - paragraphPosition);
cb.stroke();
}
}
}
}