公司最近新需求要针对已经学完课程的同学提供下载结业证书,我们开发小组通过内部协商最终采用pdf方式让用户进行下载。操作pdf java 一般都是通过itext来实现,由于之前没有使用itext生成pdf,就去百度搜索先关信息。大部分都是通过pdf模板进行生成证书相关信息。找到一篇写的还不错的技术博客Java根据pdf模板生成荣誉证书PDF文件。先是通过word编辑好模板 然后再通过Acrobat Reader DC 来设置动态表单,之后的操作作者也提供了源码。本来想在本地跑一下看看效果如何,无奈我本地Acrobat Reader DC软件点击准备表单是如下图所示。

看到上图的信息我心中各种MMP, 但是这个并没有阻止我继续研究的决心!于是决定换种思路,既然模板不行那就将证书的图片当成pdf的背景图 然后再根据坐标点在背景图上添加内容。功夫不负有心人最终被我搞定特此分享一下。

同时我这里借用Java根据pdf模板生成荣誉证书PDF文件 作者zout邹涛的源码中的图片进行操作还望作者尽情谅解。最终效果图如下:

模板图片:

通过代码生成pdf效果:

实现代码:

这个是生成中文内容中字体的样式封装类

package cn.zhuoqianmingyue;import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;public class ContentStyle {private String TTFPath = "C:/WINDOWS/Fonts/SIMYOU.TTF";// 字体类型private float  fontSize = 12;//字体大小private BaseColor baseColor = new BaseColor(0, 0, 0);//默认是黑色private int style = Font.NORMAL;//字体样式private int alignment = Element.ALIGN_LEFT;public String getTTFPath() {return TTFPath;}public void setTTFPath(String tTFPath) {TTFPath = tTFPath;}public float getFontSize() {return fontSize;}public void setFontSize(float fontSize) {this.fontSize = fontSize;}public BaseColor getBaseColor() {return baseColor;}public void setBaseColor(BaseColor baseColor) {this.baseColor = baseColor;}public int getStyle() {return style;}public void setStyle(int style) {this.style = style;}public int getAlignment() {return alignment;}public void setAlignment(int alignment) {this.alignment = alignment;}
}

生产证书pdf 文件工具类

