欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

利用Java对PDF文件进行电子签章的实战过程

程序员文章站 2022-03-13 13:34:04
目录四、 如何按模板生成pdf文件1. 制作pdf模板2. 制作一个如下图的pdf模板,该模板是带有pdf的表单域的五、 如何生成pkcs12证书1. pkcs的简单介绍2. 使用java生成一个pk...

一、 概述

印章是我国特有的历史文化产物,古代主要用作身份凭证和行驶职权的工具。它的起源是由于社会生活的实际需要。早在商周时代,印章就已经产生。如今的印章已成为一种独特的,融实用性和艺术性为一体的艺术瑰宝。传统的印章容易被坏人、小人私刻;从而新闻鲜有报道某某私刻公章,侵吞国家财产。随着计算机技术、加密技术及图像处理技术的发展,出现了电子签章。电子签章是电子签名的一种表现形式,利用图像处理技术、数字加密技术将电子签名操作转化为与纸质文件盖章操作相同的可视效果,同时利用电子签名技术保障电子信息的真实性和完整性以及签名人的不可否认性。

电子签章与数字证书一样是身份验证的一种手段,泛指所有以电子形式存在,依附在电子文件并与其逻辑关联,可用以辨识电子文件签署者身份,保证文件的完整性,并表示签署者同意电子文件所陈述事实的内容。一般来说对电子签章的认定都是从技术角度而言的。主要是指通过特定的技术方案来鉴别当事人的身份及确保电子资料内容不被篡改的安全保障措施。电子签章常于发送安全电子邮件、访问安全站点、网上招标投标、网上签约、安全网上公文传送、公司合同、电子处方笺等。

电子签章是一个很复杂的问题,大到有相关的电子签章系统;今天分享一下如何把电子签章应用到电子处方笺的pdf文件里。

二、 技术选型

目前主流处理pdf文件两个jar包分别是:

  • 开源组织apache的pdfbox,官网https://pdfbox.apache.org/
  • 大名鼎鼎adobe公司的itext,官网https://itextpdf.com/tags/adobe,其中itext又分为itext5和itext7

如何在pdfbox、itext5和itext7选出合适自己项目的技术呢?

