Java 對 PDF 文件進行電子簽章


如何用 Java 對 PDF 文件進行電子簽章

 

 

一、 概述

印章是我國特有的歷史文化產物,古代主要用作身份憑證和行駛職權的工具。它的起源是由於社會生活的實際需要。早在商周時代,印章就已經產生。如今的印章已成為一種獨特的,融實用性和藝術性為一體的藝術瑰寶。傳統的印章容易被壞人、小人私刻;從而新聞鮮有報道某某私刻公章,侵吞國家財產。隨着計算機技術、加密技術及圖像處理技術的發展,出現了電子簽章。電子簽章是電子簽名的一種表現形式,利用圖像處理技術、數字加密技術將電子簽名操作轉化為與紙質文件蓋章操作相同的可視效果,同時利用電子簽名技術保障電子信息的真實性和完整性以及簽名人的不可否認性。

電子簽章與數字證書一樣是身份驗證的一種手段,泛指所有以電子形式存在,依附在電子文件並與其邏輯關聯,可用以辨識電子文件簽署者身份,保證文件的完整性,並表示簽署者同意電子文件所陳述事實的內容。一般來說對電子簽章的認定都是從技術角度而言的。主要是指通過特定的技術方案來鑒別當事人的身份及確保電子資料內容不被篡改的安全保障措施。電子簽章常於發送安全電子郵件、訪問安全站點、網上招標投標、網上簽約、安全網上公文傳送、公司合同、電子處方箋等。

電子簽章是一個很復雜的問題,大到有相關的電子簽章系統;今天分享一下如何把電子簽章應用到電子處方箋的PDF文件里。

二、 技術選型

目前主流處理PDF文件兩個jar包分別是:

  1. 開源組織Apache的PDFBox,官網https://pdfbox.apache.org/
  2. 大名鼎鼎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的理由:

  1. 使用iText5能實現全部的功能
  2. 如何在開發中遇到相關問題,容易找到相應解決方案

三、 生成一個圖片簽章

1. 生成一個如下圖的簽章圖片

enter image description here

2. 相關代碼

  1.  
    import java.awt.Color;
  2.  
    import java.awt.Font;
  3.  
    import java.awt.FontMetrics;
  4.  
    import java.awt.Graphics2D;
  5.  
    import java.awt.RenderingHints;
  6.  
    import java.awt.image.BufferedImage;
  7.  
    import java.io.FileOutputStream;
  8.  
    import java.io.IOException;
  9.  
    import sun.font.FontDesignMetrics;
  10.  
     
  11.  
    import com.sun.image.codec.jpeg.JPEGCodec;
  12.  
    import com.sun.image.codec.jpeg.JPEGEncodeParam;
  13.  
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
  14.  
     
  15.  
    public class SignImage {
  16.  
     
  17.  
    /**
  18.  
    * @param doctorName
  19.  
    * String 醫生名字
  20.  
    * @param hospitalName
  21.  
    * String 醫生名稱
  22.  
    * @param date
  23.  
    * String 簽名日期
  24.  
    * 圖片高度
  25.  
    * @param jpgname
  26.  
    * String jpg圖片名
  27.  
    * @return
  28.  
    */
  29.  
    public static boolean createSignTextImg(
  30.  
    String doctorName, //
  31.  
    String hospitalName, //
  32.  
    String date,
  33.  
    String jpgname) {
  34.  
    int width = 255;
  35.  
    int height = 100;
  36.  
    FileOutputStream out = null;
  37.  
    //背景色
  38.  
    Color bgcolor = Color.WHITE;
  39.  
    //字色
  40.  
    Color fontcolor = Color.RED;
  41.  
    Font doctorNameFont = new Font(null, Font.BOLD, 20);
  42.  
    Font othorTextFont = new Font(null, Font.BOLD, 18);
  43.  
    try { // 寬度 高度
  44.  
    BufferedImage bimage = new BufferedImage(width, height,
  45.  
    BufferedImage.TYPE_INT_RGB);
  46.  
    Graphics2D g = bimage.createGraphics();
  47.  
    g.setColor(bgcolor); // 背景色
  48.  
    g.fillRect( 0, 0, width, height); // 畫一個矩形
  49.  
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
  50.  
    RenderingHints.VALUE_ANTIALIAS_ON); // 去除鋸齒(當設置的字體過大的時候,會出現鋸齒)
  51.  
     
  52.  
    g.setColor(Color.RED);
  53.  
    g.fillRect( 0, 0, 8, height);
  54.  
    g.fillRect( 0, 0, width, 8);
  55.  
    g.fillRect( 0, height - 8, width, height);
  56.  
    g.fillRect(width - 8, 0, width, height);
  57.  
     
  58.  
    g.setColor(fontcolor); // 字的顏色
  59.  
    g.setFont(doctorNameFont); // 字體字形字號
  60.  
    FontMetrics fm = FontDesignMetrics.getMetrics(doctorNameFont);
  61.  
    int font1_Hight = fm.getHeight();
  62.  
    int strWidth = fm.stringWidth(doctorName);
  63.  
    int y = 35;
  64.  
    int x = (width - strWidth) / 2;
  65.  
    g.drawString(doctorName, x, y); // 在指定坐標除添加文字
  66.  
     
  67.  
    g.setFont(othorTextFont); // 字體字形字號
  68.  
     
  69.  
    fm = FontDesignMetrics.getMetrics(othorTextFont);
  70.  
    int font2_Hight = fm.getHeight();
  71.  
    strWidth = fm.stringWidth(hospitalName);
  72.  
    x = (width - strWidth) / 2;
  73.  
    g.drawString(hospitalName, x, y + font1_Hight); // 在指定坐標除添加文字
  74.  
     
  75.  
    strWidth = fm.stringWidth(date);
  76.  
    x = (width - strWidth) / 2;
  77.  
    g.drawString(date, x, y + font1_Hight + font2_Hight); // 在指定坐標除添加文字
  78.  
     
  79.  
    g.dispose();
  80.  
    out = new FileOutputStream(jpgname); // 指定輸出文件
  81.  
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  82.  
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
  83.  
    param.setQuality( 50f, true);
  84.  
    encoder.encode(bimage, param); // 存盤
  85.  
    out.flush();
  86.  
    return true;
  87.  
    } catch (Exception e) {
  88.  
    return false;
  89.  
    } finally{
  90.  
    if(out!=null){
  91.  
    try {
  92.  
    out.close();
  93.  
    } catch (IOException e) {
  94.  
    }
  95.  
    }
  96.  
    }
  97.  
    }
  98.  
    public static void main(String[] args) {
  99.  
    createSignTextImg( "華佗", "在線醫院", "2018.01.01", "sign.jpg");
  100.  
    }
  101.  
    }

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

