文檔首頁(yè)>>E-iceblue中文文檔>>使用以下功能檢測(cè)已簽名的 PDF 是否被修改過(guò)
使用以下功能檢測(cè)已簽名的 PDF 是否被修改過(guò)
在對(duì) PDF 文檔進(jìn)行數(shù)字簽名后,該 PDF 已被鎖定以防止更改或允許檢測(cè)更改。本文將介紹如何使用 Spire.PDF 檢測(cè)已簽名的 PDF 是否被修改。
為了測(cè)試此功能,我們創(chuàng)建了一個(gè) PDF 文檔,并使用數(shù)字簽名對(duì) PDF 進(jìn)行了簽名,然后將示例文檔中的 "PDF "改為 "Pdf",并保存為另一個(gè)文件。下面是修改后的 PDF 文檔:
代碼片段
步驟 1:創(chuàng)建 Window Forms 應(yīng)用程序并設(shè)計(jì) form1 如下。
第 2 步:雙擊 'Load' 按鈕,編寫(xiě)以下代碼,以便從文件夾中查找 PDF 文件,并在 textBox1.Text 中返回文件路徑。
private void btnLoad_Click(object sender, EventArgs e) { OpenFileDialog fileName = new OpenFileDialog(); fileName.InitialDirectory = Application.StartupPath; fileName.Filter = "All files|*.pdf"; if (fileName.ShowDialog() == DialogResult.OK) { string Path = fileName.FileName.ToString(); textBox1.Text = Path; } }第3步:在 'Check'.按鈕上輸入以下代碼。在這一部分,我們獲取PDF文檔中的所有簽名,然后調(diào)用PdfSignature.VerifyDocModified()方法檢測(cè)文檔是否在簽名后被修改。如果被修改則返回true,否則返回false。
private void btnCheck_Click(object sender, EventArgs e) { //get signatures from PDF List signatures = new List(); using (PdfDocument pdf = new PdfDocument(textBox1.Text)) { PdfFormWidget form = pdf.Form as PdfFormWidget; for (int i = 0; i < form.FieldsWidget.Count; i++) { PdfSignatureFieldWidget field = form.FieldsWidget[i] as PdfSignatureFieldWidget; if (field != null && field.Signature != null) { PdfSignature signature = field.Signature; signatures.Add(signature); } } PdfSignature signatureOne = signatures[0]; //detect if the PDF was modified bool modified = signatureOne.VerifyDocModified(); if (modified == true) { MessageBox.Show("The document was modified"); } } }運(yùn)行程序并加載修改后的文檔,點(diǎn)擊 'Check'按鈕后會(huì)得到以下輸出結(jié)果。
完整代碼:
private void btnLoad_Click(object sender, EventArgs e) { OpenFileDialog fileName = new OpenFileDialog(); fileName.InitialDirectory = Application.StartupPath; fileName.Filter = "All files|*.pdf"; if (fileName.ShowDialog() == DialogResult.OK) { string Path = fileName.FileName.ToString(); textBox1.Text = Path; } } private void btnCheck_Click(object sender, EventArgs e) { //get signatures from PDF List signatures = new List(); using (PdfDocument pdf = new PdfDocument(textBox1.Text)) { PdfFormWidget form = pdf.Form as PdfFormWidget; for (int i = 0; i < form.FieldsWidget.Count; i++) { PdfSignatureFieldWidget field = form.FieldsWidget[i] as PdfSignatureFieldWidget; if (field != null && field.Signature != null) { PdfSignature signature = field.Signature; signatures.Add(signature); } } PdfSignature signatureOne = signatures[0]; //detect if the PDF was modified bool modified = signatureOne.VerifyDocModified(); if (modified == true) { MessageBox.Show("The document was modified"); } } }