对比pdfbox、itext5和itext7这三者:

  1. pdfbox的功能相对较弱,itext5和itext7的功能非常强悍;
  2. itext5的资料网上相对较多,如果出现问题容易找到解决方案;pdfbox和itext7的网上资料相对较少,如果出现问题不易找到相关解决方案;
  3. 通过阅读pdfbox代码目前pdfbox还没提供自定义签章的相关接口;itext5和itext7提供了处理自定义签章的相关实现;
  4. pdfbox只能实现把签章图片加签到pdf文件;itext5和itext7除了可以把签章图片加签到pdf文件,还可以实现直接对签章进行绘制,把文件绘制到签章上。
  5. pdfbox和itext5/itext7使用的协议不一样。pdfbox使用的是apache license version 2.0(https://www.apache.org/licenses/);itext5/itext7使用的是agpl(https://itextpdf.com/agpl)。pdfbox免费使用,agpl商用收费

本分享java对pdf文件进行电子签章需要实现的功能:

  1. 生成证书。与pdfbox、itext5和itext7技术无关
  2. 按模板输出pdf文件:pdfbox、itext5和itext7都可以完成,但是pdfbox会遇到中文乱码比较棘手的问题
  3. 在pdf文件中实现把签章图片加签到pdf文件:pdfbox、itext5和itext7都可以实现,没有很多的区别
  4. 在pdf文件中绘制签章:itext5和itext7都可以实现,pdfbox目前不支持
  5. 在pdf文件中生成高清签章:itext5和itext7都可以实现,pdfbox目前不支持
  6. 在pdf文件中进行多次签名::pdfbox、itext5和itext7都可以完成,没有区别

通过相关技术分析和要实现的功能分析,采用itext5进行开发,唯一遗憾的是itext商用收费;但是这不是做技术需要关心的!!选用itext5的理由:

  • 使用itext5能实现全部的功能
  • 如何在开发中遇到相关问题,容易找到相应解决方案

三、 生成一个图片签章

1. 生成一个如下图的签章图片

利用Java对PDF文件进行电子签章的实战过程

2. 相关代码

    import java.awt.color;
    import java.awt.font;
    import java.awt.fontmetrics;
    import java.awt.graphics2d;
    import java.awt.renderinghints;
    import java.awt.image.bufferedimage;
    import java.io.fileoutputstream;
    import java.io.ioexception;
    import sun.font.fontdesignmetrics;
 
    import com.sun.image.codec.jpeg.jpegcodec;
    import com.sun.image.codec.jpeg.jpegencodeparam;
    import com.sun.image.codec.jpeg.jpegimageencoder;
 
    public class signimage {
 
    /**
     * @param doctorname
     *            string 医生名字
     * @param hospitalname
     *            string 医生名称
     * @param date
     *            string 签名日期
     *            图片高度
     * @param jpgname
     *            string jpg图片名
     * @return
     */
    public static boolean createsigntextimg(
            string doctorname, //
            string hospitalname, //
            string date, 
            string jpgname) {
        int width = 255;
        int height = 100;
        fileoutputstream out = null;
        //背景色
        color bgcolor = color.white;
        //字色
        color fontcolor = color.red;
        font doctornamefont = new font(null, font.bold, 20);
        font othortextfont = new font(null, font.bold, 18);
        try { // 宽度 高度
            bufferedimage bimage = new bufferedimage(width, height,
                    bufferedimage.type_int_rgb);
            graphics2d g = bimage.creategraphics();
            g.setcolor(bgcolor); // 背景色
            g.fillrect(0, 0, width, height); // 画一个矩形
            g.setrenderinghint(renderinghints.key_antialiasing,
                    renderinghints.value_antialias_on); // 去除锯齿(当设置的字体过大的时候,会出现锯齿)
 
            g.setcolor(color.red);
            g.fillrect(0, 0, 8, height);
            g.fillrect(0, 0, width, 8);
            g.fillrect(0, height - 8, width, height);
            g.fillrect(width - 8, 0, width, height);
 
            g.setcolor(fontcolor); // 字的颜色
            g.setfont(doctornamefont); // 字体字形字号
            fontmetrics fm = fontdesignmetrics.getmetrics(doctornamefont);
            int font1_hight = fm.getheight();
            int strwidth = fm.stringwidth(doctorname);
            int y = 35;
            int x = (width - strwidth) / 2;
            g.drawstring(doctorname, x, y); // 在指定坐标除添加文字
 
            g.setfont(othortextfont); // 字体字形字号
 
            fm = fontdesignmetrics.getmetrics(othortextfont);
            int font2_hight = fm.getheight();
            strwidth = fm.stringwidth(hospitalname);
            x = (width - strwidth) / 2;
            g.drawstring(hospitalname, x, y + font1_hight); // 在指定坐标除添加文字
 
            strwidth = fm.stringwidth(date);
            x = (width - strwidth) / 2;
            g.drawstring(date, x, y + font1_hight + font2_hight); // 在指定坐标除添加文字
 
            g.dispose();
            out = new fileoutputstream(jpgname); // 指定输出文件
            jpegimageencoder encoder = jpegcodec.createjpegencoder(out);
            jpegencodeparam param = encoder.getdefaultjpegencodeparam(bimage);
            param.setquality(50f, true);
            encoder.encode(bimage, param); // 存盘
            out.flush();
            return true;
        } catch (exception e) {
            return false;
        }finally{
            if(out!=null){
                try {
                    out.close();
                } catch (ioexception e) {
                }
            }
        }
    }
    public static void main(string[] args) {
        createsigntextimg("华佗", "在线医院", "2018.01.01",   "sign.jpg");
    }
}

四、 如何按模板生成pdf文件

1. 制作pdf模板

目前pdf模板工具别无他物,只能使用伟大的adobe公司提供的adobe acrobatpro dc软件进行制作。如何使用该软件这里就不多说了,如果在使用中遇到什么可以另外咨询。

2. 制作一个如下图的pdf模板,该模板是带有pdf的表单域的

利用Java对PDF文件进行电子签章的实战过程

五、 如何生成pkcs12证书

1. pkcs的简单介绍

pkcs:the public-key cryptography standards (简称pkcs)是由美国rsa数据安全公司及其合作伙伴制定的一组公钥密码学标准,其中包括证书申请、证书更新、证书作废表发布、扩展证书内容以及数字签名、数字信封的格式等方面的一系列相关协议。

到1999年底,pkcs已经公布了以下标准:

  • pkcs#1:定义rsa公开密钥算法加密和签名机制,主要用于组织pkcs#7中所描述的数字签名和数字信封[22]。
  • pkcs#3:定义diffie-hellman密钥交换协议[23]。
  • pkcs#5:描述一种利用从口令派生出来的安全密钥加密字符串的方法。使用md2或md5 从口令中派生密钥,并采用des-cbc模式加密。主要用于加密从一个计算机传送到另一个计算机的私人密钥,不能用于加密消息[24]。
  • pkcs#6:描述了公钥证书的标准语法,主要描述x.509证书的扩展格式[25]。
  • pkcs#7:定义一种通用的消息语法,包括数字签名和加密等用于增强的加密机制,pkcs#7与pem兼容,所以不需其他密码操作,就可以将加密的消息转换成pem消息[26]。
  • pkcs#8:描述私有密钥信息格式,该信息包括公开密钥算法的私有密钥以及可选的属性集等[27]。
  • pkcs#9:定义一些用于pkcs#6证书扩展、pkcs#7数字签名和pkcs#8私钥加密信息的属性类型[28]。
  • pkcs#10:描述证书请求语法[29]。
  • pkcs#11:称为cyptoki,定义了一套独立于技术的程序设计接口,用于智能卡和pcmcia卡之类的加密设备[30]。
  • pkcs#12:描述个人信息交换语法标准。描述了将用户公钥、私钥、证书和其他相关信息打包的语法[31]。
  • pkcs#13:椭圆曲线密码*标准[32]。
  • pkcs#14:伪随机数生成标准。
  • pkcs#15:密码令牌信息格式标准[33]。

pkcs12也就是以上标准的pkcs#12,主要用来描述个人身份信息;本次分享中要进行签章操作的是医生和药师,他们就是一个个人主体,给他们分配一个pkcs12的证书,就等于给他们分配了一个用于盖章的印章。

2. 使用java生成一个pkcs12证书并进行存贮,相关分析见代码注解

    public class extension {
 
        private string oid;
 
        private boolean critical;
 
        private byte[] value;
 
        public string getoid() {
            return oid;
        }
 
        public byte[] getvalue() {
            return value;
        }
        public boolean iscritical() {
            return critical;
        }
    }
 
 
    import java.io.bytearrayinputstream;
    import java.io.bytearrayoutputstream;
    import java.io.file;
    import java.io.fileoutputstream;
    import java.io.ioexception;
    import java.math.biginteger;
    import java.security.keypair;
    import java.security.keypairgenerator;
    import java.security.keystore;
    import java.security.nosuchalgorithmexception;
    import java.security.privatekey;
    import java.security.publickey;
    import java.security.securerandom;
    import java.security.cert.certificate;
    import java.security.cert.certificatefactory;
    import java.security.cert.x509certificate;
    import java.text.simpledateformat;
    import java.util.calendar;
    import java.util.date;
    import java.util.hashmap;
    import java.util.list;
    import java.util.map;
    import java.util.random;
 
    import org.bouncycastle.asn1.asn1objectidentifier;
    import org.bouncycastle.asn1.asn1primitive;
    import org.bouncycastle.asn1.x500.x500name;
    import org.bouncycastle.asn1.x509.basicconstraints;
    import org.bouncycastle.asn1.x509.crldistpoint;
    import org.bouncycastle.asn1.x509.distributionpoint;
    import org.bouncycastle.asn1.x509.distributionpointname;
    import org.bouncycastle.asn1.x509.generalname;
    import org.bouncycastle.asn1.x509.generalnames;
    import org.bouncycastle.asn1.x509.keyusage;
    import org.bouncycastle.cert.x509certificateholder;
    import org.bouncycastle.cert.x509v3certificatebuilder;
    import org.bouncycastle.cert.jcajce.jcax509v3certificatebuilder;
    import org.bouncycastle.jce.provider.bouncycastleprovider;
    import org.bouncycastle.operator.contentsigner;
    import org.bouncycastle.operator.jcajce.jcacontentsignerbuilder;
 
    public class pkcs {
 
    private static keypair getkey() throws nosuchalgorithmexception {
        keypairgenerator generator = keypairgenerator.getinstance("rsa",
                new bouncycastleprovider());
        generator.initialize(1024);
        // 证书中的密钥 公钥和私钥
        keypair keypair = generator.generatekeypair();
        return keypair;
    }
 
    /**
     * @param password
     *            密码
     * @param issuerstr 颁发机构信息
     * 
     * @param subjectstr 使用者信息
     * 
    * @param certificatecrl 颁发地址
     * 
     * @return
     */
    public static map<string, byte[]> createcert(string password,
            string issuerstr, string subjectstr, string certificatecrl) {
        map<string, byte[]> result = new hashmap<string, byte[]>();
        bytearrayoutputstream out = null;
        try {
            // 生成jks证书
            // keystore keystore = keystore.getinstance("jks");
            // 标志生成pkcs12证书
            keystore keystore = keystore.getinstance("pkcs12",
                    new bouncycastleprovider());
            keystore.load(null, null);
            keypair keypair = getkey();
            // issuer与 subject相同的证书就是ca证书
            certificate cert = generatecertificatev3(issuerstr, subjectstr,
                    keypair, result, certificatecrl, null);
            // cretkey随便写,标识别名
            keystore.setkeyentry("cretkey", keypair.getprivate(),
                    password.tochararray(), new certificate[] { cert });
            out = new bytearrayoutputstream();
            cert.verify(keypair.getpublic());
            keystore.store(out, password.tochararray());
            byte[] keystoredata = out.tobytearray();
            result.put("keystoredata", keystoredata);
            return result;
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (ioexception e) {
                }
            }
        }
        return result;
    }
 
    /**
     * @param issuerstr
     * @param subjectstr
     * @param keypair
     * @param result
     * @param certificatecrl
     * @param extensions
     * @return
     */
    public static certificate generatecertificatev3(string issuerstr,
            string subjectstr, keypair keypair, map<string, byte[]> result,
            string certificatecrl, list<extension> extensions) {
        bytearrayinputstream bout = null;
        x509certificate cert = null;
        try {
            publickey publickey = keypair.getpublic();
            privatekey privatekey = keypair.getprivate();
            date notbefore = new date();
            calendar rightnow = calendar.getinstance();
            rightnow.settime(notbefore);
            // 日期加1年
            rightnow.add(calendar.year, 1);
            date notafter = rightnow.gettime();
            // 证书序列号
            biginteger serial = biginteger.probableprime(256, new random());
            x509v3certificatebuilder builder = new jcax509v3certificatebuilder(
                    new x500name(issuerstr), serial, notbefore, notafter,
                    new x500name(subjectstr), publickey);
            jcacontentsignerbuilder jbuilder = new jcacontentsignerbuilder(
                    "sha1withrsa");
            securerandom securerandom = new securerandom();
            jbuilder.setsecurerandom(securerandom);
            contentsigner singer = jbuilder.setprovider(
                    new bouncycastleprovider()).build(privatekey);
            // 分发点
            asn1objectidentifier crldistributionpoints = new asn1objectidentifier(
                    "2.5.29.31");
            generalname generalname = new generalname(
                    generalname.uniformresourceidentifier, certificatecrl);
            generalnames seneralnames = new generalnames(generalname);
            distributionpointname distributionpoint = new distributionpointname(
                    seneralnames);
            distributionpoint[] points = new distributionpoint[1];
            points[0] = new distributionpoint(distributionpoint, null, null);
            crldistpoint crldistpoint = new crldistpoint(points);
            builder.addextension(crldistributionpoints, true, crldistpoint);
            // 用途
            asn1objectidentifier keyusage = new asn1objectidentifier(
                    "2.5.29.15");
            // | keyusage.nonrepudiation | keyusage.keycertsign
            builder.addextension(keyusage, true, new keyusage(
                    keyusage.digitalsignature | keyusage.keyencipherment));
            // 基本限制 x509extension.java
            asn1objectidentifier basicconstraints = new asn1objectidentifier(
                    "2.5.29.19");
            builder.addextension(basicconstraints, true, new basicconstraints(
                    true));
            // privkey:使用自己的私钥进行签名,ca证书
            if (extensions != null)
                for (extension ext : extensions) {
                    builder.addextension(
                            new asn1objectidentifier(ext.getoid()),
                            ext.iscritical(),
                            asn1primitive.frombytearray(ext.getvalue()));
                }
            x509certificateholder holder = builder.build(singer);
            certificatefactory cf = certificatefactory.getinstance("x.509");
            bout = new bytearrayinputstream(holder.toasn1structure()
                    .getencoded());
            cert = (x509certificate) cf.generatecertificate(bout);
            byte[] certbuf = holder.getencoded();
            simpledateformat format = new simpledateformat("yyyy-mm-dd");
            // 证书数据
            result.put("certificatedata", certbuf);
            //公钥
            result.put("publickey", publickey.getencoded());
            //私钥
            result.put("privatekey", privatekey.getencoded());
            //证书有效开始时间
            result.put("notbefore", format.format(notbefore).getbytes("utf-8"));
            //证书有效结束时间
            result.put("notafter", format.format(notafter).getbytes("utf-8"));
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            if (bout != null) {
                try {
                    bout.close();
                } catch (ioexception e) {
                }
            }
        }
        return cert;
    }
 
    public static void main(string[] args) throws exception{
        // cn: 名字与姓氏    ou : 组织单位名称
        // o :组织名称  l : 城市或区域名称  e : 电子邮件
        // st: 州或省份名称  c: 单位的两字母国家代码 
        string issuerstr = "cn=在线医院,ou=gitbook研发部,o=gitbook有限公司,c=cn,e=gitbook@sina.com,l=北京,st=北京";
        string subjectstr = "cn=huangjinjin,ou=gitbook研发部,o=gitbook有限公司,c=cn,e=huangjinjin@sina.com,l=北京,st=北京";
        string certificatecrl  = "https://gitbook.cn";
        map<string, byte[]> result = createcert("123456", issuerstr, subjectstr, certificatecrl);
 
        fileoutputstream outputstream = new fileoutputstream("c:/keystore.p12"); // ca.jks
        outputstream.write(result.get("keystoredata"));
        outputstream.close();
        fileoutputstream fos = new fileoutputstream(new file("c:/keystore.cer"));
        fos.write(result.get("certificatedata"));
        fos.flush();
        fos.close();
    }
    }