1. 制作PDF模板

目前PDF模板工具別無他物,只能使用偉大的Adobe公司提供的Adobe Acrobatpro DC軟件進行制作。如何使用該軟件這里就不多說了,如果在使用中遇到什么可以另外咨詢。

2. 制作一個如下圖的PDF模板,該模板是帶有PDF的表單域的

enter image description here

五、 如何生成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證書並進行存貯,相關分析見代碼注解

  1.  
    public class Extension {
  2.  
     
  3.  
    private String oid;
  4.  
     
  5.  
    private boolean critical;
  6.  
     
  7.  
    private byte[] value;
  8.  
     
  9.  
    public String getOid() {
  10.  
    return oid;
  11.  
    }
  12.  
     
  13.  
    public byte[] getValue() {
  14.  
    return value;
  15.  
    }
  16.  
    public boolean isCritical() {
  17.  
    return critical;
  18.  
    }
  19.  
    }
  20.  
     
  21.  
     
  22.  
    import java.io.ByteArrayInputStream;
  23.  
    import java.io.ByteArrayOutputStream;
  24.  
    import java.io.File;
  25.  
    import java.io.FileOutputStream;
  26.  
    import java.io.IOException;
  27.  
    import java.math.BigInteger;
  28.  
    import java.security.KeyPair;
  29.  
    import java.security.KeyPairGenerator;
  30.  
    import java.security.KeyStore;
  31.  
    import java.security.NoSuchAlgorithmException;
  32.  
    import java.security.PrivateKey;
  33.  
    import java.security.PublicKey;
  34.  
    import java.security.SecureRandom;
  35.  
    import java.security.cert.Certificate;
  36.  
    import java.security.cert.CertificateFactory;
  37.  
    import java.security.cert.X509Certificate;
  38.  
    import java.text.SimpleDateFormat;
  39.  
    import java.util.Calendar;
  40.  
    import java.util.Date;
  41.  
    import java.util.HashMap;
  42.  
    import java.util.List;
  43.  
    import java.util.Map;
  44.  
    import java.util.Random;
  45.  
     
  46.  
    import org.bouncycastle.asn1.ASN1ObjectIdentifier;
  47.  
    import org.bouncycastle.asn1.ASN1Primitive;
  48.  
    import org.bouncycastle.asn1.x500.X500Name;
  49.  
    import org.bouncycastle.asn1.x509.BasicConstraints;
  50.  
    import org.bouncycastle.asn1.x509.CRLDistPoint;
  51.  
    import org.bouncycastle.asn1.x509.DistributionPoint;
  52.  
    import org.bouncycastle.asn1.x509.DistributionPointName;
  53.  
    import org.bouncycastle.asn1.x509.GeneralName;
  54.  
    import org.bouncycastle.asn1.x509.GeneralNames;
  55.  
    import org.bouncycastle.asn1.x509.KeyUsage;
  56.  
    import org.bouncycastle.cert.X509CertificateHolder;
  57.  
    import org.bouncycastle.cert.X509v3CertificateBuilder;
  58.  
    import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
  59.  
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
  60.  
    import org.bouncycastle.operator.ContentSigner;
  61.  
    import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
  62.  
     
  63.  
    public class Pkcs {
  64.  
     
  65.  
    private static KeyPair getKey() throws NoSuchAlgorithmException {
  66.  
    KeyPairGenerator generator = KeyPairGenerator.getInstance( "RSA",
  67.  
    new BouncyCastleProvider());
  68.  
    generator.initialize( 1024);
  69.  
    // 證書中的密鑰 公鑰和私鑰
  70.  
    KeyPair keyPair = generator.generateKeyPair();
  71.  
    return keyPair;
  72.  
    }
  73.  
     
  74.  
    /**
  75.  
    * @param password
  76.  
    * 密碼
  77.  
    * @param issuerStr 頒發機構信息
  78.  
    *
  79.  
    * @param subjectStr 使用者信息
  80.  
    *
  81.  
    * @param certificateCRL 頒發地址
  82.  
    *
  83.  
    * @return
  84.  
    */
  85.  
    public static Map<String, byte[]> createCert(String password,
  86.  
    String issuerStr, String subjectStr, String certificateCRL) {
  87.  
    Map<String, byte[]> result = new HashMap<String, byte[]>();
  88.  
    ByteArrayOutputStream out = null;
  89.  
    try {
  90.  
    // 生成JKS證書
  91.  
    // KeyStore keyStore = KeyStore.getInstance("JKS");
  92.  
    // 標志生成PKCS12證書
  93.  
    KeyStore keyStore = KeyStore.getInstance( "PKCS12",
  94.  
    new BouncyCastleProvider());
  95.  
    keyStore.load( null, null);
  96.  
    KeyPair keyPair = getKey();
  97.  
    // issuer與 subject相同的證書就是CA證書
  98.  
    Certificate cert = generateCertificateV3(issuerStr, subjectStr,
  99.  
    keyPair, result, certificateCRL, null);
  100.  
    // cretkey隨便寫,標識別名
  101.  
    keyStore.setKeyEntry( "cretkey", keyPair.getPrivate(),
  102.  
    password.toCharArray(), new Certificate[] { cert });
  103.  
    out = new ByteArrayOutputStream();
  104.  
    cert.verify(keyPair.getPublic());
  105.  
    keyStore.store(out, password.toCharArray());
  106.  
    byte[] keyStoreData = out.toByteArray();
  107.  
    result.put( "keyStoreData", keyStoreData);
  108.  
    return result;
  109.  
    } catch (Exception e) {
  110.  
    e.printStackTrace();
  111.  
    } finally {
  112.  
    if (out != null) {
  113.  
    try {
  114.  
    out.close();
  115.  
    } catch (IOException e) {
  116.  
    }
  117.  
    }
  118.  
    }
  119.  
    return result;
  120.  
    }
  121.  
     
  122.  
    /**
  123.  
    * @param issuerStr
  124.  
    * @param subjectStr
  125.  
    * @param keyPair
  126.  
    * @param result
  127.  
    * @param certificateCRL
  128.  
    * @param extensions
  129.  
    * @return
  130.  
    */
  131.  
    public static Certificate generateCertificateV3(String issuerStr,
  132.  
    String subjectStr, KeyPair keyPair, Map<String, byte[]> result,
  133.  
    String certificateCRL, List<Extension> extensions) {
  134.  
    ByteArrayInputStream bout = null;
  135.  
    X509Certificate cert = null;
  136.  
    try {
  137.  
    PublicKey publicKey = keyPair.getPublic();
  138.  
    PrivateKey privateKey = keyPair.getPrivate();
  139.  
    Date notBefore = new Date();
  140.  
    Calendar rightNow = Calendar.getInstance();
  141.  
    rightNow.setTime(notBefore);
  142.  
    // 日期加1年
  143.  
    rightNow.add(Calendar.YEAR, 1);
  144.  
    Date notAfter = rightNow.getTime();
  145.  
    // 證書序列號
  146.  
    BigInteger serial = BigInteger.probablePrime( 256, new Random());
  147.  
    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
  148.  
    new X500Name(issuerStr), serial, notBefore, notAfter,
  149.  
    new X500Name(subjectStr), publicKey);
  150.  
    JcaContentSignerBuilder jBuilder = new JcaContentSignerBuilder(
  151.  
    "SHA1withRSA");
  152.  
    SecureRandom secureRandom = new SecureRandom();
  153.  
    jBuilder.setSecureRandom(secureRandom);
  154.  
    ContentSigner singer = jBuilder.setProvider(
  155.  
    new BouncyCastleProvider()).build(privateKey);
  156.  
    // 分發點
  157.  
    ASN1ObjectIdentifier cRLDistributionPoints = new ASN1ObjectIdentifier(
  158.  
    "2.5.29.31");
  159.  
    GeneralName generalName = new GeneralName(
  160.  
    GeneralName.uniformResourceIdentifier, certificateCRL);
  161.  
    GeneralNames seneralNames = new GeneralNames(generalName);
  162.  
    DistributionPointName distributionPoint = new DistributionPointName(
  163.  
    seneralNames);
  164.  
    DistributionPoint[] points = new DistributionPoint[1];
  165.  
    points[ 0] = new DistributionPoint(distributionPoint, null, null);
  166.  
    CRLDistPoint cRLDistPoint = new CRLDistPoint(points);
  167.  
    builder.addExtension(cRLDistributionPoints, true, cRLDistPoint);
  168.  
    // 用途
  169.  
    ASN1ObjectIdentifier keyUsage = new ASN1ObjectIdentifier(
  170.  
    "2.5.29.15");
  171.  
    // | KeyUsage.nonRepudiation | KeyUsage.keyCertSign
  172.  
    builder.addExtension(keyUsage, true, new KeyUsage(
  173.  
    KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
  174.  
    // 基本限制 X509Extension.java
  175.  
    ASN1ObjectIdentifier basicConstraints = new ASN1ObjectIdentifier(
  176.  
    "2.5.29.19");
  177.  
    builder.addExtension(basicConstraints, true, new BasicConstraints(
  178.  
    true));
  179.  
    // privKey:使用自己的私鑰進行簽名,CA證書
  180.  
    if (extensions != null)
  181.  
    for (Extension ext : extensions) {
  182.  
    builder.addExtension(
  183.  
    new ASN1ObjectIdentifier(ext.getOid()),
  184.  
    ext.isCritical(),
  185.  
    ASN1Primitive.fromByteArray(ext.getValue()));
  186.  
    }
  187.  
    X509CertificateHolder holder = builder.build(singer);
  188.  
    CertificateFactory cf = CertificateFactory.getInstance( "X.509");
  189.  
    bout = new ByteArrayInputStream(holder.toASN1Structure()
  190.  
    .getEncoded());
  191.  
    cert = (X509Certificate) cf.generateCertificate(bout);
  192.  
    byte[] certBuf = holder.getEncoded();
  193.  
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  194.  
    // 證書數據
  195.  
    result.put( "certificateData", certBuf);
  196.  
    //公鑰
  197.  
    result.put( "publicKey", publicKey.getEncoded());
  198.  
    //私鑰
  199.  
    result.put( "privateKey", privateKey.getEncoded());
  200.  
    //證書有效開始時間
  201.  
    result.put( "notBefore", format.format(notBefore).getBytes("utf-8"));
  202.  
    //證書有效結束時間
  203.  
    result.put( "notAfter", format.format(notAfter).getBytes("utf-8"));
  204.  
    } catch (Exception e) {
  205.  
    e.printStackTrace();
  206.  
    } finally {
  207.  
    if (bout != null) {
  208.  
    try {
  209.  
    bout.close();
  210.  
    } catch (IOException e) {
  211.  
    }
  212.  
    }
  213.  
    }
  214.  
    return cert;
  215.  
    }
  216.  
     
  217.  
    public static void main(String[] args) throws Exception{
  218.  
    // CN: 名字與姓氏 OU : 組織單位名稱
  219.  
    // O :組織名稱 L : 城市或區域名稱 E : 電子郵件
  220.  
    // ST: 州或省份名稱 C: 單位的兩字母國家代碼
  221.  
    String issuerStr = "CN=在線醫院,OU=gitbook研發部,O=gitbook有限公司,C=CN,E=gitbook@sina.com,L=北京,ST=北京";
  222.  
    String subjectStr = "CN=huangjinjin,OU=gitbook研發部,O=gitbook有限公司,C=CN,E=huangjinjin@sina.com,L=北京,ST=北京";
  223.  
    String certificateCRL = "https://gitbook.cn";
  224.  
    Map<String, byte[]> result = createCert("123456", issuerStr, subjectStr, certificateCRL);
  225.  
     
  226.  
    FileOutputStream outPutStream = new FileOutputStream("c:/keystore.p12"); // ca.jks
  227.  
    outPutStream.write(result.get( "keyStoreData"));
  228.  
    outPutStream.close();
  229.  
    FileOutputStream fos = new FileOutputStream(new File("c:/keystore.cer"));
  230.  
    fos.write(result.get( "certificateData"));
  231.  
    fos.flush();
  232.  
    fos.close();
  233.  
    }
  234.  
    }

六、 如何生成一個高清晰的簽章

1. 由PDF模板生成一個PDF文件,見代碼注解

  1.  
    import java.io.FileOutputStream;
  2.  
    import java.io.IOException;
  3.  
    import java.io.OutputStream;
  4.  
    import java.util.ArrayList;
  5.  
    import java.util.HashMap;
  6.  
    import java.util.Iterator;
  7.  
    import java.util.List;
  8.  
    import java.util.Map;
  9.  
    import com.itextpdf.text.DocumentException;
  10.  
    import com.itextpdf.text.pdf.AcroFields;
  11.  
    import com.itextpdf.text.pdf.AcroFields.Item;
  12.  
    import com.itextpdf.text.pdf.BaseFont;
  13.  
    import com.itextpdf.text.pdf.PdfReader;
  14.  
    import com.itextpdf.text.pdf.PdfStamper;
  15.  
     
  16.  
    public class PDFUtils {
  17.  
     
  18.  
     
  19.  
    /**
  20.  
    * @param fields
  21.  
    * @param data
  22.  
    * @throws IOException
  23.  
    * @throws DocumentException
  24.  
    */
  25.  
    private static void fillData(AcroFields fields, Map<String, String> data) throws IOException, DocumentException {
  26.  
    List< String> keys = new ArrayList<String>();
  27.  
    Map<String, Item> formFields = fields.getFields();
  28.  
    for (String key : data.keySet()) {
  29.  
    if(formFields.containsKey(key)){
  30.  
    String value = data.get(key);
  31.  
    fields.setField(key, value); // 為字段賦值,注意字段名稱是區分大小寫的
  32.  
    keys.add(key);
  33.  
    }
  34.  
    }
  35.  
    Iterator< String> itemsKey = formFields.keySet().iterator();
  36.  
    while(itemsKey.hasNext()){
  37.  
    String itemKey = itemsKey.next();
  38.  
    if(!keys.contains(itemKey)){
  39.  
    fields.setField(itemKey, " ");
  40.  
    }
  41.  
    }
  42.  
    }
  43.  
     
  44.  
    /**
  45.  
    * @param templatePdfPath
  46.  
    * 模板pdf路徑
  47.  
    * @param generatePdfPath
  48.  
    * 生成pdf路徑
  49.  
    * @param data
  50.  
    * 數據
  51.  
    */
  52.  
    public static String generatePDF(String templatePdfPath, String generatePdfPath, Map<String, String> data) {
  53.  
    OutputStream fos = null;
  54.  
    ByteArrayOutputStream bos = null;
  55.  
    try {
  56.  
    PdfReader reader = new PdfReader(templatePdfPath);
  57.  
    bos = new ByteArrayOutputStream();
  58.  
    /* 將要生成的目標PDF文件名稱 */
  59.  
    PdfStamper ps = new PdfStamper(reader, bos);
  60.  
    /* 使用中文字體 */
  61.  
    BaseFont bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
  62.  
    ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
  63.  
    fontList.add(bf);
  64.  
    /* 取出報表模板中的所有字段 */
  65.  
    AcroFields fields = ps.getAcroFields();
  66.  
    fields.setSubstitutionFonts(fontList);
  67.  
    fillData(fields, data);
  68.  
    /* 必須要調用這個,否則文檔不會生成的 如果為false那么生成的PDF文件還能編輯,一定要設為true*/
  69.  
    ps.setFormFlattening( true);
  70.  
    ps.close();
  71.  
    fos = new FileOutputStream(generatePdfPath);
  72.  
    fos.write(bos.toByteArray());
  73.  
    fos.flush();
  74.  
    return generatePdfPath;
  75.  
    } catch (Exception e) {
  76.  
    e.printStackTrace();
  77.  
    } finally {
  78.  
    if (fos != null) {
  79.  
    try {
  80.  
    fos.close();
  81.  
    } catch (IOException e) {
  82.  
    e.printStackTrace();
  83.  
    }
  84.  
    }
  85.  
    if (bos != null) {
  86.  
    try {
  87.  
    bos.close();
  88.  
    } catch (IOException e) {
  89.  
    e.printStackTrace();
  90.  
    }
  91.  
    }
  92.  
    }
  93.  
    return null;
  94.  
    }
  95.  
     
  96.  
    public static void main(String[] args) {
  97.  
    Map<String, String> data = new HashMap<String, String>();
  98.  
    //key為pdf模板的form表單的名字,value為需要填充的值
  99.  
    data.put( "title", "在線醫院");
  100.  
    data.put( "case", "123456789");
  101.  
    data.put( "date", "2018.12.07");
  102.  
    data.put( "name", "gitbook");
  103.  
    data.put( "sex", "男");
  104.  
    data.put( "age", "29");
  105.  
    data.put( "phone", "13711645814");
  106.  
    data.put( "office", "內科");
  107.  
    data.put( "cert", "身癢找打");
  108.  
    data.put( "drug", "1、奧美拉唑腸溶膠囊 0.25g10粒×2板 ");
  109.  
    data.put( "dose", "×2盒");
  110.  
    data.put( "cons", "用法用量:口服 一日兩次 一次2粒");
  111.  
    data.put( "tips", "溫馨提示");
  112.  
    data.put( "desc", "盡量呆在通風較好的地方,保持空氣流通,有利於病情康復。盡量呆在通風較好的地方");
  113.  
    generatePDF( "C:\\Users\\zhilin\\Desktop\\chat\\tpl.pdf",
  114.  
    "C:\\Users\\zhilin\\Desktop\\chat\\filled.pdf", data );
  115.  
    }
  116.  
    }

enter image description here

2. 對PDF文件進行簽章

經過過上面的代碼可以生成一個名為sign.jpg的簽章圖片,生成一個keystore.p12的證書文件,還有一個已經通過模板填充了表單的名為filled.pdf的pdf文件。下面就可通過以上材料生成一個簽名的PDF文件。

  1.  
    import java.io.File;
  2.  
    import java.io.FileInputStream;
  3.  
    import java.io.FileOutputStream;
  4.  
    import java.io.IOException;
  5.  
    import java.security.KeyStore;
  6.  
    import java.security.PrivateKey;
  7.  
    import java.security.Security;
  8.  
    import java.security.cert.Certificate;
  9.  
    import java.util.UUID;
  10.  
     
  11.  
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
  12.  
     
  13.  
    import com.itextpdf.text.Image;
  14.  
    import com.itextpdf.text.Rectangle;
  15.  
    import com.itextpdf.text.pdf.PdfReader;
  16.  
    import com.itextpdf.text.pdf.PdfSignatureAppearance;
  17.  
    import com.itextpdf.text.pdf.PdfSignatureAppearance.RenderingMode;
  18.  
    import com.itextpdf.text.pdf.PdfStamper;
  19.  
    import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  20.  
    import com.itextpdf.text.pdf.security.DigestAlgorithms;
  21.  
    import com.itextpdf.text.pdf.security.ExternalDigest;
  22.  
    import com.itextpdf.text.pdf.security.ExternalSignature;
  23.  
    import com.itextpdf.text.pdf.security.MakeSignature;
  24.  
    import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  25.  
    import com.itextpdf.text.pdf.security.PrivateKeySignature;
  26.  
     
  27.  
     
  28.  
    public class SignPdf {
  29.  
    /**
  30.  
    * @param password
  31.  
    * 秘鑰密碼
  32.  
    * @param keyStorePath
  33.  
    * 秘鑰文件路徑
  34.  
    * @param signPdfSrc
  35.  
    * 簽名的PDF文件
  36.  
    * @param signImage
  37.  
    * 簽名圖片文件
  38.  
    * @param x
  39.  
    * x坐標
  40.  
    * @param y
  41.  
    * y坐標
  42.  
    * @return
  43.  
    */
  44.  
    public static byte[] sign(String password, String keyStorePath, String signPdfSrc, String signImage,
  45.  
    float x, float y) {
  46.  
    File signPdfSrcFile = new File(signPdfSrc);
  47.  
    PdfReader reader = null;
  48.  
    ByteArrayOutputStream signPDFData = null;
  49.  
    PdfStamper stp = null;
  50.  
    FileInputStream fos = null;
  51.  
    try {
  52.  
    BouncyCastleProvider provider = new BouncyCastleProvider();
  53.  
    Security.addProvider(provider);
  54.  
    KeyStore ks = KeyStore.getInstance( "PKCS12", new BouncyCastleProvider());
  55.  
    fos = new FileInputStream(keyStorePath);
  56.  
    // 私鑰密碼 為Pkcs生成證書是的私鑰密碼 123456
  57.  
    ks.load(fos, password.toCharArray());
  58.  
    String alias = (String) ks.aliases().nextElement();
  59.  
    PrivateKey key = (PrivateKey) ks.getKey(alias, password.toCharArray());
  60.  
    Certificate[] chain = ks.getCertificateChain(alias);
  61.  
    reader = new PdfReader(signPdfSrc);
  62.  
    signPDFData = new ByteArrayOutputStream();
  63.  
    // 臨時pdf文件
  64.  
    File temp = new File(signPdfSrcFile.getParent(), System.currentTimeMillis() + ".pdf");
  65.  
    stp = PdfStamper.createSignature(reader, signPDFData, '\0', temp, true);
  66.  
    stp.setFullCompression();
  67.  
    PdfSignatureAppearance sap = stp.getSignatureAppearance();
  68.  
    sap.setReason( "數字簽名,不可改變");
  69.  
    // 使用png格式透明圖片
  70.  
    Image image = Image.getInstance(signImage);
  71.  
    sap.setImageScale( 0);
  72.  
    sap.setSignatureGraphic(image);
  73.  
    sap.setRenderingMode(RenderingMode.GRAPHIC);
  74.  
    // 是對應x軸和y軸坐標
  75.  
    sap.setVisibleSignature( new Rectangle(x, y, x + 185, y + 68), 1,
  76.  
    UUID.randomUUID().toString().replaceAll( "-", ""));
  77.  
    stp.getWriter().setCompressionLevel( 5);
  78.  
    ExternalDigest digest = new BouncyCastleDigest();
  79.  
    ExternalSignature signature = new PrivateKeySignature(key, DigestAlgorithms.SHA512, provider.getName());
  80.  
    MakeSignature.signDetached(sap, digest, signature, chain, null, null, null, 0, CryptoStandard.CADES);
  81.  
    stp.close();
  82.  
    reader.close();
  83.  
    return signPDFData.toByteArray();
  84.  
    } catch (Exception e) {
  85.  
    e.printStackTrace();
  86.  
    } finally {
  87.  
     
  88.  
    if (signPDFData != null) {
  89.  
    try {
  90.  
    signPDFData.close();
  91.  
    } catch (IOException e) {
  92.  
    }
  93.  
    }
  94.  
     
  95.  
    if (fos != null) {
  96.  
    try {
  97.  
    fos.close();
  98.  
    } catch (IOException e) {
  99.  
    }
  100.  
    }
  101.  
    }
  102.  
    return null;
  103.  
    }
  104.  
     
  105.  
    public static void main(String[] args) throws Exception {
  106.  
    byte[] fileData = sign("123456", "C:\\Users\\zhilin\\Desktop\\chat\\keystore.p12", //
  107.  
    "C:\\Users\\zhilin\\Desktop\\chat\\filled.pdf",//
  108.  
    "C:\\Users\\zhilin\\Desktop\\chat\\sign.jpg", 100, 290);
  109.  
    FileOutputStream f = new FileOutputStream(new File("C:\\Users\\zhilin\\Desktop\\chat\\signed.pdf"));
  110.  
    f.write(fileData);
  111.  
    f.close();
  112.  
    }
  113.  
    }

enter image description here

3. 高清簽章

高清簽章是通過iText的繪制功能來完成。主要直接在PDF文件中繪制簽章,代碼實現如下:

  1.  
    import java.io.File;
  2.  
    import java.io.FileInputStream;
  3.  
    import java.io.FileOutputStream;
  4.  
    import java.io.IOException;
  5.  
    import java.security.KeyStore;
  6.  
    import java.security.PrivateKey;
  7.  
    import java.security.Security;
  8.  
    import java.security.cert.Certificate;
  9.  
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
  10.  
     
  11.  
    import com.itextpdf.awt.AsianFontMapper;
  12.  
    import com.itextpdf.text.BaseColor;
  13.  
    import com.itextpdf.text.Element;
  14.  
    import com.itextpdf.text.Font;
  15.  
    import com.itextpdf.text.Paragraph;
  16.  
    import com.itextpdf.text.Rectangle;
  17.  
    import com.itextpdf.text.pdf.BaseFont;
  18.  
    import com.itextpdf.text.pdf.ColumnText;
  19.  
    import com.itextpdf.text.pdf.PdfReader;
  20.  
    import com.itextpdf.text.pdf.PdfSignatureAppearance;
  21.  
    import com.itextpdf.text.pdf.PdfStamper;
  22.  
    import com.itextpdf.text.pdf.PdfStream;
  23.  
    import com.itextpdf.text.pdf.PdfTemplate;
  24.  
    import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  25.  
    import com.itextpdf.text.pdf.security.DigestAlgorithms;
  26.  
    import com.itextpdf.text.pdf.security.ExternalDigest;
  27.  
    import com.itextpdf.text.pdf.security.ExternalSignature;
  28.  
    import com.itextpdf.text.pdf.security.MakeSignature;
  29.  
    import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  30.  
    import com.itextpdf.text.pdf.security.PrivateKeySignature;
  31.  
     
  32.  
     
  33.  
    public class SignHighPdf {
  34.  
     
  35.  
    /**
  36.  
    * @param password
  37.  
    * 秘鑰密碼
  38.  
    * @param keyStorePath
  39.  
    * 秘鑰文件路徑
  40.  
    * @param signPdfSrc
  41.  
    * 簽名的PDF文件
  42.  
    * @param x
  43.  
    *
  44.  
    * @param y
  45.  
    * @return
  46.  
    */
  47.  
    public static byte[] sign(String password, String keyStorePath, String signPdfSrc,
  48.  
    float x, float y,
  49.  
    String signText) {
  50.  
    File signPdfSrcFile = new File(signPdfSrc);
  51.  
    PdfReader reader = null;
  52.  
    ByteArrayOutputStream signPDFData = null;
  53.  
    PdfStamper stp = null;
  54.  
    FileInputStream fos = null;
  55.  
    try {
  56.  
    BouncyCastleProvider provider = new BouncyCastleProvider();
  57.  
    Security.addProvider(provider);
  58.  
    KeyStore ks = KeyStore.getInstance( "PKCS12", new BouncyCastleProvider());
  59.  
    fos = new FileInputStream(keyStorePath);
  60.  
    ks.load(fos, password.toCharArray()); // 私鑰密碼
  61.  
    String alias = (String) ks.aliases().nextElement();
  62.  
    PrivateKey key = (PrivateKey) ks.getKey(alias, password.toCharArray());
  63.  
    Certificate[] chain = ks.getCertificateChain(alias);
  64.  
    reader = new PdfReader(signPdfSrc);
  65.  
    signPDFData = new ByteArrayOutputStream();
  66.  
    // 臨時pdf文件
  67.  
    File temp = new File(signPdfSrcFile.getParent(), System.currentTimeMillis() + ".pdf");
  68.  
    stp = PdfStamper.createSignature(reader, signPDFData, '\0', temp, true);
  69.  
    PdfSignatureAppearance sap = stp.getSignatureAppearance();
  70.  
    sap.setReason( "數字簽名,不可改變");
  71.  
    // 是對應x軸和y軸坐標
  72.  
    sap.setVisibleSignature( new Rectangle(x, y, x + 150, y + 65), 1,
  73.  
    "sr"+String.valueOf(System.nanoTime()));
  74.  
    /////////////////layer 0 Creating the appearance for layer 0
  75.  
    PdfTemplate n0 = sap.getLayer( 0);
  76.  
    n0.reset();
  77.  
    float lx = n0.getBoundingBox().getLeft();
  78.  
    float by = n0.getBoundingBox().getBottom();
  79.  
    float width = n0.getBoundingBox().getWidth();
  80.  
    float height = n0.getBoundingBox().getHeight();
  81.  
    n0.setRGBColorFill( 255, 0, 0);
  82.  
    n0.rectangle(lx, by, 5, height);
  83.  
    n0.rectangle(lx, by, width, 5);
  84.  
    n0.rectangle(lx, by+height- 5, width, 5);
  85.  
    n0.rectangle(lx+width- 5, by, 5, height);
  86.  
    n0.fill();
  87.  
    ///////////////////////layer 2
  88.  
    PdfTemplate n2 = sap.getLayer( 2);
  89.  
    n2.setCharacterSpacing( 0.0f);
  90.  
    ColumnText ct = new ColumnText(n2);
  91.  
    ct.setSimpleColumn(n2.getBoundingBox());
  92.  
    n2.setRGBColorFill( 255, 0, 0);
  93.  
    //做一個占位的動作
  94.  
    Paragraph p1 = new Paragraph(" ");
  95.  
    BaseFont bf = BaseFont.createFont(AsianFontMapper.ChineseSimplifiedFont, AsianFontMapper.ChineseSimplifiedEncoding_H,
  96.  
    BaseFont.NOT_EMBEDDED);
  97.  
    Font font1 = new Font(bf, 5, Font.BOLD, BaseColor.RED);
  98.  
    Font font2 = new Font(bf, 13, Font.BOLD, BaseColor.RED);
  99.  
    p1.setFont(font1);
  100.  
    ct.addElement(p1);
  101.  
    Paragraph p = new Paragraph(signText);
  102.  
    p.setAlignment(Element.ALIGN_CENTER);
  103.  
    p.setFont(font2);
  104.  
    ct.addElement(p);
  105.  
    ct.go();
  106.  
    stp.getWriter().setCompressionLevel(PdfStream.BEST_COMPRESSION);
  107.  
    ExternalDigest digest = new BouncyCastleDigest();
  108.  
    ExternalSignature signature = new PrivateKeySignature(key, DigestAlgorithms.SHA512, provider.getName());
  109.  
    MakeSignature.signDetached(sap, digest, signature, chain, null, null, null, 0, CryptoStandard.CADES);
  110.  
    stp.close();
  111.  
    reader.close();
  112.  
    return signPDFData.toByteArray();
  113.  
    } catch (Exception e) {
  114.  
    e.printStackTrace();
  115.  
    } finally {
  116.  
    if (signPDFData != null) {
  117.  
    try {
  118.  
    signPDFData.close();
  119.  
    } catch (IOException e) {
  120.  
    }
  121.  
    }
  122.  
    if (fos != null) {
  123.  
    try {
  124.  
    fos.close();
  125.  
    } catch (IOException e) {
  126.  
    }
  127.  
    }
  128.  
    }
  129.  
    return null;
  130.  
    }
  131.  
     
  132.  
    public static void main(String[] args) throws Exception {
  133.  
    //對已經簽章的signed.pdf文件再次簽章,這次是高清簽章
  134.  
    byte[] fileData = sign("123456", "C:\\Users\\zhilin\\Desktop\\chat\\keystore.p12",//
  135.  
    "C:\\Users\\zhilin\\Desktop\\chat\\signed.pdf", 350, 290, "華佗\n2017-12-20");
  136.  
    FileOutputStream f = new FileOutputStream(new File("C:\\Users\\zhilin\\Desktop\\chat\\signed2.pdf"));
  137.  
    f.write(fileData);
  138.  
    f.close();
  139.  
    }
  140.  
     
  141.  
    }

可以分析下下面這兩個簽章的區別,發現左邊的簽章很模糊,右邊的特別清晰。

enter image description here

七、 如何進行多次PDF簽名

生成多個簽章重點代碼,已在SignPdf.java類進行標注說明;如果想進行多次簽名,就只需對已經進行過簽名的PDF文件再次調用sign方法進行再次簽名即可(第六點有張圖片就有兩個簽章,這就是多次簽名的結果)。

PdfStamper.createSignature(reader, signPDFData, '\0', temp, true); 

八、 總結

分享中sign.jpg文件的白色背景需要做透明化處理才能達到正確電子簽章的效果(不覆蓋PDF文件中已有的內容,真實的電子簽章也是這樣做的),大家回去可以思考下怎么把一個jpg文件白色背景透明化(高清簽章就已經實現透明化,可以試着把SignPdf.java和SignHighPdf.java簽章到有文字的PDF上面看看效果)。

大家見到的公司公章都是圓形的;這個也是可以做到的大家想想怎樣生成一個圓形的圖片簽章;然后進行電子簽名。這里主要是講解代碼實現,所有代碼非常多。大家回去好好研讀代碼。真正的電子簽名需要通過CA認證公司來完成,我這里只是提供參考方案讓大家學習。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM