/// <summary> /// string pfxFileFullPath = Global.Strings.pfxFileFullPath; /// @"C:\PROJECTS\VPrint2\ReceivingServiceLib.Common\PTF.pfx" /// string PTFLogoFileFullPath = Global.Strings.PTFLogoFileFullPath; /// @"C:\PROJECTS\VPrint2\ReceivingServiceLib.Common\Resources\PTFLogo.jpg" /// </summary> /// <param name="fileStream">ImageFileArray</param> /// <param name="barcode"></param> /// <param name="countryName">Spain</param> /// <param name="location">"Madrid, Spain"</param> /// <param name="retailerId"></param> /// <param name="voucherId"></param> /// <returns></returns> public string CreateSignPdf(Bitmap bitmap, string barcode, int retailerId, int voucherId, PdfCreationInfo creationInfo, PdfSignInfo signInfo) { PdfAManager manager = new PdfAManager(); var pdfFileName = Path.ChangeExtension(Path.GetTempFileName(), ".pdf"); var signedPdfFileName = Path.ChangeExtension(Path.GetTempFileName(), ".pdf"); try { manager.CreatePdf(pdfFileName, new Bitmap[] { bitmap }, creationInfo); manager.SignPdfFile(pdfFileName, signedPdfFileName, signInfo); return(signedPdfFileName); } finally { try { File.Delete(pdfFileName); } catch { } } }
public Action <TaskProcessOrganizer <string> .TaskItem> GetAction() { return(new Action <TaskProcessOrganizer <string> .TaskItem>((o) => { var fullFilePath = o.Item; Bitmap bmp = null; StateManager.VoucherItem item = (StateManager.VoucherItem)StateManager.Default.ProcessItem_Begin(true); try { var info = new FileInfo(fullFilePath); if (info.Exists && !info.IsReadOnly(TRIES)) { Global.IgnoreList.Add(fullFilePath); // ".tif" var ext = Path.GetExtension(info.FullName); if (ext.EqualNoCase(".pdf")) { var helper = new PDFFileHelper(); var finfo = helper.Run(info, item); fullFilePath = (finfo != null) ? finfo.FullName : ""; } bmp = ((Bitmap)Bitmap.FromFile(fullFilePath)); var useCrop = StateSaver.Default.Get <bool>(Strings.CROPIMAGE); if (useCrop) { bmp = bmp.Crop2(); } item.FileInfoList.Add(new FileInfo(fullFilePath)); // Scanned Image item.FullFileName = fullFilePath; StateManager.VoucherItem vitem = (StateManager.VoucherItem)item; #if DRAW_ON_VOUCHER bmp.DrawOnImage((gr) => { var str = string.Format("{0:dd-MM-yyyy hh:mm}", DateTime.Now); ///string user = Program.currentUser.ToString(); var an = StateSaver.Default.Get <AssemblyName>(Strings.VERSION); using (var font = new Font(FontFamily.GenericSansSerif, 10f, FontStyle.Regular)) { gr.DrawString(str, font, Brushes.Black, new PointF(10, 10)); gr.DrawString(an.Name, font, Brushes.Black, new PointF(10, 25)); gr.DrawString(an.Version.ToString(), font, Brushes.Black, new PointF(10, 40)); } }); #endif #if COVER_CCD var coverArea = StateSaver.Default.Get <Rectangle>(Strings.VOUCHERCOVERREGION); if (!coverArea.IsEmpty) { var size = StateSaver.Default.Get <int>(Strings.PIXELSIZE, 5); bmp.Pixellate(coverArea); } #endif string site; int location; if (!VPrinting.Common.CommonTools.ParseSiteCode(info.Name, out site, out location)) { throw new Exception("Wrong sitecode"); } var vinfo = ServiceDataAccess.Instance.FindVoucherTRSBySiteCode(site, location); if (vinfo == null || !vinfo.IsValid) { vinfo = ServiceDataAccess.Instance.FindVoucherPRBySiteCode(site, location); if (!vinfo.IsValid) { throw new Exception("Cannot find voucher by sitecode"); } } item.CountryID = vinfo.IsoId; vitem.RetailerID = vinfo.RetailerId; vitem.VoucherID = vinfo.VoucherId; vitem.Barcode = ""; vitem.SiteCode = string.Concat(site, location); if (item.CountryID == 0) { item.CountryID = MainForm.ms_DefaultCountryId; } #if SAVE_VOUCHER if (!ext.EqualNoCase(".tif")) { bmp.Save(fullFilePath, ImageFormat.Jpeg); } #endif if (item.Thumbnail == null) { item.Thumbnail = bmp.GetThumbnailImage(45, 45, () => false, IntPtr.Zero); } if (StateSaver.Default.Get <bool>(Strings.USE_VCOVER)) { using (WaitObject obj = new WaitObject(item.FileInfoList)) { var ptr = StateSaver.Default.Get <IntPtr>(Strings.VCOVER_FUNC); var time = StateSaver.Default.Get <TimeSpan>(Strings.VCOVER_TIMEOUT, TimeSpan.FromMinutes(10)); var dlg = ptr.GetDelegate <CallVCoverService_ReadDataDelegate>(); dlg.DynamicInvoke(obj); if (!obj.WaitOne(time)) { throw new ApplicationException("VCover timeout"); } if (obj.Err != null) { throw obj.Err; } } } var certificateSigning = StateSaver.Default.Get <bool>(Strings.CERTIFICATE_SIGNING_AVAILABLE); if (certificateSigning) { var crInfo = new PdfCreationInfo() { Title = string.Concat("Voucher ", vitem.VoucherID), Subject = string.Concat("Retailer ", vitem.RetailerID), Author = string.Concat("PTF ", StateSaver.Default.Get <string>(Strings.Certigicate_COUNTRY)), Creator = string.Concat("PTF ", StateSaver.Default.Get <string>(Strings.Certigicate_LOCATION)), }; var signInfo = new PdfSignInfo() { pfxFilePath = StateSaver.Default.Get <string>(Strings.COUNTRY_CERTIFICATE_PATH), pfxKeyPass = StateSaver.Default.Get <string>(Strings.COUNTRY_CERTIFICATE_PASS), DocPass = null, SignImagePath = StateSaver.Default.Get <string>(Strings.PTFLogoFileFullPath), ReasonForSigning = string.Concat("Signing electronic copy of voucher ", vitem.Barcode), Location = StateSaver.Default.Get <string>(Strings.Certigicate_LOCATION) }; var prtGetMetaData = StateSaver.Default.Get <IntPtr>(Strings.Certigicate_METADATA_FUNC); if (prtGetMetaData != IntPtr.Zero) { crInfo.MetaData = signInfo.MetaData = prtGetMetaData.GetDelegate <GetMetaDataDelegate>().DynamicInvoke(this, vinfo.IsoId, 0, vinfo.RetailerId).cast <ArrayList>(); var str = string.Format("{0:dd-MM-yyyy hh:mm}", DateTime.Now); var an = StateSaver.Default.Get <AssemblyName>(Strings.VERSION); crInfo.MetaData.Insert(0, new Tuple <string, string>("", "")); crInfo.MetaData.Insert(0, new Tuple <string, string>("Voucher number", vinfo.VoucherId.ToString())); crInfo.MetaData.Add(new Tuple <string, string>("", "")); crInfo.MetaData.Add(new Tuple <string, string>("Operator", Program.currentUser.Username)); crInfo.MetaData.Add(new Tuple <string, string>("App.name", an.Name)); crInfo.MetaData.Add(new Tuple <string, string>("App.version", an.Version.ToString())); crInfo.MetaData.Add(new Tuple <string, string>("Create at", str)); } var pdfFileName = pdfFileAccess.Instance.CreateSignPdf(bmp, vitem.Barcode, vitem.RetailerID, vitem.VoucherID, crInfo, signInfo); item.FileInfoList.Add(new FileInfo(pdfFileName)); // Signed Image } item.State = StateManager.eState.OK; item.Message = ""; StateManager.Default.CompleteItem(item); } } catch (Exception ex) { item.State = StateManager.eState.Err; item.Message = ex.Message; int count = StateManager.Default.SetItemWithErr(); DelegateHelper.PostShowItemsWithErrCallback(count); DelegateHelper.FireError(this, ex); } finally { bmp.DisposeSf(); DelegateHelper.PostItemScannedCallback(item); try { if (!item.IsSetup) { using (var mngr = new AsyncFormManager <RetailerForm>("Enter voucher details")) { mngr.Result = item; mngr.RunWait(); if (!item.IsSetup) { throw new ApplicationException("Cannot find barcode."); } item.State = StateManager.eState.OK; } } StateManager.Default.AddNewItem(item); } catch (Exception ex0) { item.State = StateManager.eState.Err; item.Message = ex0.Message; DelegateHelper.FireError(this, ex0); } } })); }
/// <summary> /// Read voucher/file from database /// </summary> /// <param name="fileId"></param> /// <param name="isVoucher"></param> /// <param name="signed"></param> /// <param name="startFrom"></param> /// <param name="s1"></param> /// <param name="s2"></param> /// <returns></returns> public byte[] SelectFileById(int fileId, bool isVoucher, bool signed, int startFrom, string s1, string s2) { //if (!Debugger.IsAttached) // Debugger.Launch(); const int READSIZE = 16384; using (var buffer = new CachedMemoryBuffer <int>(fileId)) { try { SecurityCheckThrow(s1, s2); RecordCallHistory("SelectFileById"); if (buffer.IsFirstRun) { if (signed) { if (!isVoucher) { throw new NotImplementedException("Signing for files not implemented yet."); } #region signed voucher //signed voucher var db = VoucherDataAccess.Instance; var vinfo = db.SelectVoucherInfo(fileId); var countryName = ISOs.ResourceManager.GetString(string.Concat('_', vinfo.isoId)); #warning NO_BLOBS_IN_SQL var fac2 = new ZipFileAccess(); var voucherDirectory = fac2.CreateDirectoryHerarchy(Global.Strings.VOCUHERSFOLDER, vinfo.isoId, vinfo.branch_id, vinfo.v_number); //byte[] data = VoucherDataAccess.Instance.SelectImageById(result2.Item1.vid, true); var file = voucherDirectory.GetFiles().FirstOrDefault(); if (file == null) { return(null); } byte[] data = file.ReadAllBytes(); //var data = db.SelectImageById(fileId, true); DirectoryInfo exportDirectory = null; FileInfo exportZipFile = null; DirectoryInfo operationDirectory = null; FileInfo operationZipFile = null; try { var uploadRootFolder = new DirectoryInfo(Global.Strings.UPLOADROOT); uploadRootFolder.EnsureDirectory(); exportDirectory = uploadRootFolder.Combine(vinfo.session_Id); exportDirectory.EnsureDirectory(); operationDirectory = uploadRootFolder.Combine(vinfo.session_Id + "_result"); operationDirectory.EnsureDirectory(); exportZipFile = uploadRootFolder.CombineFileName(vinfo.session_Id + ".zip"); operationZipFile = uploadRootFolder.CombineFileName(vinfo.session_Id + "result.zip"); File.WriteAllBytes(exportZipFile.FullName, data); var files = ZipFileAccess.Instance.ExtractFileZip(exportZipFile.FullName, exportDirectory.FullName); var imageFileToSing = files.Max((f, f1) => f.Length > f1.Length); PdfCreationInfo crInfo = new PdfCreationInfo() { Title = string.Concat("Voucher ", vinfo.v_number), Subject = string.Concat("Retailer ", vinfo.branch_id), Author = string.Concat("PTF ", countryName), Creator = string.Concat("PTF ", countryName), }; PdfSignInfo signInfo = new PdfSignInfo() { pfxFilePath = Global.Strings.pfxFileFullPath, pfxKeyPass = "", DocPass = null, SignImagePath = Global.Strings.PTFLogoFileFullPath, ReasonForSigning = string.Concat("Voucher ", vinfo.v_number), Location = "Madrid" }; using (var bmp = (Bitmap)Image.FromFile(imageFileToSing.FullName)) { var pdfFileName = pdfFileAccess.Instance.CreateSignPdf(bmp, "barcode", vinfo.branch_id, vinfo.v_number, crInfo, signInfo); var imageFileName = operationDirectory.CombineFileName(vinfo.session_Id + ".pdf").FullName; File.Move(pdfFileName, imageFileName); ZipFileAccess.Instance.CreateZip(operationZipFile.FullName, operationDirectory.FullName, "File created at: " + DateTime.Now); buffer.Buffer = operationZipFile.ReadAllBytes(); } } finally { exportDirectory.DeleteSafe(true); exportZipFile.DeleteSafe(); operationZipFile.DeleteSafe(); } #endregion } else { //voucher || file bool isProtected = false; byte[] buf = VoucherDataAccess.Instance.SelectVoucherById(fileId, isVoucher, out isProtected); if (isProtected) { var downloadRoot = new DirectoryInfo(Global.Strings.DOWNLOADROOT); downloadRoot.CreateIfNotExist(); var binInfo = downloadRoot.CombineFileName(string.Concat(fileId, ".bin")); binInfo.WriteAllBytes(buf); var zipInfo = downloadRoot.CombineFileName(string.Concat(fileId, ".zip")); binInfo.DecriptFile(zipInfo); buffer.Buffer = zipInfo.ReadAllBytes(); zipInfo.DeleteSafe(); binInfo.DeleteSafe(); } else { buffer.Buffer = buf; } } } byte[] arr = buffer.Get(startFrom, READSIZE); return(arr); } catch (Exception ex) { buffer.Remove(); throw new FaultException <MyApplicationFault>(new MyApplicationFault(), ex.Message); } } }
/// <summary> /// Signs a PDF document using iTextSharp library /// </summary> /// <param name="sourceDocument">The path of the source pdf document which is to be signed</param> /// <param name="destinationDocument">The path at which the signed pdf document should be generated</param> /// <param name="privateKeyStream">A Stream containing the private/public key in .pfx format which would be used to sign the document</param> /// <param name="pfxKeyPass">The password for the private key</param> /// <param name="reasonForSigning">String describing the reason for signing, would be embedded as part of the signature</param> /// <param name="location">Location where the document was signed, would be embedded as part of the signature</param> public void SignPdfFile(string sourceDocument, string destinationDocument, PdfSignInfo info) { using (var cpfxFile = new FileStream(info.pfxFilePath, FileMode.Open, FileAccess.Read)) { Pkcs12Store pk12 = new Pkcs12Store(cpfxFile, info.pfxKeyPass.ToCharArray()); string alias = null; foreach (string tAlias in pk12.Aliases) { if (pk12.IsKeyEntry(tAlias)) { alias = tAlias; break; } } var pk = pk12.GetKey(alias).Key; using (var reader = new PdfReader(sourceDocument)) using (var fout = new FileStream(destinationDocument, FileMode.Create, FileAccess.ReadWrite)) using (var stamper = PdfStamper.CreateSignature(reader, fout, '\0')) { if (info.DocPass != null) { stamper.SetEncryption(info.DocPass, info.DocPass, PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STRENGTH128BITS); } var img = new iTextSharp.text.Jpeg(new Uri(info.SignImagePath)); PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Image = img; appearance.Reason = info.ReasonForSigning; appearance.Location = info.Location; const float x = 20, y = 10; appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(x, y, x + img.Width, y + img.Width), 1, "Icsi-Vendor"); IExternalSignature es = new PrivateKeySignature(pk, "SHA-256"); MakeSignature.SignDetached(appearance, es, new X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS); //http://www.phronesisweb.com/blog/filling-pdf-acrofields-in-c-using-itextsharp/ AcroFields form = stamper.AcroFields; form.GenerateAppearances = true; ////form.SetField("name", "John Doe"); ////form.SetField("address", "xxxxx, yyyy"); ////form.SetField("postal_code", "12345"); ////form.SetField("email", "*****@*****.**"); if (info.MetaData != null) { lock (info.MetaData) { foreach (Tuple <string, string> kv in info.MetaData) { form.SetField(kv.Item1, kv.Item2); //form.SetFieldProperty(kv.Item1.Compress(), "fflags", 0, null); } } } //http://forums.asp.net/t/1846462.aspx?PDF+form+contents+are+not+visible+iTextSharp //Dictionary<string, string> inf = reader.Info; ////inf.Add("Title", "Hello World stamped"); ////inf.Add("Subject", "Hello World with changed metadata"); ////inf.Add("Keywords", "iText in Action, PdfStamper"); ////inf.Add("Creator", "Silly standalone example"); ////inf.Add("Author", "Also Bruno Lowagie"); //if (info.MetaData != null) //{ // lock (info.MetaData) // foreach (Tuple<string, string> kv in info.MetaData) // inf.Add(kv.Item1, kv.Item2); // stamper.MoreInfo = inf; //} //stamper.SetFullCompression(); //stamper.Writer.SetFullCompression(); stamper.FormFlattening = true; stamper.Close(); } } }