公司最近新需求要针对已经学完课程的同学提供下载结业证书,我们开发小组通过内部协商最终采用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 {
@Test
public 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内容:
4.0.0
cn.zhuoqianmingyue
certificate
0.0.1-SNAPSHOT
com.itextpdf
itextpdf
5.5.11
com.itextpdf
itext-asian
5.2.0
junit
junit
4.12
test
org.apache.maven.plugins
maven-compiler-plugin
3.1
1.8
源码地址:https://github.com/zhuoqianmingyue/certificate
参考文献:https://blog.csdn.net/ITBigGod/article/details/81155483
https://blog.csdn.net/mr_li13/article/details/78292277