예제 #1
0
        public static void AddTextSignature2PDF()
        {
            //Please repace the trial key from trial-license.txt in download package
            //This license registration line need to be at very beginning of our other code
            LicenseManager.SetKey("trial key");

            //Input your certificate and password
            PdfCertificate cert   = new PdfCertificate("test.pfx", "iditect");
            PdfSigner      signer = new PdfSigner("sample.pdf", cert);

            //Set signature information
            signer.SignatureInfo.Contact  = "123456789";
            signer.SignatureInfo.Reason   = "Sign by iDiTect";
            signer.SignatureInfo.Location = "World Wide Web";
            //Field name need to be unique in the same pdf document
            signer.SignatureInfo.FieldName = "iDiTect Sign Field";
            //Sign in target page
            signer.SignatureInfo.PageId = 0;
            //Sign in target area
            signer.SignatureInfo.Rect = new Rectangle(50, 100, 100, 50);
            signer.SignatureAlgorithm = SignatureAlgorithm.SHA256;
            signer.SignatureType      = SignatureType.Text;

            signer.Sign("signed.pdf");
        }
        static void Main(string[] args)
        {
            PdfDocument    doc       = new PdfDocument(@"..\..\test.pdf");
            PdfCertificate cert      = new PdfCertificate(@"..\..\Demo.pfx", "e-iceblue");
            var            signature = new PdfSignature(doc, doc.Pages[0], cert, "Requestd1");

            signature.Bounds             = new RectangleF(new PointF(280, 600), new SizeF(260, 90));
            signature.IsTag              = true;
            signature.DigitalSignerLable = "Digitally signed by";
            signature.DigitalSigner      = "Harry Hu for Test";

            signature.DistinguishedName = "DN:";
            signature.LocationInfoLabel = "Location:";
            signature.LocationInfo      = "London";

            signature.ReasonLabel = "Reason: ";
            signature.Reason      = "Le document est certifie";

            signature.DateLabel = "Date: ";
            signature.Date      = DateTime.Now;

            signature.ContactInfoLabel = "Contact: ";
            signature.ContactInfo      = "123456789";

            signature.Certificated = false;

            signature.ConfigGraphicType    = ConfiguerGraphicType.Picture;
            signature.ConfiguerGraphicPath = "..\\..\\img1.png";
            signature.DocumentPermissions  = PdfCertificationFlags.ForbidChanges;
            doc.SaveToFile(@"..\..\sample.pdf");
            System.Diagnostics.Process.Start(@"..\..\sample.pdf");
        }
예제 #3
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            Stream docStream = typeof(Booklet).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.SalesOrderDetail.pdf");
            //Load the PDF document into the loaded document object.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream);

            //Get the certificate stream from .pfx file.
            Stream certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.PDF.pfx");

            //Create PdfCertificate using certificate stream and password.
            PdfCertificate pdfCert = new PdfCertificate(certificateStream, "password123");

            //Add certificate to document first page.
            PdfSignature signature = new PdfSignature(loadedDocument, loadedDocument.Pages[0], pdfCert, "Signature");

            signature.Bounds = new Syncfusion.Drawing.RectangleF(5, 5, 300, 300);

            MemoryStream stream = new MemoryStream();

            //Save the PDF document
            loadedDocument.Save(stream);

            //Close the PDF document
            loadedDocument.Close(true);

            if (stream != null)
            {
                stream.Position = 0;
                ComposeMail("DigitalSignature.pdf", null, "Signing the document", "Syncfusion", stream);
            }
        }
예제 #4
0
        static void Main(string[] args)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            doc.AppendPage();
            //doc.SaveToFile("../../testingC.pdf");
            //doc.LoadFromFile("../../testingC.pdf");
            var page = doc.Pages[0];

            String         pfxPath   = @"../../test.pfx";
            PdfCertificate cert      = new PdfCertificate(pfxPath, "123456");
            PdfSignature   signature = new PdfSignature(doc, page, cert, "signname")
            {
                ContactInfo         = "contact",
                Certificated        = true,
                DocumentPermissions = PdfCertificationFlags.AllowFormFill,
                Location            = new System.Drawing.PointF(50, 50),
                LocationInfo        = "center"
            };

            //Save pdf file.
            doc.SaveToFile(@"../../testingC signed.pdf");
            doc.Close();
        }
예제 #5
0
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            if (documentStream == null)
            {
                documentStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Essential_Studio.pdf");
            }

            //Load the selected PDF document.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream);

            //Get the .pfx certificate file stream.
            if (certificateStream == null)
            {
                certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.PDF.pfx");
            }

            //Create PdfCertificate using certificate stream and password.
            PdfCertificate pdfCert = new PdfCertificate(certificateStream, txtOwnerPassword.Password);

            //Add certificate to document first page.
            PdfSignature signature = new PdfSignature(loadedDocument, loadedDocument.Pages[0], pdfCert, "Signature");

            signature.Bounds = new System.Drawing.RectangleF(5, 5, 300, 300);

            MemoryStream stream = new MemoryStream();

            loadedDocument.Save(stream);
            loadedDocument.Close(true);
            SaveFile(stream, "output.PDF");
        }
예제 #6
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfNewDocument doc = new PdfNewDocument();

            // Create one page
            PdfPageBase page = doc.Pages.Add();

            //Draw the page
            DrawPage(page);

            String pfxPath = @"..\..\..\..\..\..\Data\Demo.pfx";
            PdfCertificate cert = new PdfCertificate(pfxPath, "e-iceblue");
            PdfSignature signature = new PdfSignature(doc, page, cert, "demo");
            signature.ContactInfo = "Harry Hu";
            signature.Certificated = true;
            signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill;

            //Save pdf file.
            doc.Save("DigitalSignature.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("DigitalSignature.pdf");
        }
