Java生成荣誉证书PDF文件

公司最近新需求要针对已经学完课程的同学提供下载结业证书,我们开发小组通过内部协商最终采用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内容:

<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

  • 7
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值