Java使用itextpdf完成表单导出pdf工具类
下文将简述如何通过itextpdf 导出form表单,涉及的内容有字体设置、创建表格、表格样式设置、安全性设置、表头设置、增加一行包括内容、增加多行、合并列、增加超链接
1.引入依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
2.字体设置
对于导出的内容包含中文需要设置字体,windows系统自带的中文字体文件一般在C:/Windows/Fonts/下,不使用中文字体将显示空白
//获取基础字体
public static BaseFont getBaseFont(String path){
if(baseFont!=null){
return baseFont;
}
BaseFont baseFont=null;
try {
baseFont= BaseFont.createFont(path,
BaseFont.IDENTITY_H,
BaseFont.EMBEDDED);
}catch (Exception e){
e.printStackTrace();
}
return baseFont;
}
/**
* 设置中文字体大小
* @param path 字体路径
* @param fontSize 字体大小
* @param style 样式
* @return
*/
public static Font getChineseFont(String path,int fontSize,int style){
Font chineseFont = null;
try {
BaseFont baseFont = getBaseFont(path);
chineseFont = new Font(baseFont, fontSize);
chineseFont.setStyle(style);
}catch (Exception e){
e.printStackTrace();
}
return chineseFont;
}
3.创建表格
/**
* 获取一个table
* @param tableColNum 列数
* @param widthPercentage 宽度显示百分比
* @param spacingBefore 设置前间距
* @param spacingAfter 设置后间距
* @param columnWidths 设置表格列宽,格式{2f,2f},注意集合数量与列数相同,按顺序定义列宽
* @return
*/
public static PdfPTable getTable(Integer tableColNum,float widthPercentage,float spacingBefore,float spacingAfter, float[] columnWidths){
if(tableColNum==null||tableColNum==0){
return null;
}
PdfPTable table = new PdfPTable(tableColNum); //创建一个tableColNum的表格
table.setWidthPercentage(widthPercentage);//设置百分比
table.setSpacingBefore(spacingBefore);//设置前间距
table.setSpacingAfter(spacingAfter);//设置后间距
// 设置表格列宽
try {
table.setWidths(columnWidths);
} catch (DocumentException e) {
throw new RuntimeException(e);
}
return table;
}
4.设置表格无边框
需要创建完所有行后,再设置为无边框
/**
* 设置表格为无边框
* @param table
*/
public static void setNoneBorderTable(PdfPTable table){
for (PdfPRow row : table.getRows()) {
for (PdfPCell cell : row.getCells()) {
if (cell != null) {
cell.setBorder(Rectangle.NO_BORDER);
}
}
5.安全性设置
/**
* 设置文档的安全性
* @param document
* @param pdfPath
* @return
*/
public static PdfWriter getSecurityWriter( Document document,String pdfPath,String ownerPass) {
PdfWriter instance = null;
try {
instance = PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
if(StringUtils.isEmpty(ownerPass)){
ownerPass="ssc-logistic";
}
instance.setEncryption(
null, // 用户密码(空表示无需密码)
ownerPass.getBytes(), // 所有者密码,修改时需要该密码
PdfWriter.ALLOW_PRINTING |//允许打印
PdfWriter.ALLOW_COPY |//允许复制
PdfWriter.ALLOW_SCREENREADERS,//允许屏幕阅读器访问
PdfWriter.ENCRYPTION_AES_256//AES 256加密
);
} catch (Exception e) {
throw new RuntimeException(e);
}
return instance;
}
6.设置表头
/**
* 设置表头
* @param table
* @param headerMap 按照put顺序
* @param fontPath 从配置文件帐获取
* @param language 语言
*/
public static void addTableHeader(PdfPTable table, LinkedHashMap<String,String> headerMap, String language,String fontPath){
Font chineseFont=getChineseFont(fontPath);
if(headerMap!=null){
for(String key:headerMap.keySet()){
PdfPCell headerCell = new PdfPCell(new Phrase(headerMap.get(key), chineseFont));
headerCell.setBackgroundColor(BaseColor.LIGHT_GRAY);//背景颜色
headerCell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平对齐方式
headerCell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直对齐方式
headerCell.setFixedHeight(40f);//行高
table.addCell(headerCell);
}
}
}
7.增加一行内容
/**
* 增加表格内容行
* @param table
* @param rowMap 格式为k-v如k:field1 v:test
* @param language
*/
public static void addTableRole(PdfPTable table,LinkedHashMap<String,String> rowMap,String fontPath){
Font chineseFont = getChineseFont(fontPath);
Font font = new Font(Font.FontFamily.COURIER, 10);
if(rowMap!=null){
for(String key:rowMap.keySet()){
String fieldValue=rowMap.get(key);
PdfPCell cell = new PdfPCell(new Phrase(fieldValue,chineseFont));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setFixedHeight(30f);//行高
table.addCell(cell);
}
}
}
8.增加多行内容
/**
* 增肌多列内容
* @param table
* @param rowsMapList 多行的list
* @param language 语言
* @param fontPath 字体路径
*/
public static void addTableRoles(PdfPTable table,List<LinkedHashMap<String,String>> rowsMapList,String language,String fontPath){
Font chineseFont = getChineseFont(fontPath);
Font font = new Font(Font.FontFamily.COURIER, 10);
if(!CollectionUtils.isEmpty(rowsMapList)){
for(LinkedHashMap<String,String> rowMap:rowsMapList){
for(String key:rowMap.keySet()){
String fieldValue=rowMap.get(key);
PdfPCell cell=null;
if("zh-CN".equals(language)){
cell = new PdfPCell(new Phrase(fieldValue,chineseFont));
}else{
cell = new PdfPCell(new Phrase(fieldValue,font));
}
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setFixedHeight(30f);//行高
table.addCell(cell);
}
}
}
}
9.合并列
/**
* 增加一个合并列
* @param table
* @param colsNum 合并几列
* @param startKey 从valueMap 那个key开始
* @param valueMap filed1:fieldValue1,field2:fieldValue2
*/
public static void addColSpanRow(PdfPTable table,int colsNum,String startKey,LinkedHashMap<String,String> valueMap){
if(!valueMap.isEmpty()){
for(String key:valueMap.keySet()){
String fieldValue = valueMap.get(key);
PdfPCell cell = new PdfPCell(new Phrase(fieldValue,chineseFont));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
if(startKey.equals(key)){
cell.setColspan(colsNum); // 设置跨列
}
cell.setFixedHeight(30f);//行高
table.addCell(cell);
}
}
}
10.增加超链接
/**
* 增加一个超链接的单元格
* @param table
* @param fieldFixedValue 固定单元格内容
* @param linkedList List<Map<String,String>> 格式,包含linkName、url,分别表示显示的名称和超链接地址
*/
public static void addLinkCell(PdfPTable table, String fieldFixedValue,int colspanNum,String fontPath, List<Map<String,String>> linkedList){
BaseFont baseFont = getBaseFont(fontPath);
Font chineseFont = getChineseFont(fontPath);
Font linkFont = new Font(baseFont, 10, Font.UNDERLINE, new BaseColor(0,0,255));
Paragraph mixPara = new Paragraph();
mixPara.add(new Chunk(fieldFixedValue, chineseFont)); // 普通中文
//设置超链接
int size=0;
if(!CollectionUtils.isEmpty(linkedList)){
for(Map<String,String> linkedMap:linkedList){
String linkName = linkedMap.get("linkName");
String url=linkedMap.get("url");
if(!StringUtils.isEmpty(linkName)&&!StringUtils.isEmpty(url)){
if(size!=0&&size!=linkedList.size()){//增加分割线
Chunk sep = new Chunk(" | ", new Font(Font.FontFamily.HELVETICA, 12));
mixPara.add(sep);
}
Chunk linkChunk = new Chunk(linkName, linkFont);
linkChunk.setAction(new PdfAction(url));
mixPara.add(linkChunk);
}
size++;
}
}
PdfPCell cell = new PdfPCell(mixPara);
cell.setBorder(Rectangle.NO_BORDER);//无边框
cell.setColspan(colspanNum);//合并单元格
cell.setPaddingTop(10f);//上间距
cell.setFixedHeight(30f);//行高
table.addCell(cell);
}
根据以上方法可以实现一个简单的form表单导出成pdf,并实现超链接可跳转或下载、文档密码设置、可编辑修改复制权限。具体代码以具体业务为主,仅供参考。