public static void Main(string[] args)
        {
            // The path to the documents directory.
            string dataDir = Path.GetFullPath("../../../Data/");

            string input = dataDir + @"input.pdf";

            using (Document pdfDocument = new Document(input))
            {
                foreach (Field field in pdfDocument.Form)
                {
                    SignatureField sf = field as SignatureField;
                    if (sf != null)
                    {
                        Stream cerStream = sf.ExtractCertificate();
                        if (cerStream != null)
                        {
                            using (cerStream)
                            {
                                byte[] bytes = new byte[cerStream.Length];
                                using (FileStream fs = new FileStream(dataDir + @"input.cer", FileMode.CreateNew))
                                {
                                    cerStream.Read(bytes, 0, bytes.Length);
                                    fs.Write(bytes, 0, bytes.Length);
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #2
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();

            string input = dataDir + @"ExtractSignatureInfo.pdf";

            using (Document pdfDocument = new Document(input))
            {
                foreach (Field field in pdfDocument.Form)
                {
                    SignatureField sf = field as SignatureField;
                    if (sf != null)
                    {
                        Stream cerStream = sf.ExtractCertificate();
                        if (cerStream != null)
                        {
                            using (cerStream)
                            {
                                byte[] bytes = new byte[cerStream.Length];
                                using (FileStream fs = new FileStream(dataDir + @"input.cer", FileMode.CreateNew))
                                {
                                    cerStream.Read(bytes, 0, bytes.Length);
                                    fs.Write(bytes, 0, bytes.Length);
                                }
                            }
                        }
                    }
                }
            }
        }
        public static void Run()
        {
            // ExStart:ExtractingImage
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();

            string input = dataDir + @"ExtractingImage.pdf";

            using (Document pdfDocument = new Document(input))
            {
                foreach (Field field in pdfDocument.Form)
                {
                    SignatureField sf = field as SignatureField;
                    if (sf != null)
                    {
                        string outFile = dataDir + @"output_out.jpg";
                        using (Stream imageStream = sf.ExtractImage())
                        {
                            if (imageStream != null)
                            {
                                using (System.Drawing.Image image = Bitmap.FromStream(imageStream))
                                {
                                    image.Save(outFile, System.Drawing.Imaging.ImageFormat.Jpeg);
                                }
                            }
                        }
                    }
                }
            }
            // ExEnd:ExtractingImage
        }
Exemple #4
0
        public static void Main(string[] args)
        {
            // The path to the documents directory.
            string dataDir = Path.GetFullPath("../../../Data/");

            string input = dataDir + @"input.pdf";

            using (Document pdfDocument = new Document(input))
            {
                foreach (Field field in pdfDocument.Form)
                {
                    SignatureField sf = field as SignatureField;
                    if (sf != null)
                    {
                        string outFile = dataDir + @"output.jpg";
                        using (Stream imageStream = sf.ExtractImage())
                        {
                            if (imageStream != null)
                            {
                                using (System.Drawing.Image image = Bitmap.FromStream(imageStream))
                                {
                                    image.Save(outFile, System.Drawing.Imaging.ImageFormat.Jpeg);
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #5
0
        public int CreatePDF(Stream stream)
        {
            GcPdfDocument doc  = new GcPdfDocument();
            Page          page = doc.NewPage();
            TextFormat    tf   = new TextFormat()
            {
                Font = StandardFonts.Times, FontSize = 14
            };

            page.Graphics.DrawString(
                "Hello, World!\r\nSigned below by GcPdfWeb SignDoc sample.",
                tf, new PointF(72, 72));

            // Init a test certificate:
            var pfxPath           = Path.Combine("Resources", "Misc", "GcPdfTest.pfx");
            X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(pfxPath), "qq",
                                                         X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            SignatureProperties sp = new SignatureProperties();

            sp.Certificate = cert;
            sp.Location    = "GcPdfWeb Sample Browser";
            sp.SignerName  = "GcPdfWeb";

            // Init a signature field to hold the signature:
            SignatureField sf = new SignatureField();

            sf.Widget.Rect                     = new RectangleF(72, 72 * 2, 72 * 4, 36);
            sf.Widget.Page                     = page;
            sf.Widget.BackColor                = Color.LightSeaGreen;
            sf.Widget.TextFormat.Font          = StandardFonts.Helvetica;
            sf.Widget.ButtonAppearance.Caption = $"Signer: {sp.SignerName}\r\nLocation: {sp.Location}";
            // Add the signature field to the document:
            doc.AcroForm.Fields.Add(sf);
            // Connect the signature field and signature props:
            sp.SignatureField = sf;

            // Sign and save the document:
            // NOTES:
            // - Signing and saving is an atomic operation, the two cannot be separated.
            // - The stream passed to the Sign() method must be readable.
            doc.Sign(sp, stream);

            // Rewind the stream to read the document just created
            // into another GcPdfDocument and verify the signature:
            stream.Seek(0, SeekOrigin.Begin);
            GcPdfDocument doc2 = new GcPdfDocument();

            doc2.Load(stream);
            SignatureField sf2 = (SignatureField)doc2.AcroForm.Fields[0];

            if (!sf2.Value.VerifySignature())
            {
                throw new Exception("Failed to verify the signature");
            }

            // Done (the generated and signed document has already been saved to 'stream').
            return(doc.Pages.Count);
        }
Exemple #6
0
        private static void CreateFields(RadFixedDocument document)
        {
            CheckBoxField check = new CheckBoxField("checkBox");

            document.AcroForm.FormFields.Add(check);
            check.IsChecked = true;

            ComboBoxField combo = new ComboBoxField("combo");

            document.AcroForm.FormFields.Add(combo);
            combo.Options.Add(new ChoiceOption("Combo choice 1"));
            combo.Options.Add(new ChoiceOption("Combo choice 2"));
            combo.Options.Add(new ChoiceOption("Combo choice 3"));
            combo.Options.Add(new ChoiceOption("Combo choice 4"));
            combo.Options.Add(new ChoiceOption("Combo choice 5"));
            combo.Value = combo.Options[2];

            CombTextBoxField comb = new CombTextBoxField("comb");

            document.AcroForm.FormFields.Add(comb);
            comb.MaxLengthOfInputCharacters = 10;
            comb.Value = "0123456789";

            ListBoxField list = new ListBoxField("list");

            document.AcroForm.FormFields.Add(list);
            list.AllowMultiSelection = true;
            list.Options.Add(new ChoiceOption("List choice 1"));
            list.Options.Add(new ChoiceOption("List choice 2"));
            list.Options.Add(new ChoiceOption("List choice 3"));
            list.Options.Add(new ChoiceOption("List choice 4"));
            list.Options.Add(new ChoiceOption("List choice 5"));
            list.Options.Add(new ChoiceOption("List choice 6"));
            list.Options.Add(new ChoiceOption("List choice 7"));
            list.Value = new ChoiceOption[] { list.Options[0], list.Options[2] };

            PushButtonField push = new PushButtonField("push");

            document.AcroForm.FormFields.Add(push);

            RadioButtonField radio = new RadioButtonField("radio");

            document.AcroForm.FormFields.Add(radio);
            radio.Options.Add(new RadioOption("Radio option 1"));
            radio.Options.Add(new RadioOption("Radio option 2"));
            radio.Value = radio.Options[1];

            SignatureField signature = new SignatureField("signiture");

            document.AcroForm.FormFields.Add(signature);

            TextBoxField textBox = new TextBoxField("textBox");

            document.AcroForm.FormFields.Add(textBox);
            textBox.Value = "Sample text...";
        }
Exemple #7
0
        // This method is almost exactly the same as the SignDoc sample,
        // but adds a second signature field (does not sign it though):
        private Stream CreateAndSignPdf()
        {
            GcPdfDocument doc  = new GcPdfDocument();
            Page          page = doc.NewPage();
            TextFormat    tf   = new TextFormat()
            {
                Font = StandardFonts.Times, FontSize = 14
            };

            page.Graphics.DrawString(
                "Hello, World!\r\nSigned below TWICE by GcPdfWeb SignIncremental sample.",
                tf, new PointF(72, 72));

            // Init a test certificate:
            var pfxPath           = Path.Combine("Resources", "Misc", "GcPdfTest.pfx");
            X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(pfxPath), "qq",
                                                         X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            SignatureProperties sp = new SignatureProperties();

            sp.Certificate = cert;
            sp.Location    = "GcPdfWeb Sample Browser";
            sp.SignerName  = "GcPdfWeb";

            // Init a signature field to hold the signature:
            SignatureField sf = new SignatureField();

            sf.Widget.Rect      = new RectangleF(72, 72 * 2, 72 * 4, 36);
            sf.Widget.Page      = page;
            sf.Widget.BackColor = Color.LightSeaGreen;
            // Add the signature field to the document:
            doc.AcroForm.Fields.Add(sf);
            // Connect the signature field and signature props:
            sp.SignatureField = sf;

            // Add a second signature field:
            SignatureField sf2 = new SignatureField()
            {
                Name = "SecondSignature"
            };

            sf2.Widget.Rect      = new RectangleF(72, 72 * 3, 72 * 4, 36);
            sf2.Widget.Page      = page;
            sf2.Widget.BackColor = Color.LightYellow;
            // Add the signature field to the document:
            doc.AcroForm.Fields.Add(sf2);

            var ms = new MemoryStream();

            doc.Sign(sp, ms);
            return(ms);
        }
Exemple #8
0
        public static void AddTextSignature2PDF()
        {
            PdfFile     pdfFile  = new PdfFile();
            PdfDocument document = pdfFile.Import(File.ReadAllBytes("sample.pdf"));

            //Input your certificate and password
            X509Certificate2 certificate = new X509Certificate2("test.pfx", "iditect");

            //First you need create a SignatureField with unique name
            SignatureField signatureField = new SignatureField("iDiTect Sign Field");

            //Add signature object to a signature field, so we can add a visualization to it
            signatureField.Signature = new Signature(certificate);
            //Add signature info as need
            signatureField.Signature.Properties.Reason      = "Sign by iDiTect";
            signatureField.Signature.Properties.Location    = "World Wide Web";
            signatureField.Signature.Properties.ContactInfo = "1234567";

            //Apply a visible signature widiget to represent the contents of the signature field.
            SignatureWidget widget = signatureField.Widgets.AddWidget();

            //Set signature position and size
            widget.Rect = new System.Windows.Rect(new System.Windows.Point(200, 200), new System.Windows.Size(400, 100));
            widget.RecalculateContent();

            //Customize signature appearance, you can show all signature info, or just name or date
            PageContentBuilder signatureAppearance = new PageContentBuilder(widget.Content.NormalContentSource);

            signatureAppearance.Position.Translate(10, 0);
            signatureAppearance.DrawText("Digitally signed by " + certificate.GetNameInfo(X509NameType.SimpleName, true));
            signatureAppearance.Position.Translate(10, 20);
            signatureAppearance.DrawText("Reason: " + signatureField.Signature.Properties.Reason);
            signatureAppearance.Position.Translate(10, 40);
            signatureAppearance.DrawText("Location: " + signatureField.Signature.Properties.Location);
            signatureAppearance.Position.Translate(10, 60);
            signatureAppearance.DrawText("Contact: " + signatureField.Signature.Properties.ContactInfo);
            signatureAppearance.Position.Translate(10, 80);
            signatureAppearance.DrawText("Date: " + DateTime.Now.ToString());

            //Add this signature to first PDF page
            document.Pages[0].Annotations.Add(widget);
            document.AcroForm.FormFields.Add(signatureField);

            //Digital sign feature need the stream support reading, so you have to use ReadWrite mode here
            using (FileStream fs = new FileStream("signed.pdf", FileMode.Create, FileAccess.ReadWrite))
            {
                pdfFile.Export(document, fs);
            }
        }
        public void SignAllWithText()
        {
            string outputFileName     = GetFileNameBasedOnCaller();
            string signatureFieldName = string.Empty;

            using (Stream inputStream = File.Open("../../data/letter_unsigned.pdf", FileMode.Open), certStream = File.Open("../../data/johndoe.pfx", FileMode.Open), outputStream = File.Create(outputFileName))
            {
                using (FixedDocument doc = new FixedDocument(inputStream))
                {
                    signatureFieldName = doc.Sign(certStream, "password", "John Doe,\r\n(click to view signature details)",
                                                  new Boundary(90, 140, 250, 180), 0, doc.Pages.Count - 1, (Stream)outputStream);
                }
            }

            using (Stream inputStream = File.Open(outputFileName, FileMode.Open))
            {
                using (FixedDocument doc = new FixedDocument(inputStream))
                {
                    SignatureField signatureField = (SignatureField)doc.AcroForm[signatureFieldName];

                    // check the signature
                    Assert.IsTrue(signatureField.IsSigned && signatureField.IsValid);

                    string signatureViewId = signatureField.Views[0].Identity;

                    // check that we have signature view placed on all pages
                    for (int i = 0; i < doc.Pages.Count; ++i)
                    {
                        bool annotationFound = false;

                        foreach (Annotation annotation in doc.Pages[i].Annotations)
                        {
                            WidgetAnnotation signatureFieldView = annotation as WidgetAnnotation;

                            if ((annotationFound = (signatureFieldView != null && signatureFieldView.Identity == signatureViewId)))
                            {
                                break;
                            }
                        }

                        Assert.IsTrue(annotationFound);
                    }
                }
            }

            //  Process.Start(outputFileName);
        }
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();

            File.Copy(dataDir + "blank.pdf", dataDir + "externalSignature1.pdf", true);
            using (FileStream fs = new FileStream(dataDir + "externalSignature1.pdf", FileMode.Open, FileAccess.ReadWrite))
            {
                using (Document doc = new Document(fs))
                {
                    SignatureField field1 = new SignatureField(doc.Pages[1], new Rectangle(100, 400, 10, 10));

                    // 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);

                    Aspose.Pdf.Forms.ExternalSignature externalSignature = new Aspose.Pdf.Forms.ExternalSignature(sel[0])
                    {
                        Authority   = "Me",
                        Reason      = "Reason",
                        ContactInfo = "Contact"
                    };

                    field1.PartialName = "sig1";
                    doc.Form.Add(field1, 1);
                    field1.Sign(externalSignature);
                    doc.Save();
                }
            }

            using (PdfFileSignature pdfSign = new PdfFileSignature(new Document(dataDir + "externalSignature1.pdf")))
            {
                IList <string> sigNames = pdfSign.GetSignNames();
                for (int index = 0; index <= sigNames.Count - 1; index++)
                {
                    if (!pdfSign.VerifySigned(sigNames[index]) || !pdfSign.VerifySignature(sigNames[index]))
                    {
                        throw new ApplicationException("Not verified");
                    }
                }
            }
            // ExEnd:1
        }
Exemple #11
0
        public static void AddImageSignature2PDF()
        {
            PdfFile     pdfFile  = new PdfFile();
            PdfDocument document = pdfFile.Import(File.ReadAllBytes("sample.pdf"));

            //Input your certificate and password
            X509Certificate2 certificate = new X509Certificate2("test.pfx", "iditect");

            //First you need create a SignatureField with unique name
            SignatureField signatureField = new SignatureField("iDiTect Sign Field");

            //Add signature object to a signature field, so we can add a visualization to it
            signatureField.Signature = new Signature(certificate);
            //Add signature info as need
            signatureField.Signature.Properties.Reason      = "Sign by iDiTect";
            signatureField.Signature.Properties.Location    = "World Wide Web";
            signatureField.Signature.Properties.ContactInfo = "1234567";

            //Apply a visible signature widiget to represent the contents of the signature field.
            SignatureWidget widget = signatureField.Widgets.AddWidget();

            //Set signature position and size
            widget.Rect = new System.Windows.Rect(new System.Windows.Point(200, 200), new System.Windows.Size(50, 50));
            widget.RecalculateContent();

            //Customize signature appearance, insert an image as signature displaying
            PageContentBuilder signatureAppearance = new PageContentBuilder(widget.Content.NormalContentSource);

            using (Stream imgStream = File.OpenRead("sample.jpg"))
            {
                signatureAppearance.DrawImage(imgStream);
            }

            //Add this signature to first PDF page
            document.Pages[0].Annotations.Add(widget);
            document.AcroForm.FormFields.Add(signatureField);

            //Digital sign feature need the stream support reading, so you have to use ReadWrite mode here
            using (FileStream fs = new FileStream("signed.pdf", FileMode.Create, FileAccess.ReadWrite))
            {
                pdfFile.Export(document, fs);
            }
        }
Exemple #12
0
        public static void ValidateSignature()
        {
            PdfFile     pdfFile  = new PdfFile();
            PdfDocument document = pdfFile.Import(File.ReadAllBytes("signed.pdf"));

            string status;

            //Handle first signature for example
            SignatureField signatureField = document.AcroForm.FormFields
                                            .Where(f => f.FieldType == FormFieldType.Signature).FirstOrDefault() as SignatureField;

            if (signatureField != null && signatureField.Signature != null)
            {
                SignatureValidationResult validationResult;

                if (signatureField.Signature.TryValidate(out validationResult))
                {
                    if (validationResult.IsDocumentModified)
                    {
                        status = "Invalid";
                    }
                    else
                    {
                        if (validationResult.IsCertificateValid)
                        {
                            status = "Valid";
                        }
                        else
                        {
                            status = "Unknown";
                        }
                    }
                }
                else
                {
                    status = "Invalid";
                }
            }
        }
        public void SignTwoPages()
        {
            string outputFileName     = GetFileNameBasedOnCaller();
            string signatureFieldName = string.Empty;

            using (Stream inputStream = File.Open("../../data/letter_unsigned.pdf", FileMode.Open))
            {
                using (FixedDocument doc = new FixedDocument(inputStream))
                {
                    signatureFieldName = doc.Sign("../../data/johndoe.pfx", "password", "../../data/signatureImage.png",
                                                  new Boundary(100, 140, 190, 180), 0, 1, outputFileName);
                }
            }

            using (Stream inputStream = File.Open(outputFileName, FileMode.Open))
            {
                using (FixedDocument doc = new FixedDocument(inputStream))
                {
                    SignatureField signatureField = (SignatureField)doc.AcroForm[signatureFieldName];

                    // check the signature
                    Assert.IsTrue(signatureField.IsSigned && signatureField.IsValid);

                    string signatureViewId = signatureField.Views[0].Identity;

                    for (int i = 0; i < doc.Pages.Count; ++i)
                    {
                        foreach (Annotation annotation in doc.Pages[i].Annotations)
                        {
                            WidgetAnnotation signatureFieldView = annotation as WidgetAnnotation;

                            // so we have signature view placed somewhere on the wrong page
                            Assert.False(signatureFieldView != null && signatureFieldView.Identity == signatureViewId && i > 1);
                        }
                    }
                }
            }
        }
Exemple #14
0
        public void PutSignatureFieldTest()
        {
            const string name = "adbe.x509.rsa_sha1.valid.pdf";

            UploadFile(name, name);
            const string SignatureName = "33226.p12";

            UploadFile(SignatureName, SignatureName);

            SignatureField field = new SignatureField(PageIndex: 1)
            {
                PartialName = "sign1",
                Signature   = new Signature(
                    Authority: "Sergey Smal",
                    Contact: "*****@*****.**",
                    Date: "08/01/2012 12:15:00.000 PM",
                    FormFieldName: "Signature1",
                    Location: "Ukraine",
                    Password: "******",
                    Rectangle: new Rectangle(
                        LLX: 100,
                        LLY: 100,
                        URX: 0,
                        URY: 0),
                    SignaturePath: Path.Combine(TempFolder, SignatureName),
                    SignatureType: SignatureType.PKCS7,
                    Visible: true,
                    ShowProperties: false
                    ),
                Rect = new Rectangle(100, 100, 500, 200),
            };

            var response = PdfApi.PutSignatureField(name, "Signature1", field, folder: TempFolder);

            Assert.That(response.Code, Is.EqualTo(200));
        }
Exemple #15
0
        // Fill in employee info and working hours with sample data:
        private Stream FillEmployeeData(GcPdfDocument doc)
        {
            // For the purposes of this sample, we fill the form with random data:
            var empName = "Jaime Smith";

            SetFieldValue(doc, _Names.EmpName, empName);
            SetFieldValue(doc, _Names.EmpNum, "12345");
            SetFieldValue(doc, _Names.EmpDep, "Research & Development");
            SetFieldValue(doc, _Names.EmpTitle, "Senior Developer");
            SetFieldValue(doc, _Names.EmpStatus, "Full Time");
            var      rand    = new Random((int)DateTime.Now.Ticks);
            DateTime workday = DateTime.Now.AddDays(-15);

            while (workday.DayOfWeek != DayOfWeek.Sunday)
            {
                workday = workday.AddDays(1);
            }
            TimeSpan wkTot = TimeSpan.Zero, wkReg = TimeSpan.Zero, wkOvr = TimeSpan.Zero;

            for (int i = 0; i < 7; ++i)
            {
                // Start time:
                var start = new DateTime(workday.Year, workday.Month, workday.Day, rand.Next(6, 12), rand.Next(0, 59), 0);
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][0], start.ToShortDateString());
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][1], start.ToShortTimeString());
                // End time:
                var end = start.AddHours(rand.Next(8, 14)).AddMinutes(rand.Next(0, 59));
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][2], end.ToShortTimeString());
                var tot = end - start;
                var reg = TimeSpan.FromHours((start.DayOfWeek != DayOfWeek.Saturday && start.DayOfWeek != DayOfWeek.Sunday) ? 8 : 0);
                var ovr = tot.Subtract(reg);
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][3], reg.ToString(@"hh\:mm"));
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][4], ovr.ToString(@"hh\:mm"));
                SetFieldValue(doc, _Names.DtNames[_Names.Dows[i]][5], tot.ToString(@"hh\:mm"));
                wkTot += tot;
                wkOvr += ovr;
                wkReg += reg;
                //
                workday = workday.AddDays(1);
            }
            SetFieldValue(doc, _Names.TotalReg, wkReg.TotalHours.ToString("F"));
            SetFieldValue(doc, _Names.TotalOvr, wkOvr.TotalHours.ToString("F"));
            SetFieldValue(doc, _Names.TotalHours, wkTot.TotalHours.ToString("F"));
            SetFieldValue(doc, _Names.EmpSignDate, workday.ToShortDateString());

            // Digitally sign the document on behalf of the 'employee':
            var pfxPath           = Path.Combine("Resources", "Misc", "JohnDoe.pfx");
            X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(pfxPath), "secret",
                                                         X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            SignatureProperties sp = new SignatureProperties()
            {
                Certificate = cert,
                DocumentAccessPermissions = AccessPermissions.FormFillingAndAnnotations,
                Reason     = "I confirm time sheet is correct.",
                Location   = "TimeSheetIncremental sample",
                SignerName = empName,
            };

            // Connect the signature field and signature props:
            SignatureField empSign = doc.AcroForm.Fields.First(f_ => f_.Name == _Names.EmpSign) as SignatureField;

            sp.SignatureField = empSign;
            empSign.Widget.ButtonAppearance.Caption = empName;
            // Some browser PDF viewers do not show form fields, so we render a placeholder:
            empSign.Widget.Page.Graphics.DrawString("digitally signed", new TextFormat()
            {
                FontName = "Segoe UI", FontSize = 9
            }, empSign.Widget.Rect);

            // We now 'flatten' the form: loop over document AcroForm's fields,
            // drawing their current values in place, and then remove the fields.
            // This produces a PDF with text fields' values as part of the regular
            // (non-editable) content (we leave fields filled by the supervisor):
            FlattenDoc(doc, _Names.EmpSuper, _Names.SupSignDate);

            // Done, now save the document with employee's signature:
            var ms = new MemoryStream();

            // Note that we do NOT use incremental update here (3rd parameter is false)
            // as this is not needed yet (but will be needed/used when signing by supervisor later):
            doc.Sign(sp, ms, false);
            return(ms);
        }
Exemple #16
0
        // Main entry point of this sample:
        public int CreatePDF(Stream stream)
        {
            // Set up a font collection with the fonts we need:
            _fc.RegisterDirectory(Path.Combine("Resources", "Fonts"));
            // Set that font collection on input fields' text layout
            // (we will also set it on all text layouts that we'll use):
            _inputTl.FontCollection = _fc;
            // Set up layout and formatting for input fields:
            _inputTl.ParagraphAlignment = ParagraphAlignment.Center;
            _inputTf.FontName           = "Segoe UI";
            _inputTf.FontSize           = 12;
            _inputTf.FontBold           = true;

            // Create the time sheet input form
            // (in a real-life scenario, we probably would only create it once,
            // and then re-use the form PDF):
            var doc = MakeTimeSheetForm();

            // At this point, 'doc' is an empty AcroForm.
            // In a real-life app it would be distributed to employees
            // for them to fill and send back.
            FillEmployeeData(doc);

            //
            // At this point the form is filled with employee's data.
            //

            // Supervisor data (in a real app, these would probably be fetched from a db):
            var supName     = "Jane Donahue";
            var supSignDate = DateTime.Now.ToShortDateString();

            SetFieldValue(doc, _Names.EmpSuper, supName);
            SetFieldValue(doc, _Names.SupSignDate, supSignDate);

            // The next step is to 'flatten' the form: we loop over document AcroForm's fields,
            // drawing their current values in place, and then remove the fields.
            // This produces a PDF with text fields' values as part of the regular (non-editable) content:
            FlattenDoc(doc);

            // Now we digitally sign the flattened document on behalf of the 'manager':
            var pfxPath           = Path.Combine("Resources", "Misc", "GcPdfTest.pfx");
            X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(pfxPath), "qq",
                                                         X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            SignatureProperties sp = new SignatureProperties();

            sp.Certificate = cert;
            sp.Location    = "GcPdfWeb - TimeSheet sample";
            sp.SignerName  = supName;

            // Connect the signature field and signature props:
            SignatureField supSign = doc.AcroForm.Fields.First(f_ => f_.Name == _Names.SupSign) as SignatureField;

            sp.SignatureField = supSign;
            supSign.Widget.ButtonAppearance.Caption = supName;
            // Some browser PDF viewers do not show form fields, so we render a placeholder:
            supSign.Widget.Page.Graphics.DrawString("digitally signed", new TextFormat()
            {
                FontName = "Segoe UI", FontSize = 9
            }, supSign.Widget.Rect);

            // Done, now save the document with supervisor signature:
            doc.Sign(sp, stream);
            // Dispose images only after the document is saved:
            _disposables.ForEach(d_ => d_.Dispose());
            return(doc.Pages.Count);
        }
Exemple #17
0
        // Creates the Time Sheet form:
        private GcPdfDocument MakeTimeSheetForm()
        {
            const float marginH = 72, marginV = 48;
            var         doc  = new GcPdfDocument();
            var         page = doc.NewPage();
            var         g    = page.Graphics;
            var         ip   = new PointF(marginH, marginV);

            var tl = new TextLayout(g.Resolution)
            {
                FontCollection = _fc
            };

            tl.Append("TIME SHEET", new TextFormat()
            {
                FontName = "Segoe UI", FontSize = 18
            });
            tl.PerformLayout(true);
            g.DrawTextLayout(tl, ip);
            ip.Y += tl.ContentHeight + 15;

            var logo = Image.FromFile(Path.Combine("Resources", "ImagesBis", "AcmeLogo-vertical-250px.png"));

            _disposables.Add(logo);
            var s = new SizeF(250f * 0.75f, 64f * 0.75f);

            g.DrawImage(logo, new RectangleF(ip, s), null, ImageAlign.Default);
            ip.Y += s.Height + 5;

            tl.Clear();
            tl.Append("Where Business meets Technology",
                      new TextFormat()
            {
                FontName = "Segoe UI", FontItalic = true, FontSize = 10
            });
            tl.PerformLayout(true);
            g.DrawTextLayout(tl, ip);
            ip.Y += tl.ContentHeight + 15;

            tl.Clear();
            tl.Append("1901, Halford Avenue,\r\nSanta Clara, California – 95051-2553,\r\nUnited States",
                      new TextFormat()
            {
                FontName = "Segoe UI", FontSize = 9
            });
            tl.MaxWidth      = page.Size.Width - marginH * 2;
            tl.TextAlignment = TextAlignment.Trailing;
            tl.PerformLayout(true);
            g.DrawTextLayout(tl, ip);
            ip.Y += tl.ContentHeight + 25;

            var pen = new Pen(Color.Gray, 0.5f);

            var colw    = (page.Size.Width - marginH * 2) / 2;
            var fields1 = DrawTable(ip,
                                    new float[] { colw, colw },
                                    new float[] { 30, 30, 30 },
                                    g, pen);

            var tf = new TextFormat()
            {
                FontName = "Segoe UI", FontSize = 9
            };

            tl.ParagraphAlignment = ParagraphAlignment.Center;
            tl.TextAlignment      = TextAlignment.Leading;
            tl.MarginLeft         = tl.MarginRight = tl.MarginTop = tl.MarginBottom = 4;

            // t_ - caption
            // b_ - bounds
            // f_ - field name, null means no field
            Action <string, RectangleF, string> drawField = (t_, b_, f_) =>
            {
                float tWidth;
                if (!string.IsNullOrEmpty(t_))
                {
                    tl.Clear();
                    tl.MaxHeight = b_.Height;
                    tl.MaxWidth  = b_.Width;
                    tl.Append(t_, tf);
                    tl.PerformLayout(true);
                    g.DrawTextLayout(tl, b_.Location);
                    tWidth = tl.ContentRectangle.Right;
                }
                else
                {
                    tWidth = 0;
                }
                if (!string.IsNullOrEmpty(f_))
                {
                    var fld = new TextField()
                    {
                        Name = f_
                    };
                    fld.Widget.Page = page;
                    fld.Widget.Rect = new RectangleF(
                        b_.X + tWidth + _inputMargin, b_.Y + _inputMargin,
                        b_.Width - tWidth - _inputMargin * 2, b_.Height - _inputMargin * 2);
                    fld.Widget.TextFormat   = _inputTf;
                    fld.Widget.Border.Color = Color.LightSlateGray;
                    fld.Widget.Border.Width = 0.5f;
                    doc.AcroForm.Fields.Add(fld);
                }
            };

            drawField("EMPLOYEE NAME: ", fields1[0, 0], _Names.EmpName);
            drawField("TITLE: ", fields1[1, 0], _Names.EmpTitle);
            drawField("EMPLOYEE NUMBER: ", fields1[0, 1], _Names.EmpNum);
            drawField("STATUS: ", fields1[1, 1], _Names.EmpStatus);
            drawField("DEPARTMENT: ", fields1[0, 2], _Names.EmpDep);
            drawField("SUPERVISOR: ", fields1[1, 2], _Names.EmpSuper);

            ip.Y = fields1[0, 2].Bottom;

            float col0 = 100;

            colw = (page.Size.Width - marginH * 2 - col0) / 5;
            float rowh    = 25;
            var   fields2 = DrawTable(ip,
                                      new float[] { col0, colw, colw, colw, colw, colw },
                                      new float[] { 50, rowh, rowh, rowh, rowh, rowh, rowh, rowh, rowh },
                                      g, pen);

            tl.ParagraphAlignment = ParagraphAlignment.Far;
            drawField("DATE", fields2[0, 0], null);
            drawField("START TIME", fields2[1, 0], null);
            drawField("END TIME", fields2[2, 0], null);
            drawField("REGULAR HOURS", fields2[3, 0], null);
            drawField("OVERTIME HOURS", fields2[4, 0], null);
            tf.FontBold = true;
            drawField("TOTAL HOURS", fields2[5, 0], null);
            tf.FontBold           = false;
            tl.ParagraphAlignment = ParagraphAlignment.Center;
            tf.ForeColor          = Color.Gray;
            for (int i = 0; i < 7; ++i)
            {
                drawField(_Names.Dows[i], fields2[0, i + 1], _Names.DtNames[_Names.Dows[i]][0]);
            }
            tf.ForeColor = Color.Black;
            for (int row = 1; row <= 7; ++row)
            {
                for (int col = 1; col <= 5; ++col)
                {
                    drawField(null, fields2[col, row], _Names.DtNames[_Names.Dows[row - 1]][col]);
                }
            }

            tf.FontBold = true;
            drawField("WEEKLY TOTALS", fields2[0, 8], null);
            tf.FontBold = false;

            drawField(null, fields2[3, 8], _Names.TotalReg);
            drawField(null, fields2[4, 8], _Names.TotalOvr);
            drawField(null, fields2[5, 8], _Names.TotalHours);

            ip.Y = fields2[0, 8].Bottom;

            col0 = 72 * 4;
            colw = page.Size.Width - marginH * 2 - col0;
            var fields3 = DrawTable(ip,
                                    new float[] { col0, colw },
                                    new float[] { rowh + 10, rowh, rowh },
                                    g, pen);

            drawField("EMPLOYEE SIGNATURE: ", fields3[0, 1], null);
            var r = fields3[0, 1];

            _empSignRect = new RectangleF(r.X + r.Width / 2, r.Y, r.Width / 2 - _inputMargin * 2, r.Height);
            // For a digital employee signature, uncomment this code:

            /*
             * SignatureField sf = new SignatureField();
             * sf.Name = _Names.EmpSign;
             * sf.Widget.Rect = new RectangleF(r.X + r.Width / 2, r.Y + _inputMargin, r.Width / 2 - _inputMargin * 2, r.Height - _inputMargin * 2);
             * sf.Widget.Page = page;
             * sf.Widget.BackColor = Color.LightSeaGreen;
             * doc.AcroForm.Fields.Add(sf);
             */
            drawField("DATE: ", fields3[1, 1], _Names.EmpSignDate);

            drawField("SUPERVISOR SIGNATURE: ", fields3[0, 2], null);
            // Supervisor signature:
            r = fields3[0, 2];
            SignatureField sf = new SignatureField();

            sf.Name             = _Names.SupSign;
            sf.Widget.Rect      = new RectangleF(r.X + r.Width / 2, r.Y + _inputMargin, r.Width / 2 - _inputMargin * 2, r.Height - _inputMargin * 2);
            sf.Widget.Page      = page;
            sf.Widget.BackColor = Color.LightYellow;
            doc.AcroForm.Fields.Add(sf);
            drawField("DATE: ", fields3[1, 2], _Names.SupSignDate);

            // Done:
            return(doc);
        }
        public object SignDocument(
            string appDataPath,
            string documentGuid,
            string documentId,
            string name,
            SignatureField[] fields,
            Func <string, string> urlCreator)
        {
            if (fields == null || fields.Length == 0)
            {
                return(null);
            }
            SignatureField field         = fields[0];
            string         data          = field.Data;
            string         signatureText = String.Empty;

            SignatureField.Location location      = field.Locations[0];
            const double            scaleForSizes = 2.083;
            int signatureWidth  = (int)(location.LocationWidth / scaleForSizes);
            int signatureHeight = (int)(location.LocationHeight / scaleForSizes);

            byte[]       imageBytes    = null;
            const string dataUrlPrefix = "data:image/png;base64,";

            if (data.StartsWith(dataUrlPrefix))
            {
                string base64Data = data.Substring(dataUrlPrefix.Length);
                imageBytes = Convert.FromBase64String(base64Data);
            }
            else
            {
                Regex  removeUnclosedLinkTagRegex = new Regex(@"<link[^>]*>");
                string svgData = removeUnclosedLinkTagRegex.Replace(data, String.Empty);
                IEnumerable <XElement> textElements;

                imageBytes = _svgRenderer.DrawSvgImage(svgData, signatureWidth, signatureHeight);

                XDocument root = XDocument.Parse(svgData);
                textElements = root.Descendants("{http://www.w3.org/2000/svg}text");
                if (textElements.Count() > 0)
                {
                    foreach (XElement textElement in textElements)
                    {
                        signatureText += textElement.Value;
                    }
                }
            }
            // request structure:
            //{ "documentId":"","name":"a b","waterMarkText":"","waterMarkImage":"","fields":[{"fieldType":1,"data":"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100%\" height=\"100%\" viewbox=\"0 0 233 82\" preserveaspectratio=\"none\"><text font-family=\"Tangerine\" font-size=\"60px\" fill=\"#0036D9\" y=\"50%\" x=\"50%\" dy=\"0.3em\" text-anchor=\"middle\">Anonymous</text><defs><link href=\"http://fonts.googleapis.com/css?family=Tangerine\" type=\"text/css\" rel=\"stylesheet\" xmlns=\"http://www.w3.org/1999/xhtml\"><style type=\"text/css\">@import url(http://fonts.googleapis.com/css?family=Tangerine)</style></defs></svg>","locations":[{"page":1,"locationX":0.4,"locationY":0.3,"locationWidth":150,"locationHeight":50,"fontName":null,"fontSize":null,"fontColor":null,"fontBold":null,"fontItalic":null,"fontUnderline":null,"alignment":0,"id":"ff4dd6a4a44ecd682a4be3a19a801e6f"}],"id":"1c9b463ac3c1e9ebaf51e34ea352de3a"}],"documentGuid":"candy.pdf","recipientGuid":"71d1f3ef88a5d7fe32f4c46588a69887","email":"*****@*****.**"}

            string path = documentGuid;
            string fullPathToDocument = Path.Combine(appDataPath, path);

            string fileNameExtension = Path.GetExtension(path).TrimStart('.');

            fileNameExtension = fileNameExtension.ToLower();
            int pageWidth = 0, pageHeight = 0;
            int signatureColumnNum = 0, signatureRowNum = 0;

            int pageNumber = location.Page;

            PositionInCellsDocument positionInCellsDocument = new PositionInCellsDocument();

            System.Drawing.Size size = GetPageSize(fullPathToDocument, location.Page,
                                                   location.LocationX, location.LocationY,
                                                   positionInCellsDocument);
            signatureColumnNum = positionInCellsDocument.ColumnNumber;
            signatureRowNum    = positionInCellsDocument.RowNumber;
            pageWidth          = size.Width;
            pageHeight         = size.Height;
            string outputFilePath;

            MemoryStream imageStream = null;

            try
            {
                if (imageBytes == null)
                {
                    outputFilePath = SignDocumentWithText(appDataPath,
                                                          documentGuid,
                                                          signatureText,
                                                          pageNumber,
                                                          (int)(pageWidth * location.LocationX),
                                                          (int)(pageHeight * location.LocationY),
                                                          signatureWidth,
                                                          signatureHeight,
                                                          signatureColumnNum, signatureRowNum);
                }
                else
                {
                    imageStream    = new MemoryStream(imageBytes);
                    outputFilePath = SignDocumentWithImage(appDataPath,
                                                           documentGuid,
                                                           imageStream,
                                                           pageNumber,
                                                           (int)(pageWidth * location.LocationX),
                                                           (int)(pageHeight * location.LocationY),
                                                           signatureWidth,
                                                           signatureHeight,
                                                           signatureColumnNum, signatureRowNum);
                }
            }
            finally
            {
                if (imageStream != null)
                {
                    imageStream.Dispose();
                }
            }
            string relativeOutputFileName = Path.Combine("Output", Path.GetFileName(outputFilePath));

            var resultData = new
            {
                status = "Ok",
                result = new
                {
                    document = new
                    {
                        guid              = relativeOutputFileName,
                        name              = relativeOutputFileName,
                        signedName        = relativeOutputFileName,
                        signedDocumentUrl = urlCreator(relativeOutputFileName),
                        signedFromAll     = true,
                        recipients        = new[]
                        {
                            new
                            {
                                id           = 0,
                                guid         = "71d1f3ef88a5d7fe32f4c46588a69887",
                                documentGuid = "cea6784811dc54d7feac5fcb5ef8817a",
                                firstName    = "dummy",
                                lastName     = "dummy",
                                email        = "*****@*****.**",
                                signed       = true
                            }
                        }
                    }
                }
            };

            return(resultData);
        }
Exemple #19
0
        private static void DrawPageWithWidgets(RadFixedDocument document)
        {
            RadFixedPage page = document.Pages.AddPage();

            FixedContentEditor editor = new FixedContentEditor(page);

            using (editor.SaveGraphicProperties())
            {
                editor.GraphicProperties.IsFilled        = true;
                editor.GraphicProperties.IsStroked       = false;
                editor.GraphicProperties.StrokeThickness = 0;
                editor.GraphicProperties.FillColor       = new RgbColor(209, 178, 234);
                editor.DrawRectangle(new Rect(50, 50, editor.Root.Size.Width - 100, editor.Root.Size.Height - 100));
            }

            editor.Position.Translate(100, 100);
            Size widgetDimensions = new Size(200, 30);

            foreach (FormField field in document.AcroForm.FormFields)
            {
                switch (field.FieldType)
                {
                case FormFieldType.CheckBox:
                    CheckBoxField check = (CheckBoxField)field;
                    DrawNextWidgetWithDescription(editor, "CheckBox", (e) => e.DrawWidget(check, widgetDimensions));
                    break;

                case FormFieldType.ComboBox:
                    ComboBoxField combo = (ComboBoxField)field;
                    DrawNextWidgetWithDescription(editor, "ComboBox", (e) => e.DrawWidget(combo, widgetDimensions));
                    break;

                case FormFieldType.CombTextBox:
                    CombTextBoxField comb = (CombTextBoxField)field;
                    DrawNextWidgetWithDescription(editor, "Comb TextBox", (e) => e.DrawWidget(comb, widgetDimensions));
                    break;

                case FormFieldType.ListBox:
                    ListBoxField list = (ListBoxField)field;
                    DrawNextWidgetWithDescription(editor, "ListBox", (e) => e.DrawWidget(list, new Size(widgetDimensions.Width, widgetDimensions.Width)));
                    break;

                case FormFieldType.PushButton:
                    PushButtonField push = (PushButtonField)field;
                    DrawNextWidgetWithDescription(editor, "Button", (e) => e.DrawWidget(push, widgetDimensions));
                    break;

                case FormFieldType.RadioButton:
                    RadioButtonField radio = (RadioButtonField)field;
                    foreach (RadioOption option in radio.Options)
                    {
                        DrawNextWidgetWithDescription(editor, option.Value, (e) => e.DrawWidget(radio, option, widgetDimensions));
                    }
                    break;

                case FormFieldType.Signature:
                    SignatureField signature = (SignatureField)field;
                    DrawNextWidgetWithDescription(editor, "Signature", (e) => e.DrawWidget(signature, widgetDimensions));
                    break;

                case FormFieldType.TextBox:
                    TextBoxField textBox = (TextBoxField)field;
                    DrawNextWidgetWithDescription(editor, "TextBox", (e) => e.DrawWidget(textBox, widgetDimensions));
                    break;
                }
            }
        }
        /// <summary>
        /// Signs the range of document pages using given certificate and signature image.
        /// </summary>
        /// <param name="doc">Document to sign.</param>
        /// <param name="signingCertificate">Signing certificate's data stream.</param>
        /// <param name="certPassword">Certificate's password.</param>
        /// <param name="signatureText">The text of the signature.</param>
        /// <param name="signatureBoundary">Visual signature boundaries.</param>
        /// <param name="signaturePageIndexStart">The index of the first page to sign.</param>
        /// <param name="signaturePageIndexEnd">The index of the last page to sign.</param>
        /// <param name="outputStream">Output stream, optional. If not set, incremental save will be performed.</param>
        /// <returns>Identifier assigned to the created signature field. Using this id you can find this field in doc's AcroForm dictionary.</returns>
        public static string Sign(this FixedDocument doc, Stream signingCertificate,
                                  string certPassword, string signatureText, Boundary signatureBoundary,
                                  int signaturePageIndexStart = 0, int signaturePageIndexEnd = 0, Stream outputStream = null)
        {
            if (doc == null)
            {
                throw new ArgumentNullException(nameof(doc));
            }

            if (signingCertificate == null)
            {
                throw new ArgumentNullException(nameof(signingCertificate));
            }

            if (certPassword == null)
            {
                throw new ArgumentNullException(nameof(certPassword));
            }

            if (signatureBoundary == null)
            {
                throw new ArgumentNullException(nameof(signatureBoundary));
            }

            if (signaturePageIndexStart < 0 || signaturePageIndexStart > doc.Pages.Count - 1)
            {
                throw new ArgumentOutOfRangeException(nameof(signaturePageIndexStart));
            }

            if (signaturePageIndexEnd < signaturePageIndexStart || signaturePageIndexEnd > doc.Pages.Count - 1)
            {
                throw new ArgumentOutOfRangeException(nameof(signaturePageIndexEnd));
            }

            // create textual resource
            FixedContent signatureTextXObject = new FixedContent(Guid.NewGuid().ToString("N"), new Boundary(0, 0, signatureBoundary.Width, signatureBoundary.Height));

            Section section = new Section();

            if (!string.IsNullOrEmpty(signatureText))
            {
                var newLineString = "<br/>";
                signatureText = signatureText.Replace("\r\n", newLineString)
                                .Replace("\n", newLineString)
                                .Replace("\r", newLineString);

                foreach (ContentElement contentElement in ContentElement.FromMarkup(signatureText))
                {
                    contentElement.Font = new Font("TimesNewRoman", 12);
                    section.Add(contentElement);
                }

                signatureTextXObject.Content.AppendContentElement(section, signatureBoundary.Width, signatureBoundary.Height);
            }

            doc.ResourceManager.RegisterResource(signatureTextXObject);

            string signatureFieldId = Guid.NewGuid().ToString("N");

            // create signature field and initialize it using a stored
            // password protected certificate
            SignatureField signatureField = new SignatureField(signatureFieldId);

            signatureField.Signature = Signature.Create(new Pkcs12Store(signingCertificate, certPassword));

            // add signature field to a document
            doc.AcroForm.Fields.Add(signatureField);

            // create signature view using the image resource
            SignatureFieldView signatureView = new SignatureFieldView(signatureField, signatureBoundary);

            signatureView.ViewSettings.Graphic           = Graphic.XObject;
            signatureView.ViewSettings.GraphicResourceID = signatureTextXObject.ID;
            signatureView.ViewSettings.Description       = Description.None;

            // add view to pages' annotations
            for (int i = signaturePageIndexStart; i <= signaturePageIndexEnd; ++i)
            {
                doc.Pages[i].Annotations.Add(signatureView);
            }

            // save to specified file or do an incremental update
            if (outputStream != null)
            {
                doc.Save(outputStream);
            }
            else
            {
                doc.Save();
            }

            return(signatureFieldId);
        }
Exemple #21
0
        public void CreatePDF(Stream stream)
        {
            var        doc  = new GcPdfDocument();
            var        page = doc.NewPage();
            var        g    = page.Graphics;
            TextFormat tf   = new TextFormat();

            tf.Font     = StandardFonts.Times;
            tf.FontSize = 14;
            PointF ip        = new PointF(72, 72);
            float  fldOffset = 72 * 2;
            float  fldHeight = tf.FontSize * 1.2f;
            float  dY        = 32;

            // Text field:
            g.DrawString("Text field:", tf, ip);
            var fldText = new TextField();

            fldText.Value                      = "Initial TextField value";
            fldText.Widget.Page                = page;
            fldText.Widget.Rect                = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
            fldText.Widget.TextFormat.Font     = tf.Font;
            fldText.Widget.TextFormat.FontSize = tf.FontSize;
            doc.AcroForm.Fields.Add(fldText);
            ip.Y += dY;

            // Checkbox:
            g.DrawString("Checkbox:", tf, ip);
            var fldCheckbox = new CheckBoxField();

            fldCheckbox.Value       = true;
            fldCheckbox.Widget.Page = page;
            fldCheckbox.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, fldHeight, fldHeight);
            doc.AcroForm.Fields.Add(fldCheckbox);
            ip.Y += dY;

            // Radio button:
            g.DrawString("Radio button:", tf, ip);
            var fldRadio = new RadioButtonField();

            fldRadio.Value = 1;
            fldRadio.Widgets.Add(new WidgetAnnotation(page, new RectangleF(ip.X + fldOffset, ip.Y, fldHeight, fldHeight)));
            fldRadio.Widgets.Add(new WidgetAnnotation(page, new RectangleF(ip.X + fldOffset, ip.Y + fldHeight * 1.2f, fldHeight, fldHeight)));
            fldRadio.Widgets.Add(new WidgetAnnotation(page, new RectangleF(ip.X + fldOffset, ip.Y + (fldHeight * 1.2f) * 2, fldHeight, fldHeight)));
            doc.AcroForm.Fields.Add(fldRadio);
            ip.Y = fldRadio.Widgets[fldRadio.Widgets.Count - 1].Rect.Y + dY;

            // CombTextField:
            g.DrawString("CombText field:", tf, ip);
            var fldCombText = new CombTextField();

            fldCombText.Value = "123";
            fldCombText.Widget.TextFormat.FontSize = 12;
            fldCombText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
            fldCombText.Widget.Page = page;
            doc.AcroForm.Fields.Add(fldCombText);
            ip.Y += dY;

            // Combo-box:
            g.DrawString("Combo box:", tf, ip);
            var fldComboBox = new ComboBoxField();

            fldComboBox.Items.Add(new ChoiceFieldItem("ComboBox Choice 1"));
            fldComboBox.Items.Add(new ChoiceFieldItem("ComboBox Choice 2"));
            fldComboBox.Items.Add(new ChoiceFieldItem("ComboBox Choice 3"));
            fldComboBox.SelectedIndex = 1;
            fldComboBox.Widget.Rect   = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
            fldComboBox.Widget.Page   = page;
            doc.AcroForm.Fields.Add(fldComboBox);
            ip.Y += dY;

            // List box:
            g.DrawString("List box:", tf, ip);
            ListBoxField fldListBox = new ListBoxField();

            fldListBox.Items.Add(new ChoiceFieldItem("ListBox Choice 1"));
            fldListBox.Items.Add(new ChoiceFieldItem("ListBox Choice 2"));
            fldListBox.Items.Add(new ChoiceFieldItem("ListBox Choice 3"));
            fldListBox.SelectedIndexes   = new int[] { 0, 2 };
            fldListBox.MultiSelect       = true;
            fldListBox.CommitOnSelChange = true;
            fldListBox.Widget.Rect       = new RectangleF(ip.X + fldOffset, ip.Y, 100, 50);
            fldListBox.Widget.Page       = page;
            doc.AcroForm.Fields.Add(fldListBox);
            ip.Y = fldListBox.Widget.Rect.Bottom - fldHeight + dY;

            // Signature field:
            g.DrawString("Signature field:", tf, ip);
            var fldSignature = new SignatureField();

            fldSignature.AlternateName = "All fields locked when the document is signed";
            fldSignature.LockedFields  = new SignatureLockedFields();
            fldSignature.Widget.Rect   = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 2, 72 - dY);
            fldSignature.Widget.TextFormat.FontSize      = 8;
            fldSignature.Widget.ButtonAppearance.Caption = "Click to sign";
            fldSignature.Widget.Border = new Border()
            {
                Width = 0.5f, Color = Color.DarkSeaGreen
            };
            fldSignature.Widget.Page = page;
            doc.AcroForm.Fields.Add(fldSignature);
            ip.Y += 72 - fldHeight;

            // Buttons:
            g.DrawString("Push buttons:", tf, ip);

            // Submit form button:
            var btnSubmit = new PushButtonField();

            btnSubmit.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72, fldHeight);
            btnSubmit.Widget.ButtonAppearance.Caption = "Submit";
            btnSubmit.Widget.Highlighting             = HighlightingMode.Invert;
            btnSubmit.Widget.Events.Activate          = new ActionSubmitForm("Sample Form Submit URI");
            btnSubmit.Widget.Page = page;
            doc.AcroForm.Fields.Add(btnSubmit);
            // ip.Y += dY;

            // Reset form button:
            var btnReset = new PushButtonField();

            btnReset.Widget.Rect = new RectangleF(ip.X + fldOffset + 72 * 1.5f, ip.Y, 72, fldHeight);
            btnReset.Widget.ButtonAppearance.Caption = "Reset";
            btnReset.Widget.Highlighting             = HighlightingMode.Invert;
            btnReset.Widget.Events.Activate          = new ActionResetForm();
            btnReset.Widget.Page = page;
            doc.AcroForm.Fields.Add(btnReset);
            ip.Y += dY;

            // Done:
            doc.Save(stream);
        }
        /// <summary>
        /// Signs the range of document pages using given certificate and signature image.
        /// </summary>
        /// <param name="doc">Document to sign.</param>
        /// <param name="signingCertificate">Signing certificate's data stream.</param>
        /// <param name="certPassword">Certificate's password.</param>
        /// <param name="signatureImage">Image stream that will represent the signature visually on page.</param>
        /// <param name="signatureBoundary">Visual signature boundaries.</param>
        /// <param name="signaturePageIndexStart">The index of the first page to sign.</param>
        /// <param name="signaturePageIndexEnd">The index of the last page to sign.</param>
        /// <param name="outputStream">Output stream, optional. If not set, incremental save will be performed.</param>
        /// <returns>Identifier assigned to the created signature field. Using this id you can find this field in doc's AcroForm dictionary.</returns>
        public static string Sign(this FixedDocument doc, Stream signingCertificate,
                                  string certPassword, Stream signatureImage, Boundary signatureBoundary,
                                  int signaturePageIndexStart = 0, int signaturePageIndexEnd = 0, Stream outputStream = null)
        {
            if (doc == null)
            {
                throw new ArgumentNullException(nameof(doc));
            }

            if (signingCertificate == null)
            {
                throw new ArgumentNullException(nameof(signingCertificate));
            }

            if (certPassword == null)
            {
                throw new ArgumentNullException(nameof(certPassword));
            }

            if (signatureImage == null)
            {
                throw new ArgumentNullException(nameof(signatureImage));
            }

            if (signatureBoundary == null)
            {
                throw new ArgumentNullException(nameof(signatureBoundary));
            }

            if (signaturePageIndexStart < 0 || signaturePageIndexStart > doc.Pages.Count - 1)
            {
                throw new ArgumentOutOfRangeException(nameof(signaturePageIndexStart));
            }

            if (signaturePageIndexEnd < signaturePageIndexStart || signaturePageIndexEnd > doc.Pages.Count - 1)
            {
                throw new ArgumentOutOfRangeException(nameof(signaturePageIndexEnd));
            }

            string imageId          = Guid.NewGuid().ToString("N");
            string signatureFieldId = Guid.NewGuid().ToString("N");

            // register signature image resource
            doc.ResourceManager.RegisterResource(new Image(imageId, signatureImage));

            // create signature field and initialize it using a stored
            // password protected certificate
            SignatureField signatureField = new SignatureField(signatureFieldId);

            signatureField.Signature = Signature.Create(new Pkcs12Store(signingCertificate, certPassword));

            // add signature field to a document
            doc.AcroForm.Fields.Add(signatureField);

            // create signature view using the image resource
            SignatureFieldView signatureView = new SignatureFieldView(signatureField, signatureBoundary);

            signatureView.ViewSettings.Graphic           = Graphic.Image;
            signatureView.ViewSettings.GraphicResourceID = imageId;
            signatureView.ViewSettings.Description       = Description.None;

            // add view to pages' annotations
            for (int i = signaturePageIndexStart; i <= signaturePageIndexEnd; ++i)
            {
                doc.Pages[i].Annotations.Add(signatureView);
            }

            // save to specified file or do an incremental update
            if (outputStream != null)
            {
                doc.Save(outputStream);
            }
            else
            {
                doc.Save();
            }

            return(signatureFieldId);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private List<SignatureField> BuildSignatureFields(List<SignatureParameter> signatureParameters)
        {
            List<SignatureField> lstSignatureFields = new List<SignatureField>();

            //Entity signature
            SignatureField signatureFieldEntity = new SignatureField()
            {
                label = ENTITY,
                location = BuildSignatureLocation(signatureParameters.ElementAt(0).SignaturePosition.Page
                                                    , 5
                                                    , signatureParameters.ElementAt(0).SignaturePosition.Y
                                                    , 1
                                                    , 1)                                                    
            };

            lstSignatureFields.Add(signatureFieldEntity);

            //Personal signatures
            foreach (var signatureParameter in signatureParameters)
            {
                SignatureField signatureFieldPersonal = new SignatureField()
                {
                    label = signatureParameter.SignatureFieldLabel,
                    location = BuildSignatureLocation(signatureParameter.SignaturePosition.Page
                                                      , signatureParameter.SignaturePosition.X
                                                      , signatureParameter.SignaturePosition.Y
                                                      , signatureParameter.SignaturePosition.Width
                                                      , signatureParameter.SignaturePosition.Height),
                };

                lstSignatureFields.Add(signatureFieldPersonal);

            }

            return lstSignatureFields;
        }
Exemple #24
0
        public int CreatePDF(Stream stream)
        {
            GcPdfDocument doc  = new GcPdfDocument();
            Page          page = doc.NewPage();
            TextFormat    tf   = new TextFormat()
            {
                Font = StandardFonts.Times, FontSize = 14
            };

            page.Graphics.DrawString(
                "Hello, World!\r\nSigned below by GcPdfWeb SignatureAppearance sample.",
                tf, new PointF(72, 72));

            // Init a test certificate:
            var pfxPath           = Path.Combine("Resources", "Misc", "GcPdfTest.pfx");
            X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(pfxPath), "qq",
                                                         X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            SignatureProperties sp = new SignatureProperties();

            sp.Certificate = cert;
            sp.Location    = "GcPdfWeb Sample Browser";
            sp.SignerName  = "GcPdfWeb";

            // Create a signature field to hold the signature:
            SignatureField sf = new SignatureField();

            // Add the signature field to the document:
            doc.AcroForm.Fields.Add(sf);
            // Connect the signature field and signature props:
            sp.SignatureField = sf;

            // Set up the signature field:
            sf.Widget.Rect = new RectangleF(page.Size.Width - 72 * 4, 72 * 2, 72 * 3, 72);
            sf.Widget.Page = page;
            // Widget visual props will be overridden by sf.Widget.AppearanceStreams.Normal.Default set below:
            sf.Widget.BackColor = Color.PeachPuff;
            sf.Widget.Border    = new GrapeCity.Documents.Pdf.Annotations.Border()
            {
                Color = Color.SaddleBrown,
                Width = 3,
            };
            sf.Widget.ButtonAppearance.Caption = $"Signer: {sp.SignerName}\r\nLocation: {sp.Location}";
            // Create custom signature appearance stream:
            var rc  = new RectangleF(PointF.Empty, sf.Widget.Rect.Size);
            var fxo = new FormXObject(doc, rc);

            rc.Inflate(-4, -4);
            fxo.Graphics.FillEllipse(rc, Color.CornflowerBlue);
            fxo.Graphics.DrawEllipse(rc, new Pen(Color.RoyalBlue, 3));
            rc.Inflate(-5, -5);
            fxo.Graphics.DrawEllipse(rc, new Pen(Color.LightSteelBlue, 1));
            fxo.Graphics.DrawString($"Signed by {sp.SignerName}\non {DateTime.Now.ToShortDateString()}.",
                                    new TextFormat()
            {
                FontName   = "Times New Roman",
                FontSize   = 14,
                FontItalic = true,
                ForeColor  = Color.Navy
            },
                                    fxo.Bounds,
                                    TextAlignment.Center, ParagraphAlignment.Center, false);
            sf.Widget.AppearanceStreams.Normal.Default = fxo;

            // Reset signature appearance so that the widget appearance stream is used:
            sp.SignatureAppearance = null;

            // Sign and save the document:
            // NOTES:
            // - Signing and saving is an atomic operation, the two cannot be separated.
            // - The stream passed to the Sign() method must be readable.
            doc.Sign(sp, stream);

            // Done (the generated and signed docment has already been saved to 'stream').
            return(doc.Pages.Count);
        }