2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > itextpdf导出pdf流 写入表格 以及生成水印

itextpdf导出pdf流 写入表格 以及生成水印

时间:2020-12-10 19:37:29

相关推荐

itextpdf导出pdf流 写入表格  以及生成水印

导出PDF流

设置响应参数HttpServletResponse

response.setCharacterEncoding("utf-8");response.setContentType("application/pdf");response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(tempName + ".pdf", "UTF-8"));

将数据写入到response.getOutputStream()输出流,以流的形式返回给前端

Document document = new Document();PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());document.open();//设置字体 中文需要导入itext-asian包 否则中文将中不到对应的字体不显示BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);Font f1 = new Font(bfChinese);//通过反射去获取字段Field[] declaredFields = tempClass.getDeclaredFields();PdfPTable leftTable = new PdfPTable(declaredFields.length);//表头for (Field declaredField : declaredFields) {//获取ExcelProperty注解中value值String name=declaredField.getAnnotation(ExcelProperty.class).value()[0];PdfPCell topCell = new PdfPCell(new Paragraph(name,f1));//设置水平垂直居中topCell.setHorizontalAlignment(Element.ALIGN_CENTER);topCell.setVerticalAlignment(Element.ALIGN_MIDDLE);leftTable.addCell(topCell);}//表格内容for (Object datum : data) {for (Field declaredField : declaredFields) {declaredField.setAccessible(true);Object o = declaredField.get(datum);String text = Objects.isNull(o)?"":o.toString();//特殊字段需要处理 可以去掉if(StringUtil.equals("isCancel",declaredField.getName())){text = Objects.equals(o, YesOrNoEnum.NO.getCode())?"有效":"已失效";}PdfPCell cell = new PdfPCell(new Paragraph(text,f1));cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setVerticalAlignment(Element.ALIGN_MIDDLE);leftTable.addCell(cell);}}document.add(leftTable);//水印文字 实现换行List<String> watermarks= new ArrayList<>();watermarks.add(LocalDate.now().format(DatePattern.NORM_DATE_FORMATTER));watermarks.add(LocalDate.now().format(DatePattern.NORM_DATETIME_MINUTE_FORMATTER));watermarks.add(LocalDate.now().format(DatePattern.CHINESE_DATE_TIME_FORMATTER));Font watermarkFont = new Font(f1.getBaseFont(),100, Font.NORMAL,new BaseColor(223,223,223,120));Rectangle rectangle =writer.getPageSize();for (int i = 0; i < watermarks.size(); i++) {ColumnText.showTextAligned(writer.getDirectContentUnder(), Element.ALIGN_CENTER, new Phrase(watermarks.get(i), watermarkFont), rectangle.getRight()/2, rectangle.getTop()/2-(150*i)+200, 30);}//关闭流document.close();writer.close();

pom文件

注:itextpdf 和 asian的版本需对应,否则将会出现一系列报错 asian版本过低 将提示找不到cjk_registry.properties文件

<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.9</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>

UniGB-UCS2-H :为cjk_registry.properties 的Adobe_GB1中的一个值 可替换为其他值

STSong-Light :为cjk_registry.properties 的fonts中的一个值 可替换为其他值

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