package cn.zhuoqianmingyue;import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Date;import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;public class PDFUtil {private Document document;private PdfWriter writer;public void setDocument(Document document) {this.document = document;}public void setWriter(PdfWriter writer) {this.writer = writer;}/*** 开启创建PDF对象* @param pafPath : 生成pdf的磁盘路径* @return* @throws FileNotFoundException* @throws DocumentException*/public PDFUtil openDocumnet(String pafPath) throws FileNotFoundException, DocumentException{Document document = new Document(PageSize.A4);writer = PdfWriter.getInstance(document,new FileOutputStream(pafPath));document.open();this.document = document;return this;}/*** 添加图片背景* @param imageUrl :证书图片的磁盘路径* @param absoluteX :左边距* @param absoluteY :底边距* @return* @throws MalformedURLException* @throws IOException* @throws DocumentException*/public PDFUtil addImage(String imagePath,float absoluteX, float absoluteY) throws MalformedURLException, IOException, DocumentException{Image tImgCover = Image.getInstance(imagePath);tImgCover.setAbsolutePosition(absoluteX, absoluteY);float heigth = tImgCover.getHeight();float width = tImgCover.getWidth();// int percent=getPercent(heigth, width);int percent = getPercent2(heigth, width);// 设置图片居中显示// tImgCover.setAlignment(Image.MIDDLE);tImgCover.scalePercent(percent);// 表示是原来图像的比例;document.add(tImgCover);return this;}/*** * @param certificateContent :pdf证书的中文内容* @param x :左边距* @param y :底边距* @param contentStyle :中文内容的样式* @return* @throws DocumentException* @throws IOException*/public PDFUtil addContent(String certificateContent,float x, float y,ContentStyle contentStyle) throws DocumentException, IOException{if(contentStyle == null){contentStyle = new ContentStyle();}PdfContentByte canvas = writer.getDirectContent();BaseFont bf = BaseFont.createFont(contentStyle.getTTFPath(),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);Font secFont = new Font(bf, contentStyle.getFontSize(), contentStyle.getStyle(), contentStyle.getBaseColor());Phrase certificateContentPhrase = new Phrase(certificateContent, secFont);ColumnText.showTextAligned(canvas, contentStyle.getAlignment(), certificateContentPhrase, x,y, 0);return this;}/*** 添加日期内容* @param x 插入pdf左边距* @param y 插入pdf底边距* @param contentStyle* @return* @throws DocumentException* @throws IOException*/public PDFUtil addDateContent(float x, float y,ContentStyle contentStyle) throws DocumentException, IOException{if(contentStyle == null){contentStyle = new ContentStyle();}Date currentDate = DateTimeUtil.getCurrentDate();String currentDateString = DateTimeUtil.DateToString(currentDate);PdfContentByte canvas = writer.getDirectContent();BaseFont bf = BaseFont.createFont(contentStyle.getTTFPath(),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);Font secFont = new Font(bf, contentStyle.getFontSize(), contentStyle.getStyle(), contentStyle.getBaseColor());Phrase certificateDatephrase = new Phrase(currentDateString, secFont);ColumnText.showTextAligned(canvas,contentStyle.getAlignment(), certificateDatephrase, x,y, 0);return this;}/*** 释放资源*/public void close(){document.close();}/*** 第二种解决方案,统一按照宽度压缩* 这样来的效果是,所有图片的宽度是相等的,自我认为给客户的效果是最好的* @param args*/public int getPercent2(float h,float w){int p=0;float p2=0.0f;p2=595/w*100;System.out.println("--"+p2);p=Math.round(p2);return p;}/*** 第一种解决方案* 在不改变图片形状的同时,判断,如果h>w,则按h压缩,否则在w>h或w=h的情况下,按宽度压缩* @param h* @param w* @return*/public int getPercent(float h,float w){int p=0;float p2=0.0f;if(h>w){p2=297/h*100;}else{p2=210/w*100;}p=Math.round(p2);return p;}public static void main(String[] args) throws MalformedURLException, FileNotFoundException, DocumentException, IOException {long currentDateTime = new Date().getTime();String imagePath = PDFUtil.class.getClassLoader().getResource("certificate.png").getPath();String pdfFilePath = "d:/pdf/" +7+ ".pdf";PDFUtil pdfUtil = new PDFUtil();pdfUtil.openDocumnet(pdfFilePath).addImage(imagePath, 0, 400).addDateContent(330,462,null).addContent("张三",85,655,null).close();}
}

日期的工具类

package cn.zhuoqianmingyue;import java.text.SimpleDateFormat;
import java.util.Date;public class DateTimeUtil {public static java.util.Date getCurrentDate(){return new java.util.Date(System.currentTimeMillis());}public static String DateToString(Date date) {if(date == null){return "";}SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");return sdf.format(date);}
}

PDFUtil测试类:

package cn.zhuoqianmingyue;import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Date;import org.junit.Test;import com.itextpdf.text.DocumentException;public class PDFUtilTest {@Testpublic void generatingPdfCertificate () throws MalformedURLException, FileNotFoundException, DocumentException, IOException {long currentDateTime = new Date().getTime();String imagePath = PDFUtil.class.getClassLoader().getResource("certificate.png").getPath();String pdfFilePath = "d:/pdf/" +currentDateTime+ ".pdf";PDFUtil pdfUtil = new PDFUtil();pdfUtil.openDocumnet(pdfFilePath).addImage(imagePath, 0, 400).addDateContent(330,462,null).addContent("张三",85,655,null).close();}
}

pom.xml内容:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>cn.zhuoqianmingyue</groupId><artifactId>certificate</artifactId><version>0.0.1-SNAPSHOT</version><dependencies><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.11</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies><build>  <plugins>  <plugin>  <groupId>org.apache.maven.plugins</groupId>  <artifactId>maven-compiler-plugin</artifactId>  <version>3.1</version>  <configuration>  <source>1.8</source>  <target>1.8</target>  </configuration>  </plugin>  </plugins></build>
</project>

源码地址:https://github.com/zhuoqianmingyue/certificate

参考文献:https://blog.csdn.net/ITBigGod/article/details/81155483

https://blog.csdn.net/mr_li13/article/details/78292277

Java生成荣誉证书PDF文件相关推荐

  1. Java/web/jsp根据pdf模板生成荣誉证书PDF文件

    Java/web/jsp根据pdf模板生成荣誉证书PDF文件 1.前言 最近博主在开发一个大学生学分管理系统,按照对方用户的要求,他们需要一个生成PDF荣誉证书的功能. 于是Java根据pdf模板生成 ...

  2. java生成pdf_Java实现PDF文件生成并且打印pdf文件 demo

    ## Java实现PDF生成并且打印pdf文件(附demo) #### 目录: 0. 效果预览 1. 准备环境 2. Java如何调用打印机进行打印 3. Java如何生成pdf打印文件 4. 实现p ...

  3. java 生成的临时pdf文件无法删除

    多个pdf文件从附件系统下载下来之后,合并成一个pdf文件.过程中需要把每个文件生成到本地临时文件,但是生成过后怎么也删除不了,估计有使用到的流没关闭,手动在文件夹中也无法删除,提示文件正在被占用,但 ...

  4. 根据pdf模板生成新的pdf文件(Java)

    根据pdf模板生成新的pdf文件 一.项目依赖 二.所用工具类 三.其他资料 一.项目依赖 1.maven版本:3.5.x 2.pom文件依赖 <!--itext的依赖jar--> < ...

  5. Java 读取 Excel 文件内容, 根据 pdf 模板动态生成对应的 pdf 文件

    1. 下载 adobe acrobat https://www.cr173.com/soft/11135.html 2. 编辑 pdf 模板 1用 acrobat 打开 pdf 编辑模板 添加表单元素 ...

  6. 如何使用图片生成荣誉证书

    公司项目有一个根据图片模板生成荣誉证书的需求,不废话,这里直接上代码 package com.example.demo.honorcert;import com.example.demo.util.F ...

  7. java操作Excel、PDF文件

    java操作Excel.PDF文件 下面这些是在开发中用到的一些东西,有的代码贴的不是完整的,只是贴出了关于操作EXCEL的代码: jxl是一个*国人写的java操作excel的工具, 在开源世界中, ...

  8. PDF技术(四)-Java实现Html转PDF文件

    html转换为pdf的关键技术是如何处理网页中复杂的css样式.以及中文乱码处理. 各实现对比表 于Windows平台进行测试: 基于IText 基于FlyingSaucer 基于WKHtmlToPd ...

  9. java实现写字板对pdf文件签名

    java实现写字板对pdf文件签名 思路 首先明白写字板签名完输出的是base64的图片,剩下的就是将此图片插入到pdf文件中,实现此步骤的技术很多,可以用itex5但是为了实现与其他数据一起动态插入 ...

最新文章

  1. android相对布局底部对齐,Android,在edittext中输入时防止相对布局底部对齐的按钮向上移动...
  2. 明星不是梦#利用Python进行网站日志分析
  3. Hadoop 面试题之Hbase
  4. 高性能mysql_「高性能MySQL」十年阿里架构师推荐,这份高性能MySQL文档送给你
  5. 数据结构之链表及其Java实现_数据结构之链表及其Java实现
  6. SEAndroid语法介绍
  7. 2017年国家二级c语言题库,2017年计算机二级c语言题库及答案
  8. linux 交叉编译ffplay,交叉编译ffmpeg生成ffplay
  9. python与plc进行串口通信,寄存器写数据 欧姆龙plc
  10. 冰冻三尺非一日之寒-自学篇 浅谈个人学习方法(转载)
  11. 计算日期间隔,以XX年XX月XX日格式显示
  12. Mounty for Mac(NTFS格式读写工具)
  13. 天龙八部 - 其它 - 手工选择
  14. JSD-2204-MVC-微博项目-Day15
  15. Timingdesigner timing designer 入门 基础 教程
  16. MATLAB/Simulink封装子模块图片显示和参数输出设置问题
  17. 移动互联网如何改变了外卖行业
  18. 获取最新的中国IP的脚本,给ROS可以使用的脚本
  19. 8月,Github 最热开源项目排行榜来啦
  20. 优秀程序猿因何而优秀?

热门文章

  1. go regexp匹配字符串_多模式字符串匹配算法ac自动机(用go语言实现)
  2. asp php 对照表,asp 与php中常用函数对比
  3. 免堆期由谁申请_谈谈离婚冷静期
  4. ECS之System系统
  5. Ansible Tower - 使用入门 3 - 通过模板运行 Git 上的 Playbook 和 Role
  6. Windows Terminal Preview 1.3 发布
  7. Asp.net Boilerplate 源码无法打开——找不到.net core sdk
  8. 无法打开数据库‘mysql_MySQL数据库之MYSQL无法启动解决方法
  9. mr图像翻转的原因_MR成像技术讲解
  10. linux下oracle10g安装配置说明,Linux下oracle10g安装配置说明(ZT)