1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 绘制pdf表格 (二) 通过itext实现在pdf中绘制excel表格样式设置中文字体 水印 logo 页眉 页码

绘制pdf表格 (二) 通过itext实现在pdf中绘制excel表格样式设置中文字体 水印 logo 页眉 页码

时间:2022-05-22 14:06:07

相关推荐

绘制pdf表格 (二) 通过itext实现在pdf中绘制excel表格样式设置中文字体 水印 logo 页眉 页码

前言

在《通过itext实现在pdf中绘制excel表格样式并且实现下载》实现了表格的基本渲染,本文将继续进行水印、logo、页眉、页码的设置,本文的部分代码包含《通过itext实现在pdf中绘制excel表格样式并且实现下载》中的代码,为完整的可用实现代码。

1、引入POM

<dependencies><dependency><groupId>com.itextpdf</groupId><artifactId>font-asian</artifactId><version>7.2.1</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.13.3</version></dependency></dependencies>

2、查找字体

对于中文字体textpdf不支持直接写入字体名称,所以需要进行手动指定ttc或者ttf类型的字体,需要找到本机安装的字体位置,比如:C:\Windows\Fonts,正确查找字体的步骤如下:

第一步:进入C:\Windows\Fonts:

进入到字体的安装目录,Windows默认为C:\Windows\Fonts

第二步:查看字体信息

比如我们选择黑体,那么黑体的simsun.ttc

3、编写工具类

3.1 设置图片水印

public class PdfUtils {/*** 给pdf添加图片水印** @param waterMar* @param path图片路径* @throws Exception*/public static void addWater(PdfContentByte waterMar, String path) throws Exception {File file = new File(path);if (!file.exists()) {throw new RuntimeException("水印图片不存在!");}waterMar.beginText();PdfGState gs = new PdfGState();// 不透明度gs.setFillOpacity(0.2f);// 设置透明度waterMar.setGState(gs);// 设置对齐方式 内容 X坐标 Y坐标 旋转角度Image img = Image.getInstance(path);// 设置大小为200,并且居中float newWidth = 200f;float newHeight = 200f;img.scaleAbsolute(newWidth, newHeight);img.setAbsolutePosition((RECTANGLE.getWidth() - newWidth) / 2, (RECTANGLE.getHeight() - newHeight) / 2);waterMar.addImage(img);// 水印颜色waterMar.setColorFill(BaseColor.GRAY);// 关闭waterMar.endText();waterMar.stroke();}}

3.2 设置文字水印

public class PdfUtils {/*** 给pdf添加文字水印** @param waterMar* @param text水印文本* @param full是否平铺* @throws Exception*/public static void addWater(PdfContentByte waterMar, String text, boolean full) throws Exception {if (StringUtils.isEmpty(text)) {return;}waterMar.beginText();PdfGState gs = new PdfGState();// 不透明度gs.setFillOpacity(0.2f);int fontSize = 14;waterMar.setFontAndSize(createBaseFont(null), fontSize);// 设置透明度waterMar.setGState(gs);// 是否水印平铺if (full) {// 设置对齐方式 内容 X坐标 Y坐标 旋转角度 '/6'目的是为了让宽存在6个水印for (int x = 50; x <= RECTANGLE.getWidth(); x += RECTANGLE.getWidth() / 4) {for (int y = 50; y <= RECTANGLE.getHeight(); y += RECTANGLE.getHeight() / 4) {waterMar.showTextAligned(Element.ALIGN_RIGHT, text, x, y, 45);}}} else {waterMar.showTextAligned(Element.ALIGN_RIGHT, text, (RECTANGLE.getWidth()) / 2, (RECTANGLE.getHeight()) / 2, 45);}// 水印颜色waterMar.setColorFill(BaseColor.GRAY);// 关闭waterMar.endText();waterMar.stroke();}}

3.3 设置logo图片

public class PdfUtils {/*** 添加图片** @param document* @param imgPath* @param newWidth* @param newHeight* @throws IOException* @throws DocumentException*/public static void addImg(Document document, String imgPath, float newWidth, float newHeight) throws IOException, DocumentException {Image img1 = Image.getInstance(imgPath);img1.setAbsolutePosition(50, RECTANGLE.getHeight() - 60);img1.scaleAbsolute(newWidth, newHeight);document.add(img1);}}

3.4 设置页眉

public class PdfUtils {/*** 生成页眉** @param pdfWriter* @param text*/public static void addHeader(PdfWriter pdfWriter, String text) {ColumnText.showTextAligned(pdfWriter.getDirectContent(),Element.ALIGN_LEFT, new Paragraph(text, PdfUtils.setFont(10, BaseColor.GRAY)),50, RECTANGLE.getHeight() - 12, 0);}}

3.5 设置页码

public class PdfUtils {/*** 生成页码** @param pdfWriter* @param document*/public static void addPageNum(PdfWriter pdfWriter, Document document) {try {//创建一个两列的表格PdfPTable table = new PdfPTable(1);table.setTotalWidth(RECTANGLE.getWidth());//锁定列宽table.setLockedWidth(true);//设置每列宽度table.setWidths(new int[]{20});// 设置页码,字体大小为12号,灰色PdfPCell cell = new PdfPCell(new Phrase(document.getPageNumber() + "", PdfUtils.setFont(10, BaseColor.GRAY)));cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.disableBorderSide(-1);table.addCell(cell);// 将页码写到距离pdf底部30px的位置table.writeSelectedRows(0, -1, 0, 30, pdfWriter.getDirectContent());} catch (Exception e) {e.printStackTrace();throw new RuntimeException("设置页眉失败!");}}}

3.6 完整代码

public class PdfUtils {/*** 字体存放的跟路径,默认为'C:\Windows\Fonts\'*/private static final String FONT_PATH = "C:\\Windows\\Fonts\\";/*** 纸张大小*/private static Rectangle RECTANGLE = PageSize.A4;/*** 设置字体默认值** @return* @throws DocumentException* @throws IOException*/private static BaseFont createBaseFont(String fontName) throws DocumentException, IOException {// 默认为宋体if (fontName == null) {fontName = "simsun.ttc";}String fontPre = fontName.substring(fontName.lastIndexOf(".") + 1);if (fontPre.equals("ttc")) {// ttc格式的字体需要加上后缀fontName = fontName + ",0";}String font = FONT_PATH + fontName;return BaseFont.createFont(font, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);}/*** 设置字体** @return*/public static Font setFont() {return setFont(null, null, null, null);}public static Font setFont(Integer fontSize) {return setFont(null, fontSize, null, null);}public static Font setFont(Integer fontSize, BaseColor fontColor) {return setFont(null, fontSize, null, fontColor);}/*** @param fontName 字体名称 默认宋体* @param fontSize 字体大小 默认12号* @param fontStyle 字体样式* @param fontColor 字体颜色 默认黑色* @return*/public static Font setFont(String fontName, Integer fontSize, Integer fontStyle, BaseColor fontColor) {try {BaseFont baseFont = createBaseFont(fontName);Font font = new Font(baseFont);if (fontSize != null) {font.setSize(fontSize);}if (fontStyle != null) {font.setStyle(fontStyle);}if (fontColor != null) {font.setColor(fontColor);}return font;} catch (Exception e) {e.printStackTrace();throw new RuntimeException("设置字体失败!");}}/*** 创建pdf文档** @param response* @param fileName* @return*/public static Document createDocument(HttpServletResponse response, String fileName) {try {response.reset();response.setHeader("Content-Type", "application/pdf-stream");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));response.setHeader("Pragma", "no-cache");response.setHeader("Cache-Control", "no-cache");} catch (Exception e) {e.printStackTrace();}// 设置大小RECTANGLE = PageSize.A4;return new Document(RECTANGLE, 50, 50, 80, 50);}/*** 绘制标题** @param font* @param titleName* @return*/public static Paragraph setParagraph(Font font, String titleName) {Paragraph paragraph = new Paragraph(titleName, font);//设置文字居中paragraph.setAlignment(Element.ALIGN_CENTER);//行间距paragraph.setLeading(5f);//设置段落上空白paragraph.setSpacingBefore(-20f);//设置段落下空白paragraph.setSpacingAfter(15f);return paragraph;}/*** 设置表格内容** @param headFont* @param textFont* @param title* @param list* @return*/public static PdfPTable setTable(Font headFont, Font textFont, String[] title, List<User> list) {//四列PdfPTable table = createTable(new float[]{120, 120, 120, 120});for (String head : title) {table.addCell(createCell(head, headFont));}for (User user : list) {table.addCell(createCell(user.getName(), textFont));table.addCell(createCell(user.getGender(), textFont));table.addCell(createCell(Integer.toString(user.getAgx()), textFont));table.addCell(createCell(user.getAddress(), textFont));}return table;}private static PdfPTable createTable(float[] widths) {PdfPTable table = new PdfPTable(widths);try {// 设置表格大小table.setTotalWidth(RECTANGLE.getWidth() - 100);table.setLockedWidth(true);// 居中table.setHorizontalAlignment(Element.ALIGN_CENTER);// 边框table.getDefaultCell().setBorder(1);} catch (Exception e) {e.printStackTrace();}return table;}private static 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));return cell;}/*** 给pdf添加图片水印** @param waterMar* @param path图片路径* @throws Exception*/public static void addWater(PdfContentByte waterMar, String path) throws Exception {File file = new File(path);if (!file.exists()) {throw new RuntimeException("水印图片不存在!");}waterMar.beginText();PdfGState gs = new PdfGState();// 不透明度gs.setFillOpacity(0.2f);// 设置透明度waterMar.setGState(gs);// 设置对齐方式 内容 X坐标 Y坐标 旋转角度Image img = Image.getInstance(path);// 设置大小为200,并且居中float newWidth = 200f;float newHeight = 200f;img.scaleAbsolute(newWidth, newHeight);img.setAbsolutePosition((RECTANGLE.getWidth() - newWidth) / 2, (RECTANGLE.getHeight() - newHeight) / 2);waterMar.addImage(img);// 水印颜色waterMar.setColorFill(BaseColor.GRAY);// 关闭waterMar.endText();waterMar.stroke();}/*** 给pdf添加文字水印** @param waterMar* @param text水印文本* @param full是否平铺* @throws Exception*/public static void addWater(PdfContentByte waterMar, String text, boolean full) throws Exception {if (StringUtils.isEmpty(text)) {return;}waterMar.beginText();PdfGState gs = new PdfGState();// 不透明度gs.setFillOpacity(0.2f);int fontSize = 14;waterMar.setFontAndSize(createBaseFont(null), fontSize);// 设置透明度waterMar.setGState(gs);if (full) {// 设置对齐方式 内容 X坐标 Y坐标 旋转角度 '/6'目的是为了让宽存在6个水印for (int x = 50; x <= RECTANGLE.getWidth(); x += RECTANGLE.getWidth() / 4) {for (int y = 50; y <= RECTANGLE.getHeight(); y += RECTANGLE.getHeight() / 4) {waterMar.showTextAligned(Element.ALIGN_RIGHT, text, x, y, 45);}}} else {waterMar.showTextAligned(Element.ALIGN_RIGHT, text, (RECTANGLE.getWidth()) / 2, (RECTANGLE.getHeight()) / 2, 45);}// 水印颜色waterMar.setColorFill(BaseColor.GRAY);// 关闭waterMar.endText();waterMar.stroke();}/*** 添加图片** @param document* @param imgPath* @param newWidth* @param newHeight* @throws IOException* @throws DocumentException*/public static void addImg(Document document, String imgPath, float newWidth, float newHeight) throws IOException, DocumentException {Image img1 = Image.getInstance(imgPath);img1.setAbsolutePosition(50, RECTANGLE.getHeight() - 60);img1.scaleAbsolute(newWidth, newHeight);document.add(img1);}/*** 生成页眉** @param pdfWriter* @param text*/public static void addHeader(PdfWriter pdfWriter, String text) {ColumnText.showTextAligned(pdfWriter.getDirectContent(),Element.ALIGN_LEFT, new Paragraph(text, PdfUtils.setFont(10, BaseColor.GRAY)),50, RECTANGLE.getHeight() - 12, 0);}/*** 生成页码** @param pdfWriter* @param document*/public static void addPageNum(PdfWriter pdfWriter, Document document) {try {//创建一个两列的表格PdfPTable table = new PdfPTable(1);table.setTotalWidth(RECTANGLE.getWidth());//锁定列宽table.setLockedWidth(true);//设置每列宽度table.setWidths(new int[]{20});// 设置页码,字体大小为12号,灰色PdfPCell cell = new PdfPCell(new Phrase(document.getPageNumber() + "", PdfUtils.setFont(10, BaseColor.GRAY)));cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.disableBorderSide(-1);table.addCell(cell);// 将页码写到距离pdf底部30px的位置table.writeSelectedRows(0, -1, 0, 30, pdfWriter.getDirectContent());} catch (Exception e) {e.printStackTrace();throw new RuntimeException("设置页眉失败!");}}}

4、创建事件处理器

通过自定义事件处理器对PDF文档进行水印、logo、页眉、页码的设置,具体代码如下:

public class NewPdfPageEventHelper extends PdfPageEventHelper {private boolean water = false;private String textWater = null;private boolean textWaterFull = true;private String imageWaterPath = null;private boolean logo = false;private String logoImagePath = null;private float logoWidth = 0f;private float logoHeight = 0f;private boolean header = false;private String headerText = null;private boolean pageNum = false;public void setTextWaterWater(String textWater, boolean textWaterFull) {this.water = true;this.textWaterFull = textWaterFull;this.textWater = textWater;}public void setImageWaterWater(String imageWaterPath) {this.water = true;this.imageWaterPath = imageWaterPath;}public void setLogo(String logoImagePath, float logoWidth, float logoHeight) {this.logo = true;this.logoImagePath = logoImagePath;this.logoWidth = logoWidth;this.logoHeight = logoHeight;}public void setHeader(String headerText) {this.header = true;this.headerText = headerText;}public void setPageNum() {this.pageNum = true;}/*** 每开始一页pdf时回调** @param pdfWriter* @param document*/@Overridepublic void onStartPage(PdfWriter pdfWriter, Document document) {try {if (water) {// 设置水印(图片、文字水印)PdfContentByte waterMar = pdfWriter.getDirectContentUnder();// 水印if (textWater != null) {PdfUtils.addWater(waterMar, textWater, textWaterFull);}if (imageWaterPath != null) {PdfUtils.addWater(waterMar, imageWaterPath);}}if (header) {// 生成页眉PdfUtils.addHeader(pdfWriter, headerText);}if (logo) {// 设置logoPdfUtils.addImg(document, logoImagePath, logoWidth, logoHeight);}if (pageNum) {// 生成页码PdfUtils.addPageNum(pdfWriter, document);}} catch (Exception e) {e.printStackTrace();}}}

5、导出代码实现

代码:

@RestController@RequestMapping("/test")public class ExcelController {@GetMapping("/pdf")@ResponseBodypublic void downloadPDF(HttpServletResponse response) {try (BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream())) {// 1.设置输出的文件名称String fileName = "考勤报表.pdf";// 2.创建pdf文档,并且设置纸张大小为A4Document document = PdfUtils.createDocument(response, fileName);PdfWriter writer = PdfWriter.getInstance(document, os);// 3.设置事件(水印、页眉、logo)等NewPdfPageEventHelper helper = new NewPdfPageEventHelper();// 水印helper.setImageWaterWater("C:\\Users\\LiGezZ\\Desktop\\java.png");helper.setTextWaterWater("这 是 文 字 水 印", true);// logohelper.setLogo("C:\\Users\\LiGezZ\\Desktop\\logo.png", 80, 40);// 页眉helper.setHeader("xxxxx科技股份有限公司");// 页码helper.setPageNum();// 开启回调事件writer.setPageEvent(helper);// 4.打开文档document.open();// 5.设置标题String titleName = "这 个 是 标 题";// 设置字体样式:黑体 20号 加粗 红色Font titleFont = PdfUtils.setFont("simhei.ttf", 20, Font.BOLD, BaseColor.RED);Paragraph paragraph = PdfUtils.setParagraph(titleFont, titleName);// 6.设置表格// 定义列名String[] title = {"姓名", "性别", "年龄", "地址"};// 获取列表数据// 设置表头字体样式:黑体 14号 加粗 黑色// 设置正文字体样式:12号Font headFont = PdfUtils.setFont("simhei.ttf", 12, Font.BOLD, BaseColor.BLACK);Font textFont = PdfUtils.setFont(12);List<User> dataList = getData();PdfPTable table = PdfUtils.setTable(headFont, textFont, title, dataList);// 7.填充内容document.add(paragraph);document.add(table);// 关闭资源document.close();} catch (Exception e) {e.printStackTrace();}}/*** 模拟从数据库获取数据** @return*/private List<User> getData() {List<User> list = new ArrayList<>();for (int i = 0; i < 100; i++) {User user = new User();user.setName("名称-" + i);user.setAddress("地址-" + i);user.setAgx(20);user.setGender("男");list.add(user);}return list;}}

效果:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。