Java PDF數字簽名(一)
阿新 • • 發佈:2018-12-17
這篇文章將介紹如何在Java應用程式中給PDF文件新增數字簽名。
使用工具:
Free Spire.PDF for JAVA
步驟:
1.建立一個Java project,並新增一個class SignPDF.JAVA
2.下載Free Spire.PDF for JAVA包並解壓縮,然後從lib資料夾下,匯入Spire.Pdf.jar包和Spire.Common.jar包到程式中:
3.SignPDF.JAVA程式碼如下:
import com.spire.ms.System.DateTime; import com.spire.pdf.FileFormat; import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.graphics.PdfImage; import com.spire.pdf.security.GraphicMode; import com.spire.pdf.security.PdfCertificate; import com.spire.pdf.security.PdfCertificationFlags; import com.spire.pdf.security.PdfSignature; import java.awt.geom.Rectangle2D; public class SignPDF { public static void main(String[] args){ //載入PDF文件並獲取第一頁 PdfDocument doc = new PdfDocument(); doc.loadFromFile("Input.pdf"); PdfPageBase page = doc.getPages().get(0); Rectangle2D.Float rec = new Rectangle2D.Float(100, 450, 310, 100); //Load pfx檔案 PdfCertificate certificate = new PdfCertificate("gary.pfx", "e-iceblue"); //新增數字簽名 PdfSignature signature = new PdfSignature(doc, page, certificate, "signature1", rec); //設定簽名詳細資訊 PdfImage img = PdfImage.fromFile("E-iceblueLogo.png"); signature.setSignImageSource(img); signature.setNameLabel("Signer: "); signature.setName("Gary"); signature.setContactInfoLabel("ContactInfo: "); signature.setContactInfo("
[email protected]"); signature.setDateLabel("Date: "); signature.setDate(DateTime.getToday()); signature.setLocationInfoLabel("Location: "); signature.setLocationInfo("Chengdu"); signature.setReasonLabel("Reason: "); signature.setReason("The certificate of this document."); signature.setDistinguishedNameLabel("DL: "); signature.setDistinguishedName(signature.getCertificate().get_IssuerName().getName()); signature.setGraphicMode(GraphicMode.Sign_Image_And_Sign_Detail); signature.setDocumentPermissions(PdfCertificationFlags.Allow_Form_Fill); signature.setCertificated(true); //儲存檔案 doc.saveToFile("SimpleSign.pdf", FileFormat.PDF); } }
結果檔案: