我已經使用itextsharp創建了一個PDF文件,它工作正常。我創建了一個Activex控件來在客戶端使用USB令牌對PDF文件進行數字簽名。客戶端使用其USB令牌對PDF文件進行數字簽名,並將PDF文件存儲到服務器上,其他授權人員可以下載該文件。 Activex只需要一個PDF文件並進行數字簽名並臨時存儲PDF文件,然後使用PdfEncodings類的itextsharp庫將該PDF文件作爲base64字符串返回。 要使用Activex對象,我創建了兩個asp.net隱藏字段,一個用於未簽名,另一個用於已簽名的PDF。創建PDF文件後,我將其轉換爲base64字符串,然後將其分配給asp.net隱藏字段,然後調用javascript函數使用Activex控件進行簽名,然後將該值分配給另一個asp.net隱藏字段,然後將該值並使其可下載,但是,當PDF下載時,它表示PDF已損壞。我已經在臨時文件夾中檢查了正確的PDF文件。如何製作可下載的正確pdf文件並在asp.net中的itextsharp中進行驗證?
代碼數字在ActiveX控件從瀏覽器下載PDF簽署PDF
PdfReader pdfReader = new PdfReader(PdfEncodings.ConvertToBytes(unsignedPDF, null));
string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf";
FileStream signedPdf = new FileStream(fileName, FileMode.Create);
PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0');
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, X509SelectionFlag.SingleSelection);
if (sel.Count > 0)
{
X509Certificate2 cert = sel[0];
Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) };
IExternalSignature externalSignature = new X509Certificate2Signature(cert, "SHA-1");
PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
signatureAppearance.Reason = "I declare this document is legal";
signatureAppearance.Location = "Delhi";
signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 150), pdfReader.NumberOfPages, "Signature");
signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
return PdfEncodings.ConvertToString(File.ReadAllBytes(fileName), null);
}
else
{
return "ERROR";
}
代碼:
byte[] pdfByte = PdfEncodings.ConvertToBytes(signed.Value, null);
Response.Clear();
MemoryStream ms = new MemoryStream(pdfByte);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=labtest.pdf");
Response.Buffer = true;
ms.WriteTo(Response.OutputStream);
Response.End();
「PdfEncodings」類不是用於將任意二進制數據(並且完成的PDF是二進制數據)轉換爲某種字符串格式,而是用於其中一種或另一種編碼中的字符數據。應用於二進制數據,這個過程會引入錯誤。您應該使用一些base64編碼器/解碼器。 – mkl
謝謝,我解決了它。你是對的。 Pdfencodings不是那個意思,我只是使用convert.tobase64string和convert.frombase64string,它的工作。 – vishgarg