六、 如何生成一个高清晰的签章

1. 由pdf模板生成一个pdf文件,见代码注解

    import java.io.fileoutputstream;
    import java.io.ioexception;
    import java.io.outputstream;
    import java.util.arraylist;
    import java.util.hashmap;
    import java.util.iterator;
    import java.util.list;
    import java.util.map;
    import com.itextpdf.text.documentexception;
    import com.itextpdf.text.pdf.acrofields;
    import com.itextpdf.text.pdf.acrofields.item;
    import com.itextpdf.text.pdf.basefont;
    import com.itextpdf.text.pdf.pdfreader;
    import com.itextpdf.text.pdf.pdfstamper;
 
    public class pdfutils {
 
 
    /**
     * @param fields
     * @param data
     * @throws ioexception
     * @throws documentexception
     */
    private static void filldata(acrofields fields, map<string, string> data) throws ioexception, documentexception {
        list<string> keys = new arraylist<string>();
        map<string, item> formfields = fields.getfields();
        for (string key : data.keyset()) {
            if(formfields.containskey(key)){
                string value = data.get(key);
                fields.setfield(key, value); // 为字段赋值,注意字段名称是区分大小写的
                keys.add(key);
            }
        }
        iterator<string> itemskey = formfields.keyset().iterator();
        while(itemskey.hasnext()){
            string itemkey = itemskey.next();
            if(!keys.contains(itemkey)){
                fields.setfield(itemkey, " ");
            }
        }
    }
 
    /**
     * @param templatepdfpath
     *            模板pdf路径
     * @param generatepdfpath
     *            生成pdf路径
     * @param data
     *            数据
     */
    public static string generatepdf(string templatepdfpath, string generatepdfpath, map<string, string> data) {
        outputstream fos = null;
        bytearrayoutputstream bos = null;
        try {
            pdfreader reader = new pdfreader(templatepdfpath);
            bos = new bytearrayoutputstream();
            /* 将要生成的目标pdf文件名称 */
            pdfstamper ps = new pdfstamper(reader, bos);
            /* 使用中文字体 */
            basefont bf = basefont.createfont("stsong-light", "unigb-ucs2-h",basefont.not_embedded);
            arraylist<basefont> fontlist = new arraylist<basefont>();
            fontlist.add(bf);
            /* 取出报表模板中的所有字段 */
            acrofields fields = ps.getacrofields();
            fields.setsubstitutionfonts(fontlist);
            filldata(fields, data);
            /* 必须要调用这个,否则文档不会生成的  如果为false那么生成的pdf文件还能编辑,一定要设为true*/
            ps.setformflattening(true);
            ps.close();
            fos = new fileoutputstream(generatepdfpath);
            fos.write(bos.tobytearray());
            fos.flush();
            return generatepdfpath;
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (ioexception e) {
                    e.printstacktrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (ioexception e) {
                    e.printstacktrace();
                }
            }
        }
        return null;
    }
 
    public static void main(string[] args) {
        map<string, string> data = new hashmap<string, string>();
        //key为pdf模板的form表单的名字,value为需要填充的值
        data.put("title", "在线医院");
        data.put("case", "123456789");
        data.put("date", "2018.12.07");
        data.put("name", "gitbook");
        data.put("sex", "男");
        data.put("age", "29");
        data.put("phone", "13711645814");
        data.put("office", "内科");
        data.put("cert", "身痒找打");
        data.put("drug", "1、奥美拉唑肠溶胶囊             0.25g10粒×2板 ");
        data.put("dose", "×2盒");
        data.put("cons", "用法用量:口服 一日两次 一次2粒");
        data.put("tips", "温馨提示");
        data.put("desc", "尽量呆在通风较好的地方,保持空气流通,有利于病情康复。尽量呆在通风较好的地方");
        generatepdf("c:\\users\\zhilin\\desktop\\chat\\tpl.pdf", 
                "c:\\users\\zhilin\\desktop\\chat\\filled.pdf", data );
    }
    }

