itextpdf生成表格pdf+背景图片(可转图片)
- 导入jar,manven引用
<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>
<!-- pdf转图片 -->
<dependency>
<groupId>org.icepdf.os</groupId>
<artifactId>icepdf-core</artifactId>
<version>6.1.2</version>
</dependency>
- 定义全局变量和创建表格方法
// 定义全局的字体静态变量
private static Font keyfont;
private static Font textfont;
// 最大宽度
private static int maxWidth = 580;
// 静态代码块
static {
try {
// 不同字体(这里定义为同一种字体:包含不同字号、不同style)
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// 15为字体,可根据实际情况调整
keyfont = new Font(bfChinese, 15, Font.BOLD, BaseColor.YELLOW);
textfont = new Font(bfChinese, 15, Font.NORMAL, BaseColor.YELLOW);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 创建指定列宽、列数的表格
*
* @param widths
* @return
*/
public 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;
}
/**
* 创建单元格(指定字体)
*
* @param value
* @param font
* @return
*/
public 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));
cell.setBorderWidthTop(1f);
// 设置列表线颜色
cell.setBorderColorTop(BaseColor.YELLOW);
cell.setBorderColorRight(BaseColor.YELLOW);
cell.setBorderColorBottom(BaseColor.YELLOW);
cell.setBorderColorLeft(BaseColor.YELLOW);
return cell;
}
/**
* 创建单元格(指定字体、水平..)
*
* @param value
* @param font
* @param align
* @return
*/
public 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.setBorderWidthTop(1f);
// 设置列表线颜色
cell.setBorderColorTop(BaseColor.YELLOW);
cell.setBorderColorRight(BaseColor.YELLOW);
cell.setBorderColorBottom(BaseColor.YELLOW);
cell.setBorderColorLeft(BaseColor.YELLOW);
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));
cell.setBorderWidthTop(1f);
// 设置列表线颜色
cell.setBorderColorTop(BaseColor.YELLOW);
cell.setBorderColorRight(BaseColor.YELLOW);
cell.setBorderColorBottom(BaseColor.YELLOW);
cell.setBorderColorLeft(BaseColor.YELLOW);
return cell;
}
- 生成图片方法
public String pdf2Pic(String pdfPath, String path, String fileName) throws Exception {
// pdfPath:pdf路径 path:保存图片路径
org.icepdf.core.pobjects.Document document = new org.icepdf.core.pobjects.Document();
document.setFile(pdfPath);
//缩放比例
float scale = 2.5f;
String imgName = null;
//旋转角度
float rotation = 0f;
// for循环为pdf多页情况时使用
// for (int i = 0; i < document.getNumberOfPages(); i++) {
// 0为i,多页使用,注意
BufferedImage image = (BufferedImage)
document.getPageImage(0, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
RenderedImage rendImage = image;
try {
File fileDir = new File(path);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
imgName = fileName + 0 + ".jpg";
File file = new File(path + imgName);
ImageIO.write(rendImage, "jpg", file);
} catch (IOException e) {
e.printStackTrace();
}
image.flush();
// }
document.dispose();
// 此为返回的保存图片路径
~~return path + imgName;~~
}
- 生成带表格的pdf
try {
// 1.新建document对象
Document document = new Document(PageSize.A4);// 建立一个Document对象
// 2.建立一个书写器(Writer)与document对象关联
Long longTime = System.currentTimeMillis();
String url = "路径";
// 保存的pdf名称
String name = longTime + ".pdf";
File file = new File(url + name);
file.createNewFile();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// // 设置页面布局
writer.setViewerPreferences(PdfWriter.PageLayoutOneColumn);
// 3.打开文档
document.open();
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int weekYear = calendar.getWeekYear();
int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);
calendar.add(Calendar.DAY_OF_MONTH, +4);
// 表格,150, 120, 120表格列比例
PdfPTable table = createTable(new float[]{150, 120, 120});
// 表格列名以及表头
// pdfPCell 为三列合并
PdfPCell pdfPCell = createCell(weekYear+"年"+(date.getMonth() + 1) + "月第" + weekOfMonth + "周签约奖"
, keyfont, Element.ALIGN_CENTER, 3);
pdfPCell.setFixedHeight(40);
PdfPCell pdfPCell1 = createCell("xxx", keyfont, Element.ALIGN_CENTER);
pdfPCell1.setFixedHeight(40);
PdfPCell pdfPCell2 = createCell("xxxx", keyfont, Element.ALIGN_CENTER);
pdfPCell2.setFixedHeight(40);
PdfPCell pdfPCell3 = createCell("奖金/元", keyfont, Element.ALIGN_CENTER);
pdfPCell3.setFixedHeight(40);
table.addCell(pdfPCell);
table.addCell(pdfPCell1);
table.addCell(pdfPCell2);
table.addCell(pdfPCell3);
// list为数据源
for (int i = 0; i < list.size(); i++) {
PdfPCell pdfPCell4 = createCell(list.get(i).get("deptName").toString(), textfont);
// FixedHeight列高
pdfPCell4.setFixedHeight(40);
table.addCell(pdfPCell4);
PdfPCell pdfPCell5 = createCell(list.get(i).get("userName").toString(), textfont);
// FixedHeight列高
pdfPCell5.setFixedHeight(40);
table.addCell(pdfPCell5);
PdfPCell pdfPCell6 = createCell(list.get(i).get("jj").toString(), textfont);
// FixedHeight列高
pdfPCell6.setFixedHeight(40);
table.addCell(pdfPCell6);
}
PdfPCell pdfPCell7 = createCell("祝贺以上同事荣登英雄榜,奖金于" + (calendar.get(Calendar.MONTH) + 1) + "月"
+ calendar.get(Calendar.DAY_OF_MONTH) + "日发放,请注意查收!"
, keyfont, Element.ALIGN_CENTER, 3);
pdfPCell7.setFixedHeight(20);
table.addCell(pdfPCell7);
// 查找图片并插入
Image tImgCover = Image.getInstance(url+"图片名称");
/* 设置图片的位置 */
tImgCover.setAbsolutePosition(0, 0);
/* 设置图片的大小,A4不需要改动 */
tImgCover.scaleAbsolute(595, 842);
// 插入图片
document.add(tImgCover);
PdfContentByte canvas = writer.getDirectContent();
// 设置表格宽度
table.setTotalWidth(500f);
/**
* rowStart 0 起始行
* rowEnd -1 表示全部行
* xPos 表格横坐标- 从左向右开始计算
* yPos 表格纵坐标- 从下向上开始计算
* canvas 画布
*/
table.writeSelectedRows(0, -1, 50, 500, canvas);
// 关闭document对象
document.close();
String pngNmae = longTime + "_";
// 调用生成图片方法imgName =图片路径
String imgName = pdf2Pic(url + name, url, pngNmae);
} catch (Exception e) {
e.printStackTrace();
}
- 此代码可直接使用,亲测无问题