예제 #7
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfNewDocument doc = new PdfNewDocument();

            // Create one page
            PdfPageBase page = doc.Pages.Add();

            //Draw the page
            DrawPage(page);

            String         pfxPath   = @"..\..\..\..\..\..\Data\Demo.pfx";
            PdfCertificate cert      = new PdfCertificate(pfxPath, "e-iceblue");
            PdfSignature   signature = new PdfSignature(doc, page, cert, "demo");

            signature.ContactInfo         = "Harry Hu";
            signature.Certificated        = true;
            signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill;

            //Save pdf file.
            doc.Save("DigitalSignature.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("DigitalSignature.pdf");
        }
        /// <summary>
        /// Create a simple PDF document
        /// </summary>
        /// <returns>Return the created PDF document as stream</returns>
        public MemoryStream DigitalSignaturePDF(string RadioButtonList2, string NewPDF, string Cryptographic, string Digest_Algorithm)
        {
            MemoryStream stream_Empty = new MemoryStream();

            //Read the PFX file
            FileStream pfxFile = new FileStream(ResolveApplicationPath("PDF.pfx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            PdfDocument    doc       = new PdfDocument();
            PdfPage        page      = doc.Pages.Add();
            PdfSolidBrush  brush     = new PdfSolidBrush(Color.Black);
            PdfPen         pen       = new PdfPen(brush, 0.2f);
            PdfFont        font      = new PdfStandardFont(PdfFontFamily.Courier, 12, PdfFontStyle.Regular);
            PdfCertificate pdfCert   = new PdfCertificate(pfxFile, "password123");
            PdfSignature   signature = new PdfSignature(page, pdfCert, "Signature");
            FileStream     jpgFile   = new FileStream(ResolveApplicationPath("logo.png"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            PdfBitmap      bmp       = new PdfBitmap(jpgFile);

            signature.Bounds       = new RectangleF(new PointF(5, 5), page.GetClientSize());
            signature.ContactInfo  = "*****@*****.**";
            signature.LocationInfo = "Honolulu, Hawaii";
            signature.Reason       = "I am author of this document.";
            SetCryptographicStandard(Cryptographic, signature);
            SetDigest_Algorithm(Digest_Algorithm, signature);
            if (RadioButtonList2 == "Standard")
            {
                signature.Certificated = true;
            }
            else
            {
                signature.Certificated = false;
            }
            PdfGraphics graphics = signature.Appearence.Normal.Graphics;

            string validto   = "Valid To: " + signature.Certificate.ValidTo.ToString();
            string validfrom = "Valid From: " + signature.Certificate.ValidFrom.ToString();

            graphics.DrawImage(bmp, 0, 0);

            doc.Pages[0].Graphics.DrawString(validfrom, font, pen, brush, 0, 90);
            doc.Pages[0].Graphics.DrawString(validto, font, pen, brush, 0, 110);

            doc.Pages[0].Graphics.DrawString(" Protected Document. Digitally signed Document.", font, pen, brush, 0, 130);
            doc.Pages[0].Graphics.DrawString("* To validate Signature click on the signature on this page \n * To check Document Status \n click document status icon on the bottom left of the acrobat reader.", font, pen, brush, 0, 150);

            // Save the pdf document to the Stream.
            MemoryStream stream = new MemoryStream();

            doc.Save(stream);

            //Close document
            doc.Close();

            stream.Position = 0;
            return(stream);

            return(stream_Empty);
        }
예제 #9
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Load a pdf document
            String      input = @"..\..\..\..\..\..\Data\DigitalSignature.pdf";
            PdfDocument doc   = new PdfDocument();

            doc.LoadFromFile(input);
            //Load the certificate
            String         pfxPath = @"..\..\..\..\..\..\Data\gary.pfx";
            PdfCertificate cert    = new PdfCertificate(pfxPath, "e-iceblue");

            PdfSignature signature = new PdfSignature(doc, doc.Pages[0], cert, "signature0");

            signature.Bounds = new RectangleF(new PointF(90, 550), new SizeF(270, 90));

            //Load sign image source.
            signature.SignImageSource = PdfImage.FromFile(@"..\..\..\..\..\..\Data\E-iceblueLogo.png");

            //Set the dispay mode of graphics, if not set any, the default one will be applied
            signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;
            signature.NameLabel    = "Signer:";

            signature.Name = "Gary";

            signature.ContactInfoLabel = "ContactInfo:";
            signature.ContactInfo      = signature.Certificate.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, true);

            signature.DateLabel = "Date:";
            signature.Date      = DateTime.Now;

            signature.LocationInfoLabel = "Location:";
            signature.LocationInfo      = "Chengdu";

            signature.ReasonLabel = "Reason: ";
            signature.Reason      = "The certificate of this document";

            signature.DistinguishedNameLabel = "DN: ";
            signature.DistinguishedName      = signature.Certificate.IssuerName.Name;

            signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges;
            signature.Certificated        = true;

            //Set fonts. if not set, default ones will be applied.
            signature.SignDetailsFont = new PdfFont(PdfFontFamily.TimesRoman, 10f);
            signature.SignNameFont    = new PdfFont(PdfFontFamily.Courier, 15);

            //Set the sign image layout mode
            signature.SignImageLayout = SignImageLayout.None;

            //Save pdf file.
            doc.SaveToFile("DigitalSignature.pdf");
            doc.Close();

            //Launch the file.
            PDFDocumentViewer("DigitalSignature.pdf");
        }
예제 #10
0
        public static void AssinarDocumento()
        {
            var    arquivoEnt = $"d:\\temp\\modelo.pdf";
            var    pdf        = DSHelper.ReadContent(arquivoEnt);
            var    arquivo    = $"d:\\temp\\modeloOut.pdf";
            float  x;
            float  y;
            Stream pfxStream = File.OpenRead("MRV ENGENHARIA E PARTICIPAÇÕES S.A..pfx");
            //Creates a certificate instance from PFX file with private key.
            PdfCertificate pdfCert = new PdfCertificate(pfxStream, "zzzzz");

            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(pdf);

            var lista = new Dictionary <int, List <Syncfusion.Drawing.RectangleF> >();

            loadedDocument.FindText("Assinado:", out lista);

            foreach (var item in lista)
            {
                x = item.Value[0].X + 100;
                y = item.Value[0].Y;
                var page = loadedDocument.Pages[item.Key] as PdfLoadedPage;

                //aplica logo da assinatura em todas as paginas
                if (page != null)
                {
                    Stream      seloStream     = File.OpenRead("SeloMrv.jpg");
                    PdfBitmap   signatureImage = new PdfBitmap(seloStream);
                    PdfGraphics gfx            = page.Graphics;
                    gfx.DrawImage(signatureImage, x, y, 90, 80);
                }

                //Applica o certificado somente na ultima pagina
                if (item.Value == lista[lista.Keys.Count - 1])
                {
                    //Creates a signature field.
                    PdfSignatureField signatureField = new PdfSignatureField(page, "AssinaturaMRV");
                    signatureField.Bounds    = new Syncfusion.Drawing.RectangleF(x, item.Value[0].Y, 50, 50);
                    signatureField.Signature = new PdfSignature(page, "MRV Engenharia");
                    //Adds certificate to the signature field.
                    signatureField.Signature.Certificate = pdfCert;
                    signatureField.Signature.Reason      = "Assinado pela MRV Engenharia";

                    //Adds the field.
                    loadedDocument.Form.Fields.Add(signatureField);
                }
            }
            //Saves the certified PDF document.
            using (FileStream fileOut = new FileStream(arquivo, FileMode.Create))
            {
                loadedDocument.Save(fileOut);
                loadedDocument.Close(true);
            }
            //return arquivo;
        }
예제 #11
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            //Get the stream from the document.
#if COMMONSB
            Stream docStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.SalesOrderDetail.pdf");
#else
            Stream docStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.SalesOrderDetail.pdf");
#endif
            //Load the PDF document into the loaded document object.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream);

            //Get the certificate stream from .pfx file.
#if COMMONSB
            Stream certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.PDF.pfx");
#else
            Stream certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.PDF.pfx");
#endif
            //Create PdfCertificate using certificate stream and password.
            PdfCertificate pdfCert = new PdfCertificate(certificateStream, "syncfusion");

            //Add certificate to document first page.
            PdfSignature signature = new PdfSignature(loadedDocument, loadedDocument.Pages[0], pdfCert, "Signature");

            signature.Bounds = new RectangleF(5, 5, 300, 300);

            MemoryStream stream = new MemoryStream();

            //Save the PDF document
            loadedDocument.Save(stream);

            //Close the PDF document
            loadedDocument.Close(true);

            stream.Position = 0;

            //Open in default system viewer.
            if (Device.RuntimePlatform == Device.UWP)
            {
                Xamarin.Forms.DependencyService.Get <IMailService>().ComposeMail("DigitalSignature.pdf", null, "Signing the document", "Syncfusion", stream);
            }
            else
            {
                Xamarin.Forms.DependencyService.Get <IMailService>().ComposeMail("DigitalSignature.pdf", null, "Signing the document", "Syncfusion", stream);
            }
        }
예제 #12
0
        public static string SpireSignDoc(string path)
        {
            var         result = @"..\..\..\Thesis Cover_Signed.pdf";
            PdfDocument doc    = new PdfDocument(path);
            PdfPageBase page   = doc.Pages[0];

            PdfCertificate cert = new PdfCertificate(@"..\..\..\DigitalSignature.pfx", "Abc123!@#");

            PdfSignature signature = new PdfSignature(doc, page, cert, "demo");

            signature.ContactInfo  = "Harry";
            signature.Certificated = true;

            signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill;

            doc.SaveToFile(result);
            return(result);
        }
예제 #13
0
        private void button1_Click(object sender, EventArgs e)
        {
            string inputFile = @"..\..\..\..\..\..\Data\DigitalSignature.pdf";

            //Load a PDF document
            PdfDocument doc = new PdfDocument();

            doc.LoadFromFile(inputFile);

            //Get the first page
            PdfPageBase page = doc.Pages[0];

            //Load a certificate .pfx file
            String         pfxPath = @"..\..\..\..\..\..\Data\ComodoSSL.pfx";
            PdfCertificate cer     = new PdfCertificate(pfxPath, "08100601", X509KeyStorageFlags.Exportable);

            //Add a signature to the specified position
            PdfSignature signature = new PdfSignature(doc, page, cer, "signature");

            signature.Bounds = new RectangleF(new PointF(90, 550), new SizeF(180, 90));

            //set the signature content
            signature.NameLabel           = "Digitally signed by:Gary";
            signature.LocationInfoLabel   = "Location:";
            signature.LocationInfo        = "CN";
            signature.ReasonLabel         = "Reason: ";
            signature.Reason              = "Ensure authenticity";
            signature.ContactInfoLabel    = "Contact Number: ";
            signature.ContactInfo         = "028-81705109";
            signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges;
            signature.GraphicsMode        = GraphicMode.SignImageAndSignDetail;
            signature.SignImageSource     = PdfImage.FromFile(@"..\..\..\..\..\..\Data\logo.png");

            //Configure OCSP which must conform to RFC 2560
            signature.ConfigureHttpOCSP(null, null);

            //Save the PDF file
            string outputFile = "result.pdf";

            doc.SaveToFile(outputFile, FileFormat.PDF);

            //Launch the file
            PDFDocumentViewer(outputFile);
        }
예제 #14
0
        private void button1_Click(object sender, EventArgs e)
        {
            string inputFile = @"..\..\..\..\..\..\Data\DigitalSignature.pdf";

            //load a PDF document
            PdfDocument doc = new PdfDocument();

            doc.LoadFromFile(inputFile);

            //Load a certificate .pfx file
            String         pfxPath = @"..\..\..\..\..\..\Data\gary.pfx";
            PdfCertificate cert    = new PdfCertificate(pfxPath, "e-iceblue", System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);

            //Add a signature to the specified position
            PdfSignature signature = new PdfSignature(doc, doc.Pages[0], cert, "signature");

            signature.Bounds = new RectangleF(new PointF(90, 550), new SizeF(180, 90));

            //Set the signature content
            signature.NameLabel           = "Digitally signed by:Gary";
            signature.LocationInfoLabel   = "Location:";
            signature.LocationInfo        = "CN";
            signature.ReasonLabel         = "Reason: ";
            signature.Reason              = "Ensure authenticity";
            signature.ContactInfoLabel    = "Contact Number: ";
            signature.ContactInfo         = "028-81705109";
            signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges;
            signature.GraphicsMode        = GraphicMode.SignImageAndSignDetail;
            signature.SignImageSource     = PdfImage.FromFile(@"..\..\..\..\..\..\Data\logo.png");

            //Configure a timestamp server
            string url = "https://freetsa.org/tsr";

            signature.ConfigureTimestamp(url);

            //Save to file
            string output = "result.pdf";

            doc.SaveToFile(output, FileFormat.PDF);

            //Launch the file
            PDFDocumentViewer(output);
        }
예제 #15
0
        public static void AddImageSignature2PDF()
        {
            //Input your certificate and password
            PdfCertificate cert   = new PdfCertificate("test.pfx", "iditect");
            PdfSigner      signer = new PdfSigner("sample.pdf", cert);

            //Support commonly used image format, like jpg, png, gif
            signer.SignatureImageFile = "sample.jpg";
            //Field name need to be unique in the same pdf document
            signer.SignatureInfo.FieldName = "iDiTect Sign";
            //Sign in target page
            signer.SignatureInfo.PageId = 0;
            //Sign in target area
            signer.SignatureInfo.Rect = new Rectangle(50, 100, 100, 50);
            signer.SignatureAlgorithm = SignatureAlgorithm.SHA256;
            signer.SignatureType      = SignatureType.Image;

            signer.Sign("signed.pdf");
        }
예제 #16
0
        public static void AddTextSignature2PDF()
        {
            //Input your certificate and password
            PdfCertificate cert   = new PdfCertificate("test.pfx", "iditect");
            PdfSigner      signer = new PdfSigner("sample.pdf", cert);

            //Set signature information
            signer.SignatureInfo.Contact  = "123456789";
            signer.SignatureInfo.Reason   = "Sign by iDiTect";
            signer.SignatureInfo.Location = "World Wide Web";
            //Field name need to be unique in the same pdf document
            signer.SignatureInfo.FieldName = "iDiTect Sign Field";
            //Sign in target page
            signer.SignatureInfo.PageId = 0;
            //Sign in target area
            signer.SignatureInfo.Rect = new Rectangle(50, 100, 150, 50);
            signer.SignatureAlgorithm = SignatureAlgorithm.SHA256;
            signer.SignatureType      = SignatureType.Text;

            signer.Sign("signed.pdf");
        }
예제 #17
0
        public static void AddImageSignature2PDF()
        {
            //Please repace the trial key from trial-license.txt in download package
            //This license registration line need to be at very beginning of our other code
            LicenseManager.SetKey("trial key");

            //Input your certificate and password
            PdfCertificate cert   = new PdfCertificate("test.pfx", "iditect");
            PdfSigner      signer = new PdfSigner("sample.pdf", cert);

            //Support commonly used image format, like jpg, png, gif
            signer.SignatureImageFile = "sample.jpg";
            //Field name need to be unique in the same pdf document
            signer.SignatureInfo.FieldName = "iDiTect Sign";
            //Sign in target page
            signer.SignatureInfo.PageId = 0;
            //Sign in target area
            signer.SignatureInfo.Rect = new Rectangle(50, 100, 100, 50);
            signer.SignatureAlgorithm = SignatureAlgorithm.SHA256;
            signer.SignatureType      = SignatureType.Image;

            signer.Sign("signed.pdf");
        }
        public byte[] SetDigitalSignature(DigitalSignatureViewModel digitalSignature, int reportId)
        {
            try
            {
                Report report           = _reportService.GetReport(reportId);
                byte[] pdfDocumentBytes = _documentService.GetSignedPdfDocument(report, report.SignerUser.FirstName, report.SignerUser.LastName);

                Stream streamCertificate = new FileStream(CertificatePath, FileMode.Open);

                PdfLoadedDocument pdfLoadedDocument = new PdfLoadedDocument(pdfDocumentBytes);
                PdfCertificate    pdfCertificate    = new PdfCertificate(streamCertificate, CertificatePassword);

                FileStream jpgFile = new FileStream(ImagePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                PdfBitmap   bmp  = new PdfBitmap(jpgFile);
                PdfPageBase page = pdfLoadedDocument.Pages[0];

                PdfSignature signature = new PdfSignature(pdfLoadedDocument, page, pdfCertificate, "Signature");
                signature.Bounds = new RectangleF(new PointF(5, 5), page.Size);

                signature.ContactInfo  = report.SignerUser.UserName;
                signature.LocationInfo = digitalSignature.Location;
                signature.Reason       = digitalSignature.Reason;

                MemoryStream stream = new MemoryStream();

                pdfLoadedDocument.Save(stream);
                pdfLoadedDocument.Close(true);

                return(stream.ToArray());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
예제 #19
0
        public ActionResult InvoiceDigitalSignPDF(long obId)
        {
            string url         = ConfigurationManager.AppSettings.Get("InvoicePDFPreview") + obId.ToString();
            String pfxPath     = ConfigurationManager.AppSettings.Get("PFXFileForInvoice");
            string pfxpassword = ConfigurationManager.AppSettings.Get("PFXFileForInvoiceKey");

            // PdfDocument pdf = new PdfDocument();
            CLayer.Invoice data     = BLayer.Invoice.GetInvoiceByOfflineBooking(obId);
            string         filename = "";

            if (data.InvoiceNumber == "")
            {
                filename = "Invoice_" + data.InvoiceId.ToString() + ".pdf";
            }
            else
            {
                filename = "Invoice_" + data.InvoiceNumber + ".pdf";
            }

            string filepath = Server.MapPath(INVOICE_FOLDER) + filename;

            //var thread = new Thread(() => pdf.LoadFromHTML(url, false, false, false));
            //thread.SetApartmentState(ApartmentState.STA);
            //thread.Start();
            //thread.Join();

            WebClient wc = new WebClient();

            wc.DownloadFile(url, filepath);


            // pdf.SaveToFile(filepath);
            //pdf.PageSettings.Margins.Top = 2.2F;
            //pdf.PageSettings.Margins.Left = 2.2F;
            //pdf.PageSettings.Margins.Right = 2.2F;
            // pdf.Close();

            //pdf = new PdfDocument();
            PdfDocument pdf = new PdfDocument();

            pdf.LoadFromFile(filepath);

            PdfCertificate digi      = new PdfCertificate(pfxPath, pfxpassword);
            PdfSignature   signature = new PdfSignature(pdf, pdf.Pages[0], digi, "Staybazar.com");

            signature.ContactInfo         = "Staybazar.com";
            signature.Certificated        = true;
            signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges;

            pdf.SaveToFile(filepath);
            pdf.Close();


            byte[] filedata    = System.IO.File.ReadAllBytes(filepath);
            string contentType = MimeMapping.GetMimeMapping(filepath);

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = filename,
                Inline   = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());

            return(File(filedata, contentType));
        }
예제 #20
0
        private void GenerateButton_Click(object sender, EventArgs e)
        {
            matric = matricNo.Text.ToLower();

            if (!(TransactionID.Text.Equals("") || ReceiptID.Text.Equals("") || matricNo.Text.Equals("")))
            {
                MySqlCommand command = new MySqlCommand("SELECT * FROM `data` WHERE `matric`=@user", db.getConnection());
                command.Parameters.Add("@user", MySqlDbType.VarChar).Value = matric;

                db.openConnection();
                MySqlDataReader rdr = command.ExecuteReader();
                matric = "";
                while (rdr.Read())
                {
                    f_data = rdr.GetString(4);
                    name   = rdr.GetString(2);
                    matric = rdr.GetString(3);
                }
                rdr.Close();
                matric = matric.ToLower();
                if (matric.Equals(matricNo.Text))
                {
                    String   t_id    = TransactionID.Text;
                    String   r_id    = ReceiptID.Text;
                    Document doc     = new Document();
                    string   newPath = Directory.GetCurrentDirectory();

                    doc.LoadFromFile(newPath + "\\Receipt Template.docx");

                    doc.Replace("_Matric_", matric, false, true);
                    doc.Replace("_Id_", t_id, false, true);
                    doc.Replace("_Receipt_", r_id, false, true);
                    doc.Replace("_Name_", name, false, true);
                    doc.Replace("_Date_", DateTime.Today.ToShortDateString(), false, true);
                    doc.Replace("_Method_", "Quickteller", false, true);

                    //Save PDF file.
                    doc.SaveToFile("Receipt.pdf", Spire.Doc.FileFormat.PDF);

                    pdf.LoadFromFile("Receipt.pdf");

                    //Set document info
                    pdf.DocumentInformation.Author   = "Bowen University";
                    pdf.DocumentInformation.Creator  = "Ali Akolade";
                    pdf.DocumentInformation.Keywords = "Bursary, Receipt, Clearance";
                    pdf.DocumentInformation.Producer = "Bowen University";
                    pdf.DocumentInformation.Subject  = f_data;
                    pdf.DocumentInformation.Title    = "Bursary Clearance of " + name;

                    //File info
                    pdf.FileInfo.CrossReferenceType = PdfCrossReferenceType.CrossReferenceStream;
                    pdf.FileInfo.IncrementalUpdate  = false;

                    //Set an owner password, enable the permissions of Printing and Copying, set encryption level
                    String         pfxPath = "AliAkolade.pfx";
                    PdfCertificate cer     = new PdfCertificate(pfxPath, "Abc123!@#$%^&*()2020", X509KeyStorageFlags.Exportable);

                    //Get the first page
                    PdfPageBase page = pdf.Pages[0];

                    //Add a signature to the specified position
                    PdfSignature signature = new PdfSignature(pdf, page, cer, "signature");
                    //signature.Bounds = new RectangleF(new PointF(90, 550), new SizeF(180, 90));

                    //set the signature content
                    signature.NameLabel           = "Digitally signed by: Bowen University";
                    signature.LocationInfoLabel   = "Location: Iwo, Osun State";
                    signature.LocationInfo        = "Iwo";
                    signature.ReasonLabel         = "Reason: Biometric Security Certificate";
                    signature.Reason              = "Ensures authenticity";
                    signature.ContactInfoLabel    = "Contact Number: 09032942619";
                    signature.ContactInfo         = "@AliAkolade";
                    signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges;
                    signature.GraphicsMode        = GraphicMode.SignNameAndSignDetail;
                    //signature.SignImageSource = PdfImage.FromFile(@"..\..\..\..\..\..\Data\logo.png");

                    //Configure OCSP which must conform to RFC 2560
                    signature.ConfigureHttpOCSP(null, null);

                    //

                    command = new MySqlCommand("INSERT INTO `receipts`(`Matric Number`, `Transaction ID`, `Receipt ID`, `Amount Paid`, `Amount Due`) VALUES (@matric, @t_id, @r_id, @paid, @due)", db.getConnection());
                    command.Parameters.Add("@matric", MySqlDbType.VarChar).Value = matric;
                    command.Parameters.Add("@t_id", MySqlDbType.Int64).Value     = t_id;
                    command.Parameters.Add("@r_id", MySqlDbType.Int64).Value     = r_id;
                    command.Parameters.Add("@paid", MySqlDbType.Int64).Value     = 824662;
                    command.Parameters.Add("@due", MySqlDbType.Int64).Value      = 0;

                    db.openConnection();

                    if (command.ExecuteNonQuery() == 1)
                    {
                        AutoClosingMessageBox.Show("Added to Database", "RECEIPT GENERATION SUCCESSFUL", 1500);
                    }

                    db.closeConnection();

                    //Save and launch
                    SaveFileDialog dialog = new SaveFileDialog();
                    dialog.Filter = "PDF document (*.pdf)|*.pdf";
                    DialogResult result   = dialog.ShowDialog();
                    string       fileName = dialog.FileName;
                    if (result == DialogResult.OK)
                    {
                        pdf.SaveToFile(fileName);
                        AutoClosingMessageBox.Show("Save Successful", "", 1000);
                    }

                    System.Diagnostics.Process.Start(fileName);
                }
                else
                {
                    AutoClosingMessageBox.Show("Please Input Valid Matric Number", "ERROR", 1000);
                }
            }
            else
            {
                AutoClosingMessageBox.Show("Please Input Valid Details", "ERROR", 1000);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Load PDF document from disk
            PdfDocument doc = new PdfDocument();

            doc.LoadFromFile("../../../../../../Data/SignatureField.pdf");

            PdfFormWidget widgets = doc.Form as PdfFormWidget;

            for (int i = 0; i < widgets.FieldsWidget.List.Count; i++)
            {
                PdfFieldWidget widget = widgets.FieldsWidget.List[i] as PdfFieldWidget;
                if (widget is PdfSignatureFieldWidget)
                {
                    //Get the field name
                    string name = widget.Name;
                    PdfSignatureFieldWidget signWidget = widget as PdfSignatureFieldWidget;

                    //Sign with certificate selection in the windows certificate store
                    System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
                    store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);

                    //Manually chose the certificate in the store
                    System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);

                    //Create a certificate using the certificate data from the store
                    PdfCertificate cert = new PdfCertificate(sel[0].RawData);

                    //Create a signature using the signature field
                    PdfSignature signature = new PdfSignature(doc, signWidget.Page, cert, name, signWidget);

                    //Load sign image source
                    signature.SignImageSource = PdfImage.FromFile("../../../../../../Data/E-iceblueLogo.png");

                    //Set the dispay mode of graphics, if not set any, the default one will be applied
                    signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;
                    signature.NameLabel    = "Signer:";

                    signature.Name = sel[0].GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, true);

                    signature.ContactInfoLabel = "ContactInfo:";
                    signature.ContactInfo      = signature.Certificate.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, true);

                    signature.DateLabel = "Date:";
                    signature.Date      = DateTime.Now;

                    signature.LocationInfoLabel = "Location:";
                    signature.LocationInfo      = "Chengdu";

                    signature.ReasonLabel = "Reason: ";
                    signature.Reason      = "The certificate of this document";

                    signature.DistinguishedNameLabel = "DN: ";
                    signature.DistinguishedName      = signature.Certificate.IssuerName.Name;

                    signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges;
                    signature.Certificated        = true;

                    //Set fonts, if not set, default ones will be applied
                    signature.SignDetailsFont = new PdfFont(PdfFontFamily.TimesRoman, 10f);
                    signature.SignNameFont    = new PdfFont(PdfFontFamily.Courier, 15);

                    //Set the sign image layout mode
                    signature.SignImageLayout = SignImageLayout.None;
                }
            }

            //Save the Pdf document
            string output = "SignWithSmartCardUsingSignatureField_out.pdf";

            doc.SaveToFile(output);

            //Launch the result file
            PDFDocumentViewer(output);
        }