利用Java对PDF文件进行电子签章的实战过程

2. 对pdf文件进行签章

经过过上面的代码可以生成一个名为sign.jpg的签章图片,生成一个keystore.p12的证书文件,还有一个已经通过模板填充了表单的名为filled.pdf的pdf文件。下面就可通过以上材料生成一个签名的pdf文件。

    import java.io.file;
    import java.io.fileinputstream;
    import java.io.fileoutputstream;
    import java.io.ioexception;
    import java.security.keystore;
    import java.security.privatekey;
    import java.security.security;
    import java.security.cert.certificate;
    import java.util.uuid;
 
    import org.bouncycastle.jce.provider.bouncycastleprovider;
 
    import com.itextpdf.text.image;
    import com.itextpdf.text.rectangle;
    import com.itextpdf.text.pdf.pdfreader;
    import com.itextpdf.text.pdf.pdfsignatureappearance;
    import com.itextpdf.text.pdf.pdfsignatureappearance.renderingmode;
    import com.itextpdf.text.pdf.pdfstamper;
    import com.itextpdf.text.pdf.security.bouncycastledigest;
    import com.itextpdf.text.pdf.security.digestalgorithms;
    import com.itextpdf.text.pdf.security.externaldigest;
    import com.itextpdf.text.pdf.security.externalsignature;
    import com.itextpdf.text.pdf.security.makesignature;
    import com.itextpdf.text.pdf.security.makesignature.cryptostandard;
    import com.itextpdf.text.pdf.security.privatekeysignature;
 
 
    public class signpdf {
    /**
     * @param password
     *            秘钥密码
     * @param keystorepath
     *            秘钥文件路径
     * @param signpdfsrc
     *            签名的pdf文件
     * @param signimage
     *            签名图片文件
     * @param x
     *            x坐标
     * @param y
     *            y坐标
     * @return
     */
    public static byte[] sign(string password, string keystorepath, string signpdfsrc, string signimage,
            float x, float y) {
        file signpdfsrcfile = new file(signpdfsrc);
        pdfreader reader = null;
        bytearrayoutputstream signpdfdata = null;
        pdfstamper stp = null;
        fileinputstream fos = null;
        try {
            bouncycastleprovider provider = new bouncycastleprovider();
            security.addprovider(provider);
            keystore ks = keystore.getinstance("pkcs12", new bouncycastleprovider());
            fos = new fileinputstream(keystorepath);
            // 私钥密码 为pkcs生成证书是的私钥密码 123456
            ks.load(fos, password.tochararray()); 
            string alias = (string) ks.aliases().nextelement();
            privatekey key = (privatekey) ks.getkey(alias, password.tochararray());
            certificate[] chain = ks.getcertificatechain(alias);
            reader = new pdfreader(signpdfsrc);
            signpdfdata = new bytearrayoutputstream();
            // 临时pdf文件
            file temp = new file(signpdfsrcfile.getparent(), system.currenttimemillis() + ".pdf");
            stp = pdfstamper.createsignature(reader, signpdfdata, '\0', temp, true);
             stp.setfullcompression();
            pdfsignatureappearance sap = stp.getsignatureappearance();
            sap.setreason("数字签名,不可改变");
            // 使用png格式透明图片
            image image = image.getinstance(signimage);
            sap.setimagescale(0);
            sap.setsignaturegraphic(image);
            sap.setrenderingmode(renderingmode.graphic);
            // 是对应x轴和y轴坐标
            sap.setvisiblesignature(new rectangle(x, y, x + 185, y + 68), 1,
                    uuid.randomuuid().tostring().replaceall("-", ""));
            stp.getwriter().setcompressionlevel(5);
            externaldigest digest = new bouncycastledigest();
            externalsignature signature = new privatekeysignature(key, digestalgorithms.sha512, provider.getname());
            makesignature.signdetached(sap, digest, signature, chain, null, null, null, 0, cryptostandard.cades);
            stp.close();
            reader.close();
            return signpdfdata.tobytearray();
        } catch (exception e) {
            e.printstacktrace();
        } finally {
 
            if (signpdfdata != null) {
                try {
                    signpdfdata.close();
                } catch (ioexception e) {
                }
            }
 
            if (fos != null) {
                try {
                    fos.close();
                } catch (ioexception e) {
                }
            }
        }
        return null;
    }
 
    public static void main(string[] args) throws exception {
        byte[] filedata = sign("123456", "c:\\users\\zhilin\\desktop\\chat\\keystore.p12", //
                "c:\\users\\zhilin\\desktop\\chat\\filled.pdf",//
                "c:\\users\\zhilin\\desktop\\chat\\sign.jpg", 100, 290);
        fileoutputstream f = new fileoutputstream(new file("c:\\users\\zhilin\\desktop\\chat\\signed.pdf"));
        f.write(filedata);
        f.close();
    }
    }

