`
shuai1234
  • 浏览: 995177 次
  • 性别: Icon_minigender_1
  • 来自: 山西
社区版块
存档分类
最新评论

Java生成荣誉证书PDF文件

    博客分类:
  • java
 
阅读更多

Java生成荣誉证书PDF文件

 版权声明:本文为博主原创文章,转载请表明出处。如果您觉得文章还行就点个赞,同时也可以关注一下我哈。 https://blog.csdn.net/ljk126wy/article/details/84299373

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

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

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

模板图片:

通过代码生成pdf效果:

实现代码:

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

  1.  
    package cn.zhuoqianmingyue;
  2.  
     
  3.  
    import com.itextpdf.text.BaseColor;
  4.  
    import com.itextpdf.text.Element;
  5.  
    import com.itextpdf.text.Font;
  6.  
     
  7.  
    public class ContentStyle {
  8.  
     
  9.  
    private String TTFPath = "C:/WINDOWS/Fonts/SIMYOU.TTF";// 字体类型
  10.  
    private float fontSize = 12;//字体大小
  11.  
    private BaseColor baseColor = new BaseColor(0, 0, 0);//默认是黑色
  12.  
    private int style = Font.NORMAL;//字体样式
  13.  
    private int alignment = Element.ALIGN_LEFT;
  14.  
     
  15.  
    public String getTTFPath() {
  16.  
    return TTFPath;
  17.  
    }
  18.  
    public void setTTFPath(String tTFPath) {
  19.  
    TTFPath = tTFPath;
  20.  
    }
  21.  
    public float getFontSize() {
  22.  
    return fontSize;
  23.  
    }
  24.  
    public void setFontSize(float fontSize) {
  25.  
    this.fontSize = fontSize;
  26.  
    }
  27.  
    public BaseColor getBaseColor() {
  28.  
    return baseColor;
  29.  
    }
  30.  
    public void setBaseColor(BaseColor baseColor) {
  31.  
    this.baseColor = baseColor;
  32.  
    }
  33.  
    public int getStyle() {
  34.  
    return style;
  35.  
    }
  36.  
    public void setStyle(int style) {
  37.  
    this.style = style;
  38.  
    }
  39.  
    public int getAlignment() {
  40.  
    return alignment;
  41.  
    }
  42.  
    public void setAlignment(int alignment) {
  43.  
    this.alignment = alignment;
  44.  
    }
  45.  
    }

 生产证书pdf 文件工具类

  1.  
    package cn.zhuoqianmingyue;
  2.  
     
  3.  
    import java.io.FileNotFoundException;
  4.  
    import java.io.FileOutputStream;
  5.  
    import java.io.IOException;
  6.  
    import java.net.MalformedURLException;
  7.  
    import java.util.Date;
  8.  
     
  9.  
    import com.itextpdf.text.Document;
  10.  
    import com.itextpdf.text.DocumentException;
  11.  
    import com.itextpdf.text.Font;
  12.  
    import com.itextpdf.text.Image;
  13.  
    import com.itextpdf.text.PageSize;
  14.  
    import com.itextpdf.text.Phrase;
  15.  
    import com.itextpdf.text.pdf.BaseFont;
  16.  
    import com.itextpdf.text.pdf.ColumnText;
  17.  
    import com.itextpdf.text.pdf.PdfContentByte;
  18.  
    import com.itextpdf.text.pdf.PdfWriter;
  19.  
     
  20.  
    public class PDFUtil {
  21.  
     
  22.  
    private Document document;
  23.  
    private PdfWriter writer;
  24.  
     
  25.  
    public void setDocument(Document document) {
  26.  
    this.document = document;
  27.  
    }
  28.  
     
  29.  
    public void setWriter(PdfWriter writer) {
  30.  
    this.writer = writer;
  31.  
    }
  32.  
    /**
  33.  
    * 开启创建PDF对象
  34.  
    * @param pafPath : 生成pdf的磁盘路径
  35.  
    * @return
  36.  
    * @throws FileNotFoundException
  37.  
    * @throws DocumentException
  38.  
    */
  39.  
    public PDFUtil openDocumnet(String pafPath) throws FileNotFoundException, DocumentException{
  40.  
    Document document = new Document(PageSize.A4);
  41.  
    writer = PdfWriter.getInstance(document,new FileOutputStream(pafPath));
  42.  
    document.open();
  43.  
    this.document = document;
  44.  
    return this;
  45.  
    }
  46.  
    /**
  47.  
    * 添加图片背景
  48.  
    * @param imageUrl :证书图片的磁盘路径
  49.  
    * @param absoluteX :左边距
  50.  
    * @param absoluteY :底边距
  51.  
    * @return
  52.  
    * @throws MalformedURLException
  53.  
    * @throws IOException
  54.  
    * @throws DocumentException
  55.  
    */
  56.  
    public PDFUtil addImage(String imagePath,float absoluteX, float absoluteY) throws MalformedURLException, IOException, DocumentException{
  57.  
    Image tImgCover = Image.getInstance(imagePath);
  58.  
    tImgCover.setAbsolutePosition(absoluteX, absoluteY);
  59.  
    float heigth = tImgCover.getHeight();
  60.  
    float width = tImgCover.getWidth();
  61.  
    // int percent=getPercent(heigth, width);
  62.  
    int percent = getPercent2(heigth, width);
  63.  
    // 设置图片居中显示
  64.  
    // tImgCover.setAlignment(Image.MIDDLE);
  65.  
    tImgCover.scalePercent(percent);// 表示是原来图像的比例;
  66.  
    document.add(tImgCover);
  67.  
    return this;
  68.  
    }
  69.  
    /**
  70.  
    *
  71.  
    * @param certificateContent :pdf证书的中文内容
  72.  
    * @param x :左边距
  73.  
    * @param y :底边距
  74.  
    * @param contentStyle :中文内容的样式
  75.  
    * @return
  76.  
    * @throws DocumentException
  77.  
    * @throws IOException
  78.  
    */
  79.  
    public PDFUtil addContent(String certificateContent,float x, float y,ContentStyle contentStyle) throws DocumentException, IOException{
  80.  
     
  81.  
    if(contentStyle == null){
  82.  
    contentStyle = new ContentStyle();
  83.  
    }
  84.  
     
  85.  
    PdfContentByte canvas = writer.getDirectContent();
  86.  
    BaseFont bf = BaseFont.createFont(contentStyle.getTTFPath(),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  87.  
    Font secFont = new Font(bf, contentStyle.getFontSize(), contentStyle.getStyle(), contentStyle.getBaseColor());
  88.  
    Phrase certificateContentPhrase = new Phrase(certificateContent, secFont);
  89.  
    ColumnText.showTextAligned(canvas, contentStyle.getAlignment(), certificateContentPhrase, x,y, 0);
  90.  
    return this;
  91.  
    }
  92.  
    /**
  93.  
    * 添加日期内容
  94.  
    * @param x 插入pdf左边距
  95.  
    * @param y 插入pdf底边距
  96.  
    * @param contentStyle
  97.  
    * @return
  98.  
    * @throws DocumentException
  99.  
    * @throws IOException
  100.  
    */
  101.  
    public PDFUtil addDateContent(float x, float y,ContentStyle contentStyle) throws DocumentException, IOException{
  102.  
     
  103.  
    if(contentStyle == null){
  104.  
    contentStyle = new ContentStyle();
  105.  
    }
  106.  
     
  107.  
    Date currentDate = DateTimeUtil.getCurrentDate();
  108.  
    String currentDateString = DateTimeUtil.DateToString(currentDate);
  109.  
     
  110.  
    PdfContentByte canvas = writer.getDirectContent();
  111.  
    BaseFont bf = BaseFont.createFont(contentStyle.getTTFPath(),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  112.  
    Font secFont = new Font(bf, contentStyle.getFontSize(), contentStyle.getStyle(), contentStyle.getBaseColor());
  113.  
    Phrase certificateDatephrase = new Phrase(currentDateString, secFont);
  114.  
    ColumnText.showTextAligned(canvas,contentStyle.getAlignment(), certificateDatephrase, x,y, 0);
  115.  
    return this;
  116.  
    }
  117.  
    /**
  118.  
    * 释放资源
  119.  
    */
  120.  
    public void close(){
  121.  
    document.close();
  122.  
    }
  123.  
    /**
  124.  
    * 第二种解决方案,统一按照宽度压缩
  125.  
    * 这样来的效果是,所有图片的宽度是相等的,自我认为给客户的效果是最好的
  126.  
    * @param args
  127.  
    */
  128.  
    public int getPercent2(float h,float w)
  129.  
    {
  130.  
    int p=0;
  131.  
    float p2=0.0f;
  132.  
    p2=595/w*100;
  133.  
    System.out.println("--"+p2);
  134.  
    p=Math.round(p2);
  135.  
    return p;
  136.  
    }
  137.  
    /**
  138.  
    * 第一种解决方案
  139.  
    * 在不改变图片形状的同时,判断,如果h>w,则按h压缩,否则在w>h或w=h的情况下,按宽度压缩
  140.  
    * @param h
  141.  
    * @param w
  142.  
    * @return
  143.  
    */
  144.  
     
  145.  
    public int getPercent(float h,float w)
  146.  
    {
  147.  
    int p=0;
  148.  
    float p2=0.0f;
  149.  
    if(h>w)
  150.  
    {
  151.  
    p2=297/h*100;
  152.  
    }
  153.  
    else
  154.  
    {
  155.  
    p2=210/w*100;
  156.  
    }
  157.  
    p=Math.round(p2);
  158.  
    return p;
  159.  
    }
  160.  
     
  161.  
    public static void main(String[] args) throws MalformedURLException, FileNotFoundException, DocumentException, IOException {
  162.  
    long currentDateTime = new Date().getTime();
  163.  
    String imagePath = PDFUtil.class.getClassLoader().getResource("certificate.png").getPath();
  164.  
    String pdfFilePath = "d:/pdf/" +7+ ".pdf";
  165.  
    PDFUtil pdfUtil = new PDFUtil();
  166.  
    pdfUtil.openDocumnet(pdfFilePath)
  167.  
    .addImage(imagePath, 0, 400)
  168.  
    .addDateContent(330,462,null)
  169.  
    .addContent("张三",85,655,null)
  170.  
    .close();
  171.  
    }
  172.  
    }

 日期的工具类

  1.  
    package cn.zhuoqianmingyue;
  2.  
     
  3.  
    import java.text.SimpleDateFormat;
  4.  
    import java.util.Date;
  5.  
     
  6.  
    public class DateTimeUtil {
  7.  
     
  8.  
    public static java.util.Date getCurrentDate(){
  9.  
    return new java.util.Date(System.currentTimeMillis());
  10.  
    }
  11.  
     
  12.  
    public static String DateToString(Date date) {
  13.  
    if(date == null){
  14.  
    return "";
  15.  
    }
  16.  
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  17.  
    return sdf.format(date);
  18.  
    }
  19.  
    }

 PDFUtil测试类:

  1.  
    package cn.zhuoqianmingyue;
  2.  
     
  3.  
    import java.io.FileNotFoundException;
  4.  
    import java.io.IOException;
  5.  
    import java.net.MalformedURLException;
  6.  
    import java.util.Date;
  7.  
     
  8.  
    import org.junit.Test;
  9.  
     
  10.  
    import com.itextpdf.text.DocumentException;
  11.  
     
  12.  
    public class PDFUtilTest {
  13.  
     
  14.  
    @Test
  15.  
    public void generatingPdfCertificate () throws MalformedURLException, FileNotFoundException, DocumentException, IOException {
  16.  
    long currentDateTime = new Date().getTime();
  17.  
    String imagePath = PDFUtil.class.getClassLoader().getResource("certificate.png").getPath();
  18.  
    String pdfFilePath = "d:/pdf/" +currentDateTime+ ".pdf";
  19.  
    PDFUtil pdfUtil = new PDFUtil();
  20.  
    pdfUtil.openDocumnet(pdfFilePath)
  21.  
    .addImage(imagePath, 0, 400)
  22.  
    .addDateContent(330,462,null)
  23.  
    .addContent("张三",85,655,null)
  24.  
    .close();
  25.  
    }
  26.  
    }

 pom.xml内容:

  1.  
    <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">
  2.  
    <modelVersion>4.0.0</modelVersion>
  3.  
    <groupId>cn.zhuoqianmingyue</groupId>
  4.  
    <artifactId>certificate</artifactId>
  5.  
    <version>0.0.1-SNAPSHOT</version>
  6.  
    <dependencies>
  7.  
    <dependency>
  8.  
    <groupId>com.itextpdf</groupId>
  9.  
    <artifactId>itextpdf</artifactId>
  10.  
    <version>5.5.11</version>
  11.  
    </dependency>
  12.  
     
  13.  
    <dependency>
  14.  
    <groupId>com.itextpdf</groupId>
  15.  
    <artifactId>itext-asian</artifactId>
  16.  
    <version>5.2.0</version>
  17.  
    </dependency>
  18.  
    <dependency>
  19.  
    <groupId>junit</groupId>
  20.  
    <artifactId>junit</artifactId>
  21.  
    <version>4.12</version>
  22.  
    <scope>test</scope>
  23.  
    </dependency>
  24.  
    </dependencies>
  25.  
    <build>
  26.  
    <plugins>
  27.  
    <plugin>
  28.  
    <groupId>org.apache.maven.plugins</groupId>
  29.  
    <artifactId>maven-compiler-plugin</artifactId>
  30.  
    <version>3.1</version>
  31.  
    <configuration>
  32.  
    <source>1.8</source>
  33.  
    <target>1.8</target>
  34.  
    </configuration>
  35.  
    </plugin>
  36.  
    </plugins>
  37.  
    </build>
  38.  
    </project>

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

 

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

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

分享到:
评论

相关推荐

    Allot中文简介.pdf

    - **市场反响**:自问世以来,NetEnforcer™系列多次荣获业界奖项,包括“最热门产品”等荣誉,并且Allot公司连续五年(2000年至2004年)被Deloitte德勤评为“全球增长最快公司”。 #### 三、产品功能 - **流量管理...

    WEKA教程(完整版).pdf

    - **荣誉与成就**:2005年,在第11届ACM SIGKDD国际会议上,WEKA团队获得了数据挖掘领域的最高服务奖,这标志着WEKA在数据挖掘和机器学习领域的重要地位。 #### 2. 数据格式 - **ARFF格式**:WEKA使用ARFF...

    联迪信息_招聘简章2023届.pdf

    以下是从给定的文件中生成的相关知识点: 一、公司介绍 * 南京联迪信息系统股份有限公司是北京证券交易所上市企业,成立于1999年,员工人数近千人,总部位于江苏省南京市,在上海、泰州、日本东京等国内外城市均设...

    程序员简历模板单页单色风格(优秀毕业生)23.zip

    - **证书与奖项**:如果有相关认证或在学校获得的荣誉,可以增加简历的亮点。 3. **使用Word(docx)编辑简历**: - **模板应用**:利用docx模板可以快速生成专业外观的简历,节省设计时间。 - **自定义内容**:...

    resume:个人公开简历

    6. 证书和荣誉:任何提升个人资质的证书或奖项都应提及。 7. 兴趣爱好:展示个人特质,但应保持相关性。 五、代码实践 创建HTML简历时,需用文本编辑器(如Sublime Text、Visual Studio Code等)编写代码,然后用...

    resume:一个非常好的简历模板(请相信我)

    将你的信息替换掉模板中的占位符,然后编译文件,就可以生成PDF格式的简历了。 总的来说,利用LaTeX创建简历不仅可以保证格式的一致性和专业性,还允许你自定义样式和布局,以满足个人需求。这个“resume:一个非常...

Global site tag (gtag.js) - Google Analytics