예제 #22
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Load PDF document from disk
            String      input = "../../../../../../Data/PDFTemplate_HF.pdf";
            PdfDocument doc   = new PdfDocument();

            doc.LoadFromFile(input);

            //Sign with certificate selection in the windows certificate store
            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);

            //Manually chose the certificate in the store
            System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);

            //Create a certificate using the certificate data from the store
            PdfCertificate cert = new PdfCertificate(sel[0].RawData);

            PdfSignature signature = new PdfSignature(doc, doc.Pages[0], cert, "signature0");

            signature.Bounds = new RectangleF(new PointF(250, 660), new SizeF(250, 90));

            //Load sign image source.
            signature.SignImageSource = PdfImage.FromFile("../../../../../../Data/E-iceblueLogo.png");

            //Set the dispay mode of graphics, if not set any, the default one will be applied
            signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;
            signature.NameLabel    = "Signer:";

            signature.Name = sel[0].GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, true);

            signature.ContactInfoLabel = "ContactInfo:";
            signature.ContactInfo      = signature.Certificate.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, true);

            signature.DateLabel = "Date:";
            signature.Date      = DateTime.Now;

            signature.LocationInfoLabel = "Location:";
            signature.LocationInfo      = "Chengdu";

            signature.ReasonLabel = "Reason: ";
            signature.Reason      = "The certificate of this document";

            signature.DistinguishedNameLabel = "DN: ";
            signature.DistinguishedName      = signature.Certificate.IssuerName.Name;

            signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges;
            signature.Certificated        = true;

            //Set fonts, if not set, default ones will be applied
            signature.SignDetailsFont = new PdfFont(PdfFontFamily.TimesRoman, 10f);
            signature.SignNameFont    = new PdfFont(PdfFontFamily.Courier, 15);

            //Set the sign image layout mode
            signature.SignImageLayout = SignImageLayout.None;

            //Save the PDF file
            String output = "SignWithSmartCardUsingPdfFileSignature_out.pdf";

            doc.SaveToFile(output);
            doc.Close();

            //Launch the Pdf file
            PDFDocumentViewer(output);
        }