利用Java对PDF文件进行电子签章的实战过程

3. 高清签章

高清签章是通过itext的绘制功能来完成。主要直接在pdf文件中绘制签章,代码实现如下:

    import java.io.file;
    import java.io.fileinputstream;
    import java.io.fileoutputstream;
    import java.io.ioexception;
    import java.security.keystore;
    import java.security.privatekey;
    import java.security.security;
    import java.security.cert.certificate;
    import org.bouncycastle.jce.provider.bouncycastleprovider;
 
    import com.itextpdf.awt.asianfontmapper;
    import com.itextpdf.text.basecolor;
    import com.itextpdf.text.element;
    import com.itextpdf.text.font;
    import com.itextpdf.text.paragraph;
    import com.itextpdf.text.rectangle;
    import com.itextpdf.text.pdf.basefont;
    import com.itextpdf.text.pdf.columntext;
    import com.itextpdf.text.pdf.pdfreader;
    import com.itextpdf.text.pdf.pdfsignatureappearance;
    import com.itextpdf.text.pdf.pdfstamper;
    import com.itextpdf.text.pdf.pdfstream;
    import com.itextpdf.text.pdf.pdftemplate;
    import com.itextpdf.text.pdf.security.bouncycastledigest;
    import com.itextpdf.text.pdf.security.digestalgorithms;
    import com.itextpdf.text.pdf.security.externaldigest;
    import com.itextpdf.text.pdf.security.externalsignature;
    import com.itextpdf.text.pdf.security.makesignature;
    import com.itextpdf.text.pdf.security.makesignature.cryptostandard;
    import com.itextpdf.text.pdf.security.privatekeysignature;
 
 
    public class signhighpdf {
 
    /**
     * @param password
     *            秘钥密码
     * @param keystorepath
     *            秘钥文件路径
     * @param signpdfsrc
     *            签名的pdf文件
     * @param x
     * 
     * @param y
     * @return
     */
    public static byte[] sign(string password, string keystorepath, string signpdfsrc, 
            float x, float y,
            string signtext) {
        file signpdfsrcfile = new file(signpdfsrc);
        pdfreader reader = null;
        bytearrayoutputstream signpdfdata = null;
        pdfstamper stp = null;
        fileinputstream fos = null;
        try {
            bouncycastleprovider provider = new bouncycastleprovider();
            security.addprovider(provider);
            keystore ks = keystore.getinstance("pkcs12", new bouncycastleprovider());
            fos = new fileinputstream(keystorepath);
            ks.load(fos, password.tochararray()); // 私钥密码
            string alias = (string) ks.aliases().nextelement();
            privatekey key = (privatekey) ks.getkey(alias, password.tochararray());
            certificate[] chain = ks.getcertificatechain(alias);
            reader = new pdfreader(signpdfsrc);
            signpdfdata = new bytearrayoutputstream();
            // 临时pdf文件
            file temp = new file(signpdfsrcfile.getparent(), system.currenttimemillis() + ".pdf");
            stp = pdfstamper.createsignature(reader, signpdfdata, '\0', temp, true);
            pdfsignatureappearance sap = stp.getsignatureappearance();
            sap.setreason("数字签名,不可改变");
            // 是对应x轴和y轴坐标
            sap.setvisiblesignature(new rectangle(x, y, x + 150, y + 65), 1,
                    "sr"+string.valueof(system.nanotime()));
            /layer 0 creating the appearance for layer 0
            pdftemplate n0 = sap.getlayer(0);
            n0.reset();
            float lx = n0.getboundingbox().getleft();
            float by = n0.getboundingbox().getbottom();
            float width = n0.getboundingbox().getwidth();
            float height = n0.getboundingbox().getheight();
            n0.setrgbcolorfill(255, 0, 0);
            n0.rectangle(lx, by, 5, height);
            n0.rectangle(lx, by, width, 5);
            n0.rectangle(lx, by+height-5, width, 5);
            n0.rectangle(lx+width-5, by, 5, height);
            n0.fill();
            ///layer 2
            pdftemplate n2 = sap.getlayer(2);
            n2.setcharacterspacing(0.0f);
            columntext ct = new columntext(n2);
            ct.setsimplecolumn(n2.getboundingbox());
            n2.setrgbcolorfill(255, 0, 0);
            //做一个占位的动作
            paragraph p1 = new paragraph(" ");
            basefont bf = basefont.createfont(asianfontmapper.chinesesimplifiedfont, asianfontmapper.chinesesimplifiedencoding_h, 
                    basefont.not_embedded);
            font font1 = new font(bf, 5, font.bold, basecolor.red);
            font font2 = new font(bf, 13, font.bold, basecolor.red);
            p1.setfont(font1);
            ct.addelement(p1);
            paragraph p = new paragraph(signtext);
            p.setalignment(element.align_center);
            p.setfont(font2);
            ct.addelement(p);
            ct.go();
            stp.getwriter().setcompressionlevel(pdfstream.best_compression);
            externaldigest digest = new bouncycastledigest();
            externalsignature signature = new privatekeysignature(key, digestalgorithms.sha512, provider.getname());
            makesignature.signdetached(sap, digest, signature, chain, null, null, null, 0, cryptostandard.cades);
            stp.close();
            reader.close();
            return signpdfdata.tobytearray();
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            if (signpdfdata != null) {
                try {
                    signpdfdata.close();
                } catch (ioexception e) {
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (ioexception e) {
                }
            }
        }
        return null;
    }
 
    public static void main(string[] args) throws exception {
        //对已经签章的signed.pdf文件再次签章,这次是高清签章
        byte[] filedata = sign("123456", "c:\\users\\zhilin\\desktop\\chat\\keystore.p12",//
                "c:\\users\\zhilin\\desktop\\chat\\signed.pdf", 350, 290, "华佗\n2017-12-20");
        fileoutputstream f = new fileoutputstream(new file("c:\\users\\zhilin\\desktop\\chat\\signed2.pdf"));
        f.write(filedata);
        f.close();
    }
 
    }

可以分析下下面这两个签章的区别,发现左边的签章很模糊,右边的特别清晰。

利用Java对PDF文件进行电子签章的实战过程

七、 如何进行多次pdf签名

生成多个签章重点代码,已在signpdf.java类进行标注说明;如果想进行多次签名,就只需对已经进行过签名的pdf文件再次调用sign方法进行再次签名即可(第六点有张图片就有两个签章,这就是多次签名的结果)。

pdfstamper.createsignature(reader, signpdfdata, '\0', temp, true);

八、 总结

分享中sign.jpg文件的白色背景需要做透明化处理才能达到正确电子签章的效果(不覆盖pdf文件中已有的内容,真实的电子签章也是这样做的),大家回去可以思考下怎么把一个jpg文件白色背景透明化(高清签章就已经实现透明化,可以试着把signpdf.java和signhighpdf.java签章到有文字的pdf上面看看效果)。

大家见到的公司公章都是圆形的;这个也是可以做到的大家想想怎样生成一个圆形的图片签章;然后进行电子签名。这里主要是讲解代码实现,所有代码非常多。大家回去好好研读代码。真正的电子签名需要通过ca认证公司来完成,我这里只是提供参考方案让大家学习。

到此这篇关于利用java对pdf文件进行电子签章的文章就介绍到这了,更多相关java对pdf文件电子签章内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!