pom引入
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
itextpdf
相关代码
一、创建一个Document实例。
一共有三个构造方法,
public Document();
// 默认PageSize.A4
Document document = new Document();
public Document(Rectangle pageSize);
// 设置大小
Rectangle pageSize = new Rectangle(300, 500);
// 设置背景颜色
pageSize.setBackgroundColor(new BaseColor(0xFF, 0xFF, 0xDE));
// 设置边框
pageSize.setBorder(1220);
// 设置边框颜色
pageSize.setBorderColor(new BaseColor(0xFF, 0xFF, 0xDE));
// 边框宽度
pageSize.setBorderWidth(244.2f);
Document document = new Document(pageSize);
// 设置横向打印
Document document = new Document(PageSize.A4.rotate());
public Document(Rectangle pageSize,int marginLeft,int marginRight,int marginTop,int marginBottom);
// Rectangl-左边距-右边距-上边距-下边距
// 边距默认以磅为单位,默认边距是36磅,至于和厘米,英寸等其它单位的换算这里就不详细介绍了,注意一点就是,边距是针对整个文件生效的,故慎用,如果没有特别需求,使用默认的就可以了。
Document document =new Document(PageSize.A4,50,50,30,20);
二、创建Writer实例
// 建立一个书写器(Writer)与document对象关联,后面对document任何操作都会写入流中
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfWriter.getInstance(document, outputStream);
设置文档密码
//用户密码
String userPassword = "123456";
//拥有者密码
String ownerPassword = "hd";
writer.setEncryption(userPassword.getBytes(), ownerPassword.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
设置文档权限
writer.setEncryption("".getBytes(), "".getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
设置水印
writer.setPageEvent(new PdfWidget().new Watermark());
三、打开Document
// 打开文档
document.open();
在写入实际内容前,我们通常需要设置文件的一些属性,比如作者、标题、摘要等
// 作者
document.addAuthor("feng");
// 创建日期
document.addCreationDate();
// 创建关键字
document.addKeywords("测试");
// 创建生产商,自动使用iText
document.addProducer();
// 创建程序
document.addCreator("www.ydc51.com");
// 标题
document.addTitle("测试标题");
// 主题
document.addSubject("测试PDF创建的主题");
四、设置字体
// 方式一(推荐):使用Windows系统字体
BaseFont baseFont = BaseFont.createFont("c://windows//fonts//simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 方式二:使用资源字体(ClassPath)
BaseFont baseFont = BaseFont.createFont("/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 方式三:使用iTextAsian.jar中的字体
BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font font = new Font(baseFont);
// 设置字体大小
font.setSize(13);
// 设置字体颜色
font.setColor(new BaseColor(255, 0, 0));
// 设置类型,加粗
font.setStyle(Font.BOLD);
// 设置类型,倾斜
font.setStyle(Font.ITALIC);
// 设置类型,下划线
font.setStyle(Font.UNDERLINE);
// 设置类型,可组合,倾斜+删除线
font.setStyle(Font.ITALIC | Font.STRIKETHRU);
五、添加内容
document.add(Element element)
块
Chunk:块(Chunk)是能被添加到文档的文本的最小单位。
// 块
Chunk chunk = new Chunk("语句块");
// 设置字体,字体定宽
chunk.setFont(font);
// 设置背景颜色
chunk.setBackground(new BaseColor(0xFF, 0xFF, 0x00));
//使用块来构造段落
Paragraph paragraph = new Paragraph(chunk);
短句
Phrase:短句(Phrase)是一系列以特定间距(两行之间的距离)作为参数的块。
// 短句
Phrase phrase = new Phrase(content);
// 设置字体
phrase.setFont(font);
// 设置间距
phrase.setLeading(30f);
// 使用短句来构造段落
Paragraph paragraph = new Paragraph(phrase);
段落
Paragraph :段落是一系列块和(或)短句。添加到文档中的每一个段落将自动另起一行。
// 段落
Paragraph paragraph = new Paragraph("段落", font);
// 对齐方式
paragraph.setAlignment(alignment);
// 左缩进
paragraph.setIndentationLeft(indentationLeft);
// 右缩进
paragraph.setIndentationRight(indentationRight);
// 首行缩进
paragraph.setFirstLineIndent(firstLineIndent);
// 行间距
paragraph.setLeading(fixedLeading);
// 设置上空白
paragraph.setSpacingBefore(spacingBefore);
// 设置段落下空白
paragraph.setSpacingAfter(spacingAfter);
表格
PdfPTable:
// 表格,设置列数量
Table table = new Table(3);
// 设置每列宽度比例
table.setWidths(new int[]{10, 45, 45});
// 占页面宽度比例
table.setWidth(95);
PdfPCell:
// 格
PdfPCell cell = new PdfPCell(new Paragraph(value, font));
// 合并单元格列
cell.setColspan(1);
// 设置水平(Element.ALIGN_CENTER = 居中)
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
// 设置垂直(Element.ALIGN_CENTER = 居中)
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// 单元格高度
cell.setFixedHeight(30.0f);
// 单元格背景颜色
cell.setBackgroundColor(new BaseColor(190, 190, 190));
// 设置单元格边线宽度(0为没有边线)
cell.setBorder(0);
// 设置单元格上边线宽度
cell.setBorderWidthTop(0);
// 设置单元格上边线宽度
cell.setBorderWidthBottom(0);
// 设置单元格上边线宽度
cell.setBorderWidthLeft(0);
// 设置单元格上边线宽度
cell.setBorderWidthRight(0);
// 添加单元
table.addCell(cell);
图片
Image img = Image.getInstance("C:/Users/H__D/Desktop/IMG_0109.JPG");
// 设置图片位置的x轴和y轴
img.setAbsolutePosition(100f, 550f);
// 设置图片的宽度和高度
img.scaleAbsolute(200, 200);
// 设置图片居中
img.setAlignment(Image.MIDDLE);
// 设置图片边线
img.setBorder(Image.BOX);
// 设置图片边线宽度
img.setBorderWidth(10);
// 设置图片背景
img.setBorderColor(BaseColor.WHITE);
// 设置图片大小
img.scaleToFit(900, 350);
//依照比例缩放
img.scalePercent(40);
// 旋转
img.setRotationDegrees(-30);
六、文档新建页
document.newPage();
七、关闭文档
document.close();
示例效果
示例代码
@Override
public FileInfo exportPdf(Long id) throws Exception {
TestBedReport report = getById(id);
ReportDataDTO data = JSONObject.parseObject(report.getJsonContent(), ReportDataDTO.class);
Document document = new Document();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfWriter.getInstance(document, outputStream);
BaseFont bfChinese = BaseFont.createFont(PDF_BASE_FONT_SIMHEI, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font bold14 = new Font(bfChinese, 14, Font.BOLD);
Font normal9 = new Font(bfChinese, 9, Font.NORMAL);
Font normal11 = new Font(bfChinese, 11, Font.NORMAL);
document.open();
createHead(document, normal9, bold14);
createTableTitle(document, TESTBED_NAMEPLATE_NAME, normal11);
createTableCell(document, data.getNameplateParameter(), TESTBED_NAMEPLATE_COLUMN_WIDTHS, normal9, TESTBED_NAMEPLATE_COLUMN_NAME, TESTBED_NAMEPLATE_COLUMN_KEY);
createTableTitle(document, TESTBED_TEST_CONDITIONS_NAME, normal9);
createTableCell(document, data.getTestConditions(), TESTBED_TEST_CONDITIONS_COLUMN_WIDTHS, normal9, TESTBED_TEST_CONDITIONS_COLUMN_NAME, TESTBED_TEST_CONDITIONS_COLUMN_KEY);
createTableTitle(document, TESTBED_CALCULATION_RESULT_NAME, normal9);
createTableCell(document, data.getCalculationResult(), TESTBED_CALCULATION_RESULT_COLUMN_WIDTHS, normal9, TESTBED_CALCULATION_RESULT_COLUMN_NAME, TESTBED_CALCULATION_RESULT_COLUMN_KEY);
createTail(document, normal9, report, TESTBED_TAIL_INFOS, Boolean.TRUE);
document.newPage();
createHead(document, normal9, bold14);
createTableTitle(document, TESTBED_TEST_DATA_NAME, normal9);
createTableCell(document, data.getTestData(), TESTBED_TEST_DATA_COLUMN_WIDTHS, normal9, TESTBED_TEST_DATA_COLUMN_NAME, TESTBED_TEST_DATA_COLUMN_KEY);
createTail(document, normal9, report, TESTBED_TAIL_INFOS, Boolean.FALSE);
document.close();
FileInfo fileInfo = new FileInfo();
fileInfo.setFilename(report.getFileName() + PDF_FORMAT);
fileInfo.setInputStream(new ByteArrayInputStream(outputStream.toByteArray()));
return fileInfo;
}
/**
* 创建表格标题
*
* @param document 文档
* @param text 标题内容
* @param font 字体
* @throws Exception
*/
private void createTableTitle(Document document, String text, Font font) throws Exception {
PdfPTable table = new PdfPTable(1);
float[] widths = {1f};
table.setWidths(widths);
table.setWidthPercentage(100);
PdfPCell cell = new PdfPCell(new Paragraph(text, font));
cell.setColspan(1);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setFixedHeight(30.0f);
table.addCell(cell);
document.add(table);
}
/**
* 创建表格数据
*
* @param document 文档
* @param dataList 数据集
* @param relativeWidths 每格宽度数组
* @param font 字体
* @param columnNames 表头名数组
* @param columnKeys 字段Key数组
* @param <T>
* @throws Exception
*/
private <T> void createTableCell(Document document, List<T> dataList, float[] relativeWidths, Font font, String[] columnNames, String[] columnKeys) throws Exception {
PdfPTable table = new PdfPTable(columnNames.length);
table.setWidths(relativeWidths);
table.setWidthPercentage(PDF_WIDTH_PERCENTAGE);
for (String columnName : columnNames) {
PdfPCell label = new PdfPCell(new Paragraph(columnName, font));
label.setColspan(1);
label.setHorizontalAlignment(Element.ALIGN_CENTER);
label.setVerticalAlignment(Element.ALIGN_MIDDLE);
label.setFixedHeight(20.0f);
label.setBackgroundColor(new BaseColor(190, 190, 190));
table.addCell(label);
}
for (T t : dataList) {
for (String columnKey : columnKeys) {
Field field = t.getClass().getDeclaredField(columnKey);
field.setAccessible(true);
String value = field.get(t).toString();
PdfPCell cell = new PdfPCell(new Paragraph(value, font));
cell.setColspan(1);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setFixedHeight(20.0f);
table.addCell(cell);
}
}
document.add(table);
}
/**
* 创建头部
*
* @param document 文档
* @param normal7 字体
* @param bold12 字体
* @throws Exception
*/
private void createHead(Document document, Font normal7, Font bold12) throws Exception {
PdfPTable head = new PdfPTable(3);
float[] widthsTitle = {1f, 1f, 1f};
head.setWidths(widthsTitle);
head.setWidthPercentage(PDF_WIDTH_PERCENTAGE);
createHeadPosition(TESTBED_HEAD_LEFT, head, normal7, Element.ALIGN_LEFT, Element.ALIGN_BOTTOM);
createHeadPosition(TESTBED_HEAD_CENTER, head, bold12, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE);
createHeadPosition(TESTBED_HEAD_RIGHT, head, normal7, Element.ALIGN_RIGHT, Element.ALIGN_TOP);
document.add(head);
document.add(new Paragraph(StrUtil.LF));
}
/**
* 创建头部具体部位
*
* @param text 内容
* @param table 表格
* @param font 字体
* @param horizontalAlignment 左右对齐
* @param verticalAlignment 垂直对齐
*/
private void createHeadPosition(String text, PdfPTable table, Font font, int horizontalAlignment, int verticalAlignment) {
PdfPCell cell;
cell = new PdfPCell(new Paragraph(text, font));
cell.setColspan(1);
cell.setHorizontalAlignment(horizontalAlignment);
cell.setVerticalAlignment(verticalAlignment);
cell.setFixedHeight(20.0f);
cell.setBorderWidthRight(0);
cell.setBorderWidthBottom(0);
cell.setBorderWidthLeft(0);
cell.setBorderWidthTop(0);
table.addCell(cell);
}
/**
* 创建尾部
*
* @param document 文档
* @param normal7 字体
* @param data 数据
* @param tailInfos 尾部信息
* @param remarkFlag 是否备注
* @throws Exception
*/
private void createTail(Document document, Font normal7, TestBedReport data, String[] tailInfos, boolean remarkFlag) throws Exception {
PdfPTable remarkTable;
if (remarkFlag) {
remarkTable = new PdfPTable(2);
float[] widths = {2f, 8f};
remarkTable.setWidths(widths);
remarkTable.setWidthPercentage(PDF_WIDTH_PERCENTAGE);
PdfPCell cell1 = new PdfPCell(new Paragraph("备注", normal7));
PdfPCell cell2 = new PdfPCell(new Paragraph(StrUtil.EMPTY, normal7));
cell1.setColspan(1);
cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell1.setFixedHeight(90.0f);
cell2.setColspan(1);
cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell2.setFixedHeight(90.0f);
remarkTable.addCell(cell1);
remarkTable.addCell(cell2);
} else {
remarkTable = new PdfPTable(1);
float[] widths = {1f};
remarkTable.setWidths(widths);
remarkTable.setWidthPercentage(PDF_WIDTH_PERCENTAGE);
PdfPCell cell = new PdfPCell(new Paragraph(StrUtil.EMPTY, normal7));
cell.setColspan(1);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setFixedHeight(40.0f);
remarkTable.addCell(cell);
}
PdfPTable infoTable = new PdfPTable(tailInfos.length);
infoTable.setWidths(TESTBED_TAIL_INFOS_WIDTHS);
infoTable.setWidthPercentage(PDF_WIDTH_PERCENTAGE);
for (String info : tailInfos) {
PdfPCell cell = new PdfPCell(new Paragraph(String.format(info, data.getFileName()), normal7));
cell.setColspan(1);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setFixedHeight(20.0f);
infoTable.addCell(cell);
}
document.add(remarkTable);
document.add(infoTable);
}
自定义常量
package io.test.constant;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
/**
* @author ****
* @date 2023-01-13 10:47
*/
@Data
public class PdfConstant {
/**
* PDF格式
*/
public static final String PDF_FORMAT = ".pdf";
/**
* PDF字体
*/
public static final String PDF_BASE_FONT_SIMHEI = "c://windows//fonts//simhei.ttf";
/**
* PDF宽度百分比
*/
public static final Float PDF_WIDTH_PERCENTAGE = 100F;
/**
* 试验台试验报告------------------
*/
public static final String TESTBED_HEAD_LEFT = "****技股份有限公司";
public static final String TESTBED_HEAD_CENTER = "试 验 报 告";
public static final String TESTBED_HEAD_RIGHT = StrUtil.EMPTY;
public static final String TESTBED_TAIL_REMARK = "备注";
public static final String[] TESTBED_TAIL_INFOS = {"试验:", "校队:", "核审:", "Point:%s"};
public static final float[] TESTBED_TAIL_INFOS_WIDTHS = {2f, 2f, 2f, 2f};
public static final String TESTBED_NAMEPLATE_NAME = "****";
public static final float[] TESTBED_NAMEPLATE_COLUMN_WIDTHS = {2f, 2f, 2f, 2f};
public static final String[] TESTBED_NAMEPLATE_COLUMN_NAME = {"**项目", "**内容", "**项目", "**内容"};
public static final String[] TESTBED_NAMEPLATE_COLUMN_KEY = {"name", "content"};
public static final String TESTBED_TEST_CONDITIONS_NAME = "****";
public static final float[] TESTBED_TEST_CONDITIONS_COLUMN_WIDTHS = {1f, 1f, 1f, 1f, 1f, 1f};
public static final String[] TESTBED_TEST_CONDITIONS_COLUMN_NAME = {"**项目", "**单位", "设定值", "工况**", "物理单位", "设定值"};
public static final String[] TESTBED_TEST_CONDITIONS_COLUMN_KEY = {"item", "unit", "value"};
public static final String TESTBED_CALCULATION_RESULT_NAME = "计算结果";
public static final float[] TESTBED_CALCULATION_RESULT_COLUMN_WIDTHS = {2f, 2f, 2f};
public static final String[] TESTBED_CALCULATION_RESULT_COLUMN_NAME = {"计算项目", "物理单位", "计算结果"};
public static final String[] TESTBED_CALCULATION_RESULT_COLUMN_KEY = {"item", "unit", "result"};
public static final String TESTBED_TEST_DATA_NAME = "测试数据";
public static final float[] TESTBED_TEST_DATA_COLUMN_WIDTHS = {2f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f};
public static final String[] TESTBED_TEST_DATA_COLUMN_NAME = {"**名称", "**单位", "No1", "No2", "No3", "No4", "No5", "No6", "No7", "平均值"};
public static final String[] TESTBED_TEST_DATA_COLUMN_KEY = {"item", "unit", "no_1", "no_2", "no_3", "no_4", "no_5", "no_6", "no_7", "average"};
}