예제 #23
0
        public ActionResult DigitalSignature(string Browser, string password, string Reason, string Location, string Contact, string RadioButtonList2, string NewPDF, string submit, string Cryptographic, string Digest_Algorithm, IFormFile pdfdocument, IFormFile certificate)
        {
            string basePath = _hostingEnvironment.WebRootPath;
            string dataPath = string.Empty;

            dataPath = basePath + @"/PDF/";

            if (submit == "Create Sign PDF")
            {
                if (pdfdocument != null && pdfdocument.Length > 0 && certificate != null && certificate.Length > 0 && certificate.FileName.Contains(".pfx") && password != null && Location != null && Reason != null && Contact != null)
                {
                    PdfLoadedDocument ldoc      = new PdfLoadedDocument(pdfdocument.OpenReadStream());
                    PdfCertificate    pdfCert   = new PdfCertificate(certificate.OpenReadStream(), password);
                    PdfPageBase       page      = ldoc.Pages[0];
                    PdfSignature      signature = new PdfSignature(ldoc, page, pdfCert, "Signature");
                    signature.Bounds       = new RectangleF(new PointF(5, 5), new SizeF(200, 200));
                    signature.ContactInfo  = Contact;
                    signature.LocationInfo = Location;
                    signature.Reason       = Reason;
                    SetCryptographicStandard(Cryptographic, signature);
                    SetDigest_Algorithm(Digest_Algorithm, signature);
                    MemoryStream stream = new MemoryStream();
                    ldoc.Save(stream);
                    stream.Position = 0;
                    ldoc.Close(true);

                    //Download the PDF document in the browser.
                    FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
                    fileStreamResult.FileDownloadName = "SignedPDF.pdf";
                    return(fileStreamResult);

                    return(View());
                }
                else
                {
                    ViewBag.lab = "NOTE: Fill all fields and then create PDF";
                    return(View());
                }
            }
            else
            {
                //Read the PFX file
                FileStream pfxFile = new FileStream(dataPath + "PDF.pfx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                PdfDocument    doc       = new PdfDocument();
                PdfPage        page      = doc.Pages.Add();
                PdfSolidBrush  brush     = new PdfSolidBrush(Color.Black);
                PdfPen         pen       = new PdfPen(brush, 0.2f);
                PdfFont        font      = new PdfStandardFont(PdfFontFamily.Courier, 12, PdfFontStyle.Regular);
                PdfCertificate pdfCert   = new PdfCertificate(pfxFile, "password123");
                PdfSignature   signature = new PdfSignature(page, pdfCert, "Signature");
                FileStream     jpgFile   = new FileStream(dataPath + "logo.png", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                PdfBitmap      bmp       = new PdfBitmap(jpgFile);
                signature.Bounds       = new RectangleF(new PointF(5, 5), page.GetClientSize());
                signature.ContactInfo  = "*****@*****.**";
                signature.LocationInfo = "Honolulu, Hawaii";
                signature.Reason       = "I am author of this document.";
                SetCryptographicStandard(Cryptographic, signature);
                SetDigest_Algorithm(Digest_Algorithm, signature);
                if (RadioButtonList2 == "Standard")
                {
                    signature.Certificated = true;
                }
                else
                {
                    signature.Certificated = false;
                }
                PdfGraphics graphics = signature.Appearence.Normal.Graphics;

                string validto   = "Valid To: " + signature.Certificate.ValidTo.ToString();
                string validfrom = "Valid From: " + signature.Certificate.ValidFrom.ToString();

                graphics.DrawImage(bmp, 0, 0);

                doc.Pages[0].Graphics.DrawString(validfrom, font, pen, brush, 0, 90);
                doc.Pages[0].Graphics.DrawString(validto, font, pen, brush, 0, 110);

                doc.Pages[0].Graphics.DrawString(" Protected Document. Digitally signed Document.", font, pen, brush, 0, 130);
                doc.Pages[0].Graphics.DrawString("* To validate Signature click on the signature on this page \n * To check Document Status \n click document status icon on the bottom left of the acrobat reader.", font, pen, brush, 0, 150);

                // Save the pdf document to the Stream.
                MemoryStream stream = new MemoryStream();

                doc.Save(stream);

                //Close document
                doc.Close();

                stream.Position = 0;

                // Download the PDF document in the browser.
                FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
                fileStreamResult.FileDownloadName = "SignedPDF.pdf";
                return(fileStreamResult);

                return(View());
            }
        }
        public ActionResult DigitalSignature(string Browser, string password, HttpPostedFileBase pdfdocument, HttpPostedFileBase certificate, string RadioButtonList2, string NewPDF, string submit, string mySignature)
        {
            if (mySignature != "" && submit != "Create PDF")
            {
                if (pdfdocument != null && pdfdocument.ContentLength > 0 && certificate != null && certificate.ContentLength > 0 && password != string.Empty)
                {
                    string pfxPath = string.Empty;
                    if (pdfdocument.FileName.Contains(".pdf"))
                    {
                        ldoc = new PdfLoadedDocument(pdfdocument.InputStream);
                    }
                    if (certificate.FileName.Contains(".pfx"))
                    {
                        pfxPath = Path.Combine(Server.MapPath("~/App_Data"), certificate.FileName);
                        certificate.SaveAs(pfxPath);
                    }
                    bmp = new PdfBitmap(new MemoryStream(Convert.FromBase64String(mySignature.Substring(22))));

                    PdfPageBase page = ldoc.Pages[0];
                    page.Graphics.DrawImage(bmp, new PointF(page.Graphics.ClientSize.Width - 105, page.Graphics.ClientSize.Height - 80), new SizeF(100, 75));
                    if (password != string.Empty)
                    {
                        pdfCert = new PdfCertificate(pfxPath, password);
                    }

                    signature = new PdfSignature(ldoc, page, pdfCert, "Signature");

                    signature.Bounds = new RectangleF(new PointF(page.Graphics.ClientSize.Width - 105, page.Graphics.ClientSize.Height - 80), new SizeF(100, 75));
                    string validto   = "Valid To: " + signature.Certificate.ValidTo.ToString();
                    string validfrom = "Valid From: " + signature.Certificate.ValidFrom.ToString();

                    // Save the pdf document to the Stream.
                    MemoryStream stream = new MemoryStream();
                    ldoc.Save(stream);
                    Response.ClearContent();
                    Response.Expires = 0;
                    Response.Buffer  = true;

                    string disposition = "content-disposition";
                    Response.AddHeader(disposition, "attachment; filename=Sample.pdf");
                    Response.AddHeader("Content-Type", "application/pdf");
                    Response.Clear();
                    stream.WriteTo(Response.OutputStream);
                    Response.End();

                    ldoc.Close();
                    return(View());
                }
                else
                {
                    ViewBag.lab = "NOTE: Fill all fields and then create PDF";
                    return(View());
                }
            }
            else
            {
                PdfDocument   doc   = new PdfDocument();
                PdfPage       page  = doc.Pages.Add();
                PdfSolidBrush brush = new PdfSolidBrush(Color.Black);
                PdfPen        pen   = new PdfPen(brush, 0.2f);
                PdfFont       font  = new PdfStandardFont(PdfFontFamily.Courier, 12, PdfFontStyle.Regular);
                try
                {
                    pdfCert   = new PdfCertificate(ResolveApplicationDataPath("PDF.pfx"), "password123");
                    signature = new PdfSignature(page, pdfCert, "Signature");
                    bmp       = new PdfBitmap(ResolveApplicationImagePath("syncfusion_logo.gif"));

                    signature.Bounds       = new RectangleF(new PointF(5, 5), page.Size);
                    signature.ContactInfo  = "*****@*****.**";
                    signature.LocationInfo = "Honolulu, Hawaii";
                    signature.Reason       = "I am author of this document.";

                    if (RadioButtonList2 == "Standard")
                    {
                        signature.Certificated = true;
                    }
                    else
                    {
                        signature.Certificated = false;
                    }
                    graphics = signature.Appearence.Normal.Graphics;
                }
                catch (Exception)
                {
                    graphics = signature.Appearence.Normal.Graphics;

                    Response.Write("Warning Certificate not found \"Cannot sign This Document\"");

                    //Draw the Text at specified location.
                    graphics.DrawString("Warning this document is not signed", font, brush, new PointF(0, 20));
                    graphics.DrawString("Create a self signed Digital ID to sign this document", font, brush, new PointF(20, 40));
                    graphics.DrawLine(pen, new PointF(0, 100), new PointF(page.GetClientSize().Width, 200));
                    graphics.DrawLine(pen, new PointF(0, 200), new PointF(page.GetClientSize().Width, 100));
                }

                string validto   = "Valid To: " + signature.Certificate.ValidTo.ToString();
                string validfrom = "Valid From: " + signature.Certificate.ValidFrom.ToString();

                graphics.DrawImage(bmp, 0, 0);

                doc.Pages[0].Graphics.DrawString(validfrom, font, pen, brush, 0, 90);
                doc.Pages[0].Graphics.DrawString(validto, font, pen, brush, 0, 110);

                doc.Pages[0].Graphics.DrawString(" Protected Document. Digitally signed Document.", font, pen, brush, 0, 130);
                doc.Pages[0].Graphics.DrawString("* To validate Signature click on the signature on this page \n * To check Document Status \n click document status icon on the bottom left of the acrobat reader.", font, pen, brush, 0, 150);

                // Save the pdf document to the Stream.
                MemoryStream stream = new MemoryStream();
                doc.Save(stream);
                Response.ClearContent();
                Response.Expires = 0;
                Response.Buffer  = true;

                string disposition = "content-disposition";
                Response.AddHeader(disposition, "attachment; filename=Sample.pdf");
                Response.AddHeader("Content-Type", "application/pdf");
                Response.Clear();
                stream.WriteTo(Response.OutputStream);
                Response.End();

                doc.Close();
                return(View());
            }
        }
예제 #25
0
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            //Get the template PDF file stream from assembly.
            Stream documentStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.digital_signature_template.pdf");
            //Load the PDF document from stream.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream);
            //Get the .pfx certificate file stream.
            Stream certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.certificate.pfx");
            //Get the signature field to add digital signature.
            PdfLoadedSignatureField signatureField = loadedDocument.Form.Fields[6] as PdfLoadedSignatureField;
            //Get the signature bounds.
            RectangleF bounds = signatureField.Bounds;

            //Create PDF certificate using certificate stream and password.
            PdfCertificate pdfCertificate = new PdfCertificate(certificateStream, "password123");

            //Add certificate to first page of the document.
            PdfSignature signature = new PdfSignature(loadedDocument, loadedDocument.Pages[0], pdfCertificate, "", signatureField);

            signature.ContactInfo  = "*****@*****.**";
            signature.LocationInfo = "Honolulu, Hawaii";
            signature.Reason       = "I am author of this document.";

            //Set the cryptographic standard to signature settings.
            if ((bool)cms.IsChecked)
            {
                signature.Settings.CryptographicStandard = CryptographicStandard.CMS;
            }
            else
            {
                signature.Settings.CryptographicStandard = CryptographicStandard.CADES;
            }

            //Set the digest algorithm to signature settings.
            if ((bool)sha1.IsChecked)
            {
                signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA1;
            }
            else if ((bool)sha256.IsChecked)
            {
                signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA256;
            }
            else if ((bool)sha384.IsChecked)
            {
                signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA384;
            }
            else if ((bool)sha512.IsChecked)
            {
                signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA512;
            }

            //Get the signature field appearance graphics.
            PdfGraphics graphics = signature.Appearance.Normal.Graphics;

            if (graphics != null)
            {
                //Draw the rectangle in appearance graphics.
                graphics.DrawRectangle(PdfPens.Black, bounds);

                //Get the image file stream from assembly.
                Stream imageStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.signature.png");
                //Create the PDF bitmap image from stream.
                PdfBitmap bitmap = new PdfBitmap(imageStream, true);
                //Draw image to appearance graphics.
                graphics.DrawImage(bitmap, new RectangleF(2, 1, 30, 30));

                //Get certificate subject name.
                string subject = pdfCertificate.SubjectName;

                //Create a new font instance and draw a text to appearance graphics.
                PdfFont         font     = new PdfStandardFont(PdfFontFamily.Helvetica, 7);
                RectangleF      textRect = new RectangleF(45, 0, bounds.Width - 45, bounds.Height);
                PdfStringFormat format   = new PdfStringFormat(PdfTextAlignment.Justify);
                graphics.DrawString("Digitally signed by " + subject + " \r\nReason: Testing signature \r\nLocation: USA", font, PdfBrushes.Black, textRect, format);
            }

            //Set the digital signature to signing the field.
            signatureField.Signature = signature;

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save and close the document.
                loadedDocument.Save(stream);
                loadedDocument.Close();

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("DigitalSignature.pdf", stream);
            }
        }
예제 #26
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            //Create one page.
            PdfPageBase page = doc.Pages.Add();

            //Draw the page.
            DrawPage(page);

            String         pfxPath = @"..\..\..\..\..\..\Data\Demo.pfx";
            PdfCertificate cert    = new PdfCertificate(pfxPath, "e-iceblue");

            //signature fully.
            PdfSignature signature = new PdfSignature(doc, page, cert, "signature0");

            //invisible signature.
            //signature.Bounds = new RectangleF(new PointF(20, 350), new SizeF(200, 100));
            //display signature picture.
            //signature.ConfiguerGraphicPath =  @"\signature.jpg";
            //signature.ConfigGraphicType = ConfiguerGraphicType.Picture;
            //display signature text.
            signature.IsTag = true;
            signature.DigitalSignerLable = "Firmado Por:";
            signature.DigitalSigner      = "Alex Alvarado";
            signature.ContactInfo        = "Harry";
            signature.Date = DateTime.Now;

            signature.Certificated        = true;
            signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges;

            //create empty signature field.
            PdfSignatureField signature1Field = new PdfSignatureField(page, "signature1");

            signature1Field.Bounds        = new RectangleF(new PointF(300, 350), new SizeF(200, 100));
            signature1Field.BorderWidth   = 1.0f;
            signature1Field.BorderStyle   = PdfBorderStyle.Solid;
            signature1Field.BorderColor   = new PdfRGBColor(System.Drawing.Color.Black);
            signature1Field.HighlightMode = PdfHighlightMode.Outline;
            // display picture.
            //signature1Field.DrawImage(new PdfBitmap(m_DataDirectory + @"\SpirePdf-815.jpg"), 0, 0);
            doc.Form.Fields.Add(signature1Field);

            doc.SaveToFile("DigitalSignature.pdf");
            doc.Close();

            /* --------------------------------------------------------------------------------------- */

            doc = new PdfDocument("DigitalSignature.pdf");

            //signature empty signature field.
            PdfSignatureFieldWidget signature1FieldWidget =
                (doc.Form as PdfFormWidget).FieldsWidget["signature1"] as PdfSignatureFieldWidget;
            PdfSignature signature1 =
                new PdfSignature(doc, signature1FieldWidget.Page, cert, signature1FieldWidget.Name, signature1FieldWidget);

            signature1.IsTag = true;
            signature1.DigitalSignerLable = "Firmado Por:";
            signature1.DigitalSigner      = "Alex Alvarado";
            signature1.ContactInfo        = "Harry";
            signature1.Date = DateTime.Now;

            //Save pdf file.
            doc.SaveToFile("DigitalSignature.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("DigitalSignature.pdf");
        }