Ejemplo n.º 1
0
        public static void Main()
        {
            // NOTE:
            // When used in trial mode, the library imposes some restrictions.
            // Please visit http://bitmiracle.com/pdf-library/trial-restrictions.aspx
            // for more information.

            string outputFileName = "SignSignatureField.pdf";

            using (PdfDocument pdf = new PdfDocument(@"..\Sample Data\SignatureFields.pdf"))
            {
                // IMPORTANT:
                // Replace "keystore.p12" and "password" with your own .p12 or .pfx path and password.
                // Without the change the sample will not work.

                PdfSignatureField field   = pdf.GetControl("Signature2") as PdfSignatureField;
                PdfSigningOptions options = new PdfSigningOptions("keystore.p12", "password")
                {
                    DigestAlgorithm = PdfDigestAlgorithm.Sha256,
                    Format          = PdfSignatureFormat.Pkcs7Detached,
                    Field           = field,
                    Reason          = "Testing field signing",
                    Location        = "My workplace",
                    ContactInfo     = "*****@*****.**"
                };

                pdf.SignAndSave(options, outputFileName);
            }

            Console.WriteLine($"The output is located in {Environment.CurrentDirectory}");
        }
Ejemplo n.º 2
0
        public static byte[] AddPdfSignatureField(byte[] filePdf, PdfSignatureField signatureField)
        {
            var thumbprint         = signatureField.thumbprint;
            var page               = signatureField.page;
            var x                  = signatureField.x;
            var y                  = signatureField.y;
            var location           = signatureField.location;
            var width              = signatureField.width;
            var height             = signatureField.height;
            var reason             = signatureField.reason;
            var signatureFieldName = signatureField.name;

            IList <Org.BouncyCastle.X509.X509Certificate> chain;
            X509Certificate2   pk;
            IOcspClient        ocspClient;
            ITSAClient         tsaClient;
            IList <ICrlClient> crlList;

            CertificateUtility.GetCertificateProperties(thumbprint, out chain, out pk, out ocspClient, out tsaClient, out crlList);


            var result = AddPdfSignatureField(filePdf, chain, pk, DigestAlgorithms.SHA1, CryptoStandard.CMS, reason,
                                              location,
                                              crlList, ocspClient, tsaClient, 0, page, new Rectangle(x, y, width + x, height + y), signatureFieldName);

            return(result);
        }
Ejemplo n.º 3
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;
        }
        public static void Main()
        {
            // NOTE:
            // When used in trial mode, the library imposes some restrictions.
            // Please visit http://bitmiracle.com/pdf-library/trial-restrictions.aspx
            // for more information.

            StringBuilder sb = new StringBuilder();

            using (PdfDocument pdf = new PdfDocument(@"..\Sample Data\signed.pdf"))
            {
                PdfControl control = pdf.GetControls().FirstOrDefault(c => c.Type == PdfWidgetType.Signature);
                if (control == null)
                {
                    Console.WriteLine("Document does not contain signature fields");
                    return;
                }

                PdfSignatureField field = (PdfSignatureField)control;
                sb.AppendFormat("Signature field is invisible: {0}\n", isInvisible(field));

                PdfSignature signature = field.Signature;
                sb.AppendFormat("Signed by: {0}\n", signature.Name);
                sb.AppendFormat("Signing time: {0}\n", signature.SigningTime);
                sb.AppendFormat("Signed at: {0}\n", signature.Location);
                sb.AppendFormat("Reason for signing: {0}\n", signature.Reason);
                sb.AppendFormat("Signer's contact: {0}\n", signature.ContactInfo);

                PdfSignatureContents contents = signature.Contents;
                sb.AppendFormat("Has OCSP embedded: {0}\n", contents.CheckHasEmbeddedOcsp());
                sb.AppendFormat("Has CRL embedded: {0}\n", contents.CheckHasEmbeddedCrl());

                PdfSignatureCertificate certificate = contents.GetSigningCertificate();
                sb.AppendLine();
                sb.AppendLine("== Signing certificate:");
                sb.AppendFormat("Name: {0}\n", certificate.Name);
                sb.AppendFormat("Algorithm: {0}\n", certificate.AlgorithmName);
                sb.AppendFormat("Subject DN: {0}\n", certificate.Subject.Name);
                sb.AppendFormat("Issuer DN: {0}\n", certificate.Issuer.Name);
                sb.AppendFormat("Serial number: {0}\n", certificate.SerialNumber);
                sb.AppendFormat("Valid from {0} up to {1}\n", certificate.ValidFrom, certificate.ValidUpto);
                sb.AppendFormat("Timestamp Authority URL: {0}\n", certificate.GetTimestampAuthorityUrl());

                PdfSignatureCertificate issuer = contents.GetIssuerCertificateFor(certificate);
                sb.AppendLine();
                sb.AppendLine("== Issuer certificate:");
                sb.AppendFormat("Subject DN: {0}\n", issuer.Subject.Name);
                sb.AppendFormat("Issuer DN: {0}\n", issuer.Issuer.Name);
                sb.AppendFormat("Serial number: {0}\n", issuer.SerialNumber);
            }

            Console.WriteLine(sb.ToString());
        }
Ejemplo n.º 5
0
        public static void Main()
        {
            // NOTE:
            // When used in trial mode, the library imposes some restrictions.
            // Please visit http://bitmiracle.com/pdf-library/trial-restrictions.aspx
            // for more information.

            string outputFileName = "SignSignatureFieldUsingCustomStyle.pdf";

            using (PdfDocument pdf = new PdfDocument(@"..\Sample Data\SignatureFields.pdf"))
            {
                // IMPORTANT:
                // Replace "keystore.p12" and "password" with your own .p12 or .pfx path and password.
                // Without the change the sample will not work.

                PdfSignatureField field = pdf.GetControl("Control") as PdfSignatureField;
                field.BackgroundColor = new PdfGrayColor(80);

                PdfSigningOptions options = new PdfSigningOptions("keystore.p12", "password")
                {
                    DigestAlgorithm = PdfDigestAlgorithm.Sha256,
                    Format          = PdfSignatureFormat.Pkcs7Detached,
                    Field           = field,
                    Reason          = "Testing field styles",
                    Location        = "My workplace",
                    ContactInfo     = "*****@*****.**"
                };

                PdfSignatureAppearanceOptions appearance = options.Appearance;
                appearance.IncludeDate = false;
                appearance.IncludeDistinguishedName = false;

                appearance.Image         = pdf.AddImage(@"..\Sample Data\ammerland.jpg");
                appearance.Font          = pdf.AddFont(PdfBuiltInFont.Courier);
                appearance.FontSize      = 0; // calculate font size automatically
                appearance.FontColor     = new PdfRgbColor(0, 0, 255);
                appearance.TextAlignment = PdfSignatureTextAlignment.Right;

                appearance.NameLabel     = "Digital signiert von";
                appearance.ReasonLabel   = "Grund:";
                appearance.LocationLabel = "Ort:";

                pdf.SignAndSave(options, outputFileName);
            }

            Console.WriteLine($"The output is located in {Environment.CurrentDirectory}");
        }
Ejemplo n.º 6
0
        private void AddSignatureComponents(object sender, EventArgs e)
        {
            var catalog = Document.Catalog;

            if (catalog.AcroForm == null)
            {
                catalog.AcroForm = new PdfAcroForm(Document);
            }

            catalog.AcroForm.Elements.Add(PdfAcroForm.Keys.SigFlags, new PdfInteger(3));

            var signature = new PdfSignatureField(Document);

            var paddedContents = new PdfString("", PdfStringFlags.HexLiteral, maximumSignatureLength.Value);
            var paddedRange    = new PdfArray(Document, byteRangePaddingLength, new PdfInteger(0), new PdfInteger(0), new PdfInteger(0), new PdfInteger(0));

            signature.Contents          = paddedContents;
            signature.ByteRange         = paddedRange;
            signature.Reason            = Options.Reason;
            signature.Location          = Options.Location;
            signature.Rectangle         = new PdfRectangle(Options.Rectangle);
            signature.AppearanceHandler = Options.AppearanceHandler ?? new DefaultAppearanceHandler()
            {
                Location = Options.Location,
                Reason   = Options.Reason,
                Signer   = signer.GetName()
            };
            signature.PrepareForSave();

            this.contentsTraker = new PositionTracker(paddedContents);
            this.rangeTracker   = new PositionTracker(paddedRange);

            var annotations = Document.Pages[0].Elements.GetArray(PdfPage.Keys.Annots);

            if (annotations == null)
            {
                Document.Pages[0].Elements.Add(PdfPage.Keys.Annots, new PdfArray(Document, signature));
            }
            else
            {
                annotations.Elements.Add(signature);
            }

            catalog.AcroForm.Fields.Elements.Add(signature);
        }
        public static void Main()
        {
            // NOTE:
            // When used in trial mode, the library imposes some restrictions.
            // Please visit http://bitmiracle.com/pdf-library/trial-restrictions.aspx
            // for more information.

            string outputFileName = "SignSignatureFieldUsingCustomStyle.pdf";

            using (PdfDocument pdf = new PdfDocument("Sample data/SignatureFields.pdf"))
            {
                // IMPORTANT:
                // Replace "keystore.p12" and "password" with your own .p12 or .pfx path and password.
                // Without the change the sample will not work.

                PdfSignatureField field   = pdf.GetControl("Control") as PdfSignatureField;
                PdfSigningOptions options = new PdfSigningOptions("keystore.p12", "password")
                {
                    DigestAlgorithm = PdfDigestAlgorithm.Sha256,
                    Format          = PdfSignatureFormat.Pkcs7Detached,
                    Field           = field,
                    Reason          = "Testing field styles",
                    Location        = "My workplace",
                    ContactInfo     = "*****@*****.**"
                };

                options.Appearance.IncludeDate = false;
                options.Appearance.IncludeDistinguishedName = false;

                options.Appearance.NameLabel     = "Digital signiert von";
                options.Appearance.ReasonLabel   = "Grund:";
                options.Appearance.LocationLabel = "Ort:";

                pdf.SignAndSave(options, outputFileName);
            }

            Process.Start(outputFileName);
        }
Ejemplo n.º 8
0
        public void TestSignTest()
        {
            var src   = @"D:\temp\testSignatureService\BG.PDF";
            var dest  = @"D:\temp\testSignatureService\BG_Signed.PDF";
            var field = new PdfSignatureField()
            {
                name       = "signature1",
                x          = 100,
                y          = 100,
                width      = 100,
                height     = 100,
                reason     = "testJaaa",
                location   = "current location",
                page       = 1,
                thumbprint = "‎76 61 4a 24 85 76 46 4a 5b 13 75 3a e4 f3 31 4b 7b aa 79 62".Replace("‎", "").Replace(" ", "").ToUpper()
            };
            var result = PDFUtility.AddPdfSignatureField(File.ReadAllBytes(src), field);

            File.WriteAllBytes(dest, result);

            field = new PdfSignatureField()
            {
                name       = "signature2",
                x          = 200,
                y          = 200,
                width      = 100,
                height     = 100,
                reason     = "testJaaa2",
                location   = "location",
                page       = 1,
                thumbprint = "‎bc 97 b6 69 77 48 9c fb ca a0 78 58 38 19 c5 d6 1f 65 0c b8".Replace("‎", "").Replace(" ", "").ToUpper()
            };

            result = PDFUtility.AddPdfSignatureField(File.ReadAllBytes(dest), field);
            File.WriteAllBytes(dest, result);
        }
Ejemplo n.º 9
0
        private static void FillPDF(Dictionary <string, string> submittedFields, PdfDocument PDFDocument)
        {
            if (PDFDocument == null || PDFDocument.AcroForm == null)
            {
                throw new Exception("No PDF with fillable form submitted");
            }

            PdfAcroForm af = PDFDocument.AcroForm;


            //make sure fields are enabled
            if (af.Elements.ContainsKey(PdfAcroForm.Keys.NeedAppearances))
            {
                af.Elements[PdfAcroForm.Keys.NeedAppearances] = new PdfSharp.Pdf.PdfBoolean(true);
            }
            else
            {
                af.Elements.Add(PdfAcroForm.Keys.NeedAppearances, new PdfSharp.Pdf.PdfBoolean(true));
            }


            //Turn on unicode support
            XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode);

            //foreach (PDFField sField in submittedFields)
            foreach (KeyValuePair <string, string> sField in submittedFields)
            {
                try {
                    var field = af.Fields[sField.Key];
                    if (field is PdfTextField && (!sField.Key.EndsWith("_QRFill") && !sField.Key.EndsWith("_Code39Fill") && !sField.Key.EndsWith("_PDF417Fill")))
                    {
                        // filling in a text field
                        PdfTextField tf = (PdfTextField)field;

                        tf.ReadOnly = false;
                        if (Helper.IsChinese(sField.Value)) //override font if chinese is detected.
                        {
                            if (true)                       // remove evenatully - was used for switching different rendering methods
                            {
                                //Note: This will work for text Fields.. but make sure they are not linked (ie. multiple fileds with same name)
                                // If you want to make this more generic for all form fields you need to account for the possilbility
                                // that a form field could have several phyical outputs across multiple pages.  You can find the same
                                // properties but you need to check the KIDS collection for the field.  When there is only one display
                                // for a form field then the properties are rolled up to the form field itself - so the below works.
                                PdfRectangle rect = field.Elements.GetRectangle("/Rect");

                                if (tf.HasKids)
                                {
                                    throw new Exception("Multiple render locations found for text field" + sField.Key + ".  This can be supported, or just create separate fields for now.");
                                }

                                tf.Value = new PdfSharp.Pdf.PdfString(sField.Value, PdfStringEncoding.Unicode);

                                //also a bit of pain to locate the acutaly page the field is on... but OK.
                                XGraphics gfx = null;
                                foreach (var page in PDFDocument.Pages)
                                {
                                    if (page.Reference == field.Elements["/P"])
                                    {
                                        if (gfx != null)   //dispose of object before getting a new one.  Should actually never happen... but better safe than sorry....
                                        {
                                            gfx.Dispose();
                                        }
                                        gfx = XGraphics.FromPdfPage(page);
                                        break;
                                    }
                                }


                                XFont targetFont = new XFont("MicrosoftJhengHei", tf.Font.Size, XFontStyle.Regular, options);   //It's "KaigenSansSC" behind the scenes, but this may help with some rendering....
                                // Draw the text over the field
                                gfx.DrawString(sField.Value, targetFont, XBrushes.Black, new XRect(Math.Min(rect.X1, rect.X2), gfx.PageSize.Height - Math.Min(rect.Y1, rect.Y2) - Math.Abs(rect.Height), Math.Abs(rect.Width), Math.Abs(rect.Height)), XStringFormats.TopLeft);
                                gfx.Dispose();

                                //Theb hide the field
                                if (tf.Elements.ContainsKey("/F") == true)
                                {
                                    tf.Elements.SetInteger("/F", 6);
                                }


                                //original filling routine.. still kept here for refernce ... and since it will allow extracting form values from the PDF later.
                                tf.Font = targetFont;   // this is and the below is necessary to set both the view and edit font of the field.

                                if (tf.Elements.ContainsKey("/DA") == false)
                                {
                                    tf.Elements.Add(PdfTextField.Keys.DA, new PdfString($"/{targetFont.Name} {targetFont.Size} Tf 0 g"));
                                }
                                else
                                {
                                    tf.Elements[PdfTextField.Keys.DA] = new PdfString($"/{targetFont.Name} {targetFont.Size} Tf 0 g");
                                }
                            }
                        }
                        tf.Value = new PdfSharp.Pdf.PdfString(sField.Value, PdfStringEncoding.Unicode);
                    }
                    else if (field is PdfCheckBoxField)
                    {
                        if (sField.Value != null && sField.Value.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase))
                        {
                            ((PdfCheckBoxField)field).Checked = true;
                        }
                        else
                        {
                            ((PdfCheckBoxField)field).Checked = false;
                        }
                    }
                    else if (field is PdfComboBoxField)
                    {
                        ((PdfComboBoxField)field).Value = new PdfString(sField.Value);
                    }
                    else if (field is PdfRadioButtonField)
                    {
                        ((PdfRadioButtonField)field).Value = new PdfName(sField.Value);
                    }
                    else if (field is PdfListBoxField)
                    {
                        string[] items = sField.Value.Split(",");
                        //PdfSharp.Pdf.PdfArray paNew = new PdfSharp.Pdf.PdfArray();
                        PdfArray pas = (PdfArray)(((PdfListBoxField)field).Value);
                        //PdfItem[] pis = pas.Elements.Items;
                        pas.Elements.Clear();
                        foreach (string sitem in items)

                        {
                            pas.Elements.Add(new PdfString(sitem));
                        }


                        //PdfListBoxField pl = (PdfListBoxField)field;
                        //PdfSharp.Pdf.PdfArray pa = (PdfSharp.Pdf.PdfArray)pl.Value;
                        //string values = "";
                        //foreach (PdfString pi in pa.Elements.Items)
                        //{
                        //    if (values.Length > 0) values += ", ";
                        //    values += pi.Value;
                        //}
                        //dictPDFFields.Add(key, values);
                    }
                    else if (field is PdfSignatureField)
                    {
                        if (sField.Value == "")
                        {
                            continue;
                        }

                        //Note: The below wroks because a named singature fields only appear once in a document.
                        // If you want to make this more generic for all form fields you need to account for the possilbility
                        // that a form field could have several phyical outputs across multiple pages.  You can find the same
                        // properties but you need to check the KIDS collection for the field.  When there is only one display
                        // for a form field then the properties are rolled up to the form field itself - so the below works.
                        PdfSignatureField sig = (PdfSignatureField)field;
                        OverlayImageOnField(PDFDocument, sField.Value, sig.Elements.GetRectangle("/Rect"), sig.Elements["/P"]);
                    }
                    else if (field is PdfTextField && (sField.Key.EndsWith("_QRFill") || sField.Key.EndsWith("_Code39Fill") || sField.Key.EndsWith("_PDF417Fill")))
                    {
                        if (sField.Value == "")
                        {
                            continue;
                        }

                        //Note: This will work for text Fields.. but make sure they are not linked (ie. multiple fileds with same name)
                        // If you want to make this more generic for all form fields you need to account for the possilbility
                        // that a form field could have several phyical outputs across multiple pages.  You can find the same
                        // properties but you need to check the KIDS collection for the field.  When there is only one display
                        // for a form field then the properties are rolled up to the form field itself - so the below works.
                        PdfRectangle rect = field.Elements.GetRectangle("/Rect");

                        PdfTextField tf = (PdfTextField)field;

                        if (tf.HasKids)
                        {
                            throw new Exception("Multiple render locations found on barcode fill.  This can be supported, or just create separate fields for now.");
                        }

                        tf.Value = new PdfSharp.Pdf.PdfString(sField.Value, PdfStringEncoding.Unicode);

                        //This hides the field
                        if (tf.Elements.ContainsKey("/F") == true)
                        {
                            tf.Elements.SetInteger("/F", 6);
                        }

                        MessagingToolkit.Barcode.BarcodeEncoder benc = new BarcodeEncoder();
                        benc.Width  = Convert.ToInt32((rect.X2 - rect.X1) * 5); //I just made up that rule - but seems to work well for laser printers.
                        benc.Height = Convert.ToInt32((rect.Y2 - rect.Y1) * 5);

                        if (sField.Key.EndsWith("_Code39Fill"))
                        {
                            benc.Encode(BarcodeFormat.Code39, sField.Value);
                        }
                        else if (sField.Key.EndsWith("_PDF417Fill"))
                        {
                            benc.Encode(BarcodeFormat.PDF417, sField.Value);
                        }
                        else                                                                                            //_QRFill
                        {
                            benc.ErrorCorrectionLevel = MessagingToolkit.Barcode.QRCode.Decoder.ErrorCorrectionLevel.M; //M=15%  H=25% L=7% (default)
                            benc.Encode(BarcodeFormat.QRCode, sField.Value);
                        }

                        byte[] qrCodeAsPngByteArr = benc.GetImageData(SaveOptions.Png);
                        OverlayImageOnField(PDFDocument, qrCodeAsPngByteArr, rect, field.Elements["/P"]);
                    }
                } catch (Exception e) {
                    throw new Exception("Fill of Field '" + sField.Key + "' ('" + sField.Value + "') failed.  " + e.Message);
                }
            }
        }
Ejemplo n.º 10
0
 private static bool isInvisible(PdfSignatureField field)
 {
     return((field.Width == 0 && field.Height == 0) ||
            field.Flags.HasFlag(PdfWidgetFlags.Hidden) ||
            field.Flags.HasFlag(PdfWidgetFlags.NoView));
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Main method for running the sample.
        /// </summary>
        public static SampleOutputInfo[] Run()
        {
            PdfFixedDocument document = new PdfFixedDocument();
            PdfStandardFont helvetica = new PdfStandardFont(PdfStandardFontFace.Helvetica, 12);
            PdfBrush brush = new PdfBrush();

            PdfPage page = document.Pages.Add();

            // First name
            page.Graphics.DrawString("First name:", helvetica, brush, 50, 50);
            PdfTextBoxField firstNameTextBox = new PdfTextBoxField("firstname");
            page.Fields.Add(firstNameTextBox);
            firstNameTextBox.Widgets[0].Font = helvetica;
            firstNameTextBox.Widgets[0].VisualRectangle = new PdfVisualRectangle(150, 45, 200, 20);
            firstNameTextBox.Widgets[0].BorderColor = PdfRgbColor.Black;
            firstNameTextBox.Widgets[0].BorderWidth = 1;

            // Last name
            page.Graphics.DrawString("Last name:", helvetica, brush, 50, 80);
            PdfTextBoxField lastNameTextBox = new PdfTextBoxField("lastname");
            page.Fields.Add(lastNameTextBox);
            lastNameTextBox.Widgets[0].Font = helvetica;
            lastNameTextBox.Widgets[0].VisualRectangle = new PdfVisualRectangle(150, 75, 200, 20);
            lastNameTextBox.Widgets[0].BorderColor = PdfRgbColor.Black;
            lastNameTextBox.Widgets[0].BorderWidth = 1;

            // Sex
            page.Graphics.DrawString("Sex:", helvetica, brush, 50, 110);
            PdfRadioButtonField sexRadioButton = new PdfRadioButtonField("sex");
            PdfRadioButtonWidget maleRadioItem = new PdfRadioButtonWidget();
            sexRadioButton.Widgets.Add(maleRadioItem);
            PdfRadioButtonWidget femaleRadioItem = new PdfRadioButtonWidget();
            sexRadioButton.Widgets.Add(femaleRadioItem);
            page.Fields.Add(sexRadioButton);

            page.Graphics.DrawString("Male", helvetica, brush, 180, 110);
            maleRadioItem.ExportValue = "M";
            maleRadioItem.CheckStyle = PdfCheckStyle.Circle;
            maleRadioItem.VisualRectangle = new PdfVisualRectangle(150, 105, 20, 20);
            maleRadioItem.BorderColor = PdfRgbColor.Black;
            maleRadioItem.BorderWidth = 1;

            page.Graphics.DrawString("Female", helvetica, brush, 280, 110);
            femaleRadioItem.ExportValue = "F";
            femaleRadioItem.CheckStyle = PdfCheckStyle.Circle;
            femaleRadioItem.VisualRectangle = new PdfVisualRectangle(250, 105, 20, 20);
            femaleRadioItem.BorderColor = PdfRgbColor.Black;
            femaleRadioItem.BorderWidth = 1;

            // First car
            page.Graphics.DrawString("First car:", helvetica, brush, 50, 140);
            PdfComboBoxField firstCarList = new PdfComboBoxField("firstcar");
            firstCarList.Items.Add(new PdfListItem("Mercedes", "Mercedes"));
            firstCarList.Items.Add(new PdfListItem("BMW", "BMW"));
            firstCarList.Items.Add(new PdfListItem("Audi", "Audi"));
            firstCarList.Items.Add(new PdfListItem("Volkswagen", "Volkswagen"));
            firstCarList.Items.Add(new PdfListItem("Porsche", "Porsche"));
            firstCarList.Items.Add(new PdfListItem("Honda", "Honda"));
            firstCarList.Items.Add(new PdfListItem("Toyota", "Toyota"));
            firstCarList.Items.Add(new PdfListItem("Lexus", "Lexus"));
            firstCarList.Items.Add(new PdfListItem("Infiniti", "Infiniti"));
            firstCarList.Items.Add(new PdfListItem("Acura", "Acura"));
            page.Fields.Add(firstCarList);
            firstCarList.Widgets[0].Font = helvetica;
            firstCarList.Widgets[0].VisualRectangle = new PdfVisualRectangle(150, 135, 200, 20);
            firstCarList.Widgets[0].BorderColor = PdfRgbColor.Black;
            firstCarList.Widgets[0].BorderWidth = 1;

            // Second car
            page.Graphics.DrawString("Second car:", helvetica, brush, 50, 170);
            PdfListBoxField secondCarList = new PdfListBoxField("secondcar");
            secondCarList.Items.Add(new PdfListItem("Mercedes", "Mercedes"));
            secondCarList.Items.Add(new PdfListItem("BMW", "BMW"));
            secondCarList.Items.Add(new PdfListItem("Audi", "Audi"));
            secondCarList.Items.Add(new PdfListItem("Volkswagen", "Volkswagen"));
            secondCarList.Items.Add(new PdfListItem("Porsche", "Porsche"));
            secondCarList.Items.Add(new PdfListItem("Honda", "Honda"));
            secondCarList.Items.Add(new PdfListItem("Toyota", "Toyota"));
            secondCarList.Items.Add(new PdfListItem("Lexus", "Lexus"));
            secondCarList.Items.Add(new PdfListItem("Infiniti", "Infiniti"));
            secondCarList.Items.Add(new PdfListItem("Acura", "Acura"));
            page.Fields.Add(secondCarList);
            secondCarList.Widgets[0].Font = helvetica;
            secondCarList.Widgets[0].VisualRectangle = new PdfVisualRectangle(150, 165, 200, 60);
            secondCarList.Widgets[0].BorderColor = PdfRgbColor.Black;
            secondCarList.Widgets[0].BorderWidth = 1;

            // I agree
            page.Graphics.DrawString("I agree:", helvetica, brush, 50, 240);
            PdfCheckBoxField agreeCheckBox = new PdfCheckBoxField("agree");
            page.Fields.Add(agreeCheckBox);
            agreeCheckBox.Widgets[0].Font = helvetica;
            (agreeCheckBox.Widgets[0] as PdfCheckWidget).ExportValue = "YES";
            (agreeCheckBox.Widgets[0] as PdfCheckWidget).CheckStyle = PdfCheckStyle.Check;
            agreeCheckBox.Widgets[0].VisualRectangle = new PdfVisualRectangle(150, 235, 20, 20);
            agreeCheckBox.Widgets[0].BorderColor = PdfRgbColor.Black;
            agreeCheckBox.Widgets[0].BorderWidth = 1;

            // Sign here
            page.Graphics.DrawString("Sign here:", helvetica, brush, 50, 270);
            PdfSignatureField signHereField = new PdfSignatureField("signhere");
            page.Fields.Add(signHereField);
            signHereField.Widgets[0].Font = helvetica;
            signHereField.Widgets[0].VisualRectangle = new PdfVisualRectangle(150, 265, 200, 60);

            // Submit form
            PdfPushButtonField submitBtn = new PdfPushButtonField("submit");
            page.Fields.Add(submitBtn);
            submitBtn.Widgets[0].VisualRectangle = new PdfVisualRectangle(450, 45, 150, 30);
            (submitBtn.Widgets[0] as PdfPushButtonWidget).Caption = "Submit form";
            submitBtn.Widgets[0].BackgroundColor = PdfRgbColor.LightGray;
            PdfSubmitFormAction submitFormAction = new PdfSubmitFormAction();
            submitFormAction.DataFormat = PdfSubmitDataFormat.FDF;
            submitFormAction.Fields.Add("firstname");
            submitFormAction.Fields.Add("lastname");
            submitFormAction.Fields.Add("sex");
            submitFormAction.Fields.Add("firstcar");
            submitFormAction.Fields.Add("secondcar");
            submitFormAction.Fields.Add("agree");
            submitFormAction.Fields.Add("signhere");
            submitFormAction.SubmitFields = true;
            submitFormAction.Url = "http://www.xfiniumsoft.com/";
            submitBtn.Widgets[0].MouseUp = submitFormAction;

            // Reset form
            PdfPushButtonField resetBtn = new PdfPushButtonField("reset");
            page.Fields.Add(resetBtn);
            resetBtn.Widgets[0].VisualRectangle = new PdfVisualRectangle(450, 85, 150, 30);
            (resetBtn.Widgets[0] as PdfPushButtonWidget).Caption = "Reset form";
            resetBtn.Widgets[0].BackgroundColor = PdfRgbColor.LightGray;
            PdfResetFormAction resetFormAction = new PdfResetFormAction();
            resetBtn.Widgets[0].MouseUp = resetFormAction;

            // Print form
            PdfPushButtonField printBtn = new PdfPushButtonField("print");
            page.Fields.Add(printBtn);
            printBtn.Widgets[0].VisualRectangle = new PdfVisualRectangle(450, 125, 150, 30);
            (printBtn.Widgets[0] as PdfPushButtonWidget).Caption = "Print form";
            printBtn.Widgets[0].BackgroundColor = PdfRgbColor.LightGray;
            PdfJavaScriptAction printAction = new PdfJavaScriptAction();
            printAction.Script = "this.print(true);\n";
            printBtn.Widgets[0].MouseUp = printAction;

            SampleOutputInfo[] output = new SampleOutputInfo[] { new SampleOutputInfo(document, "xfinium.pdf.sample.formgenerator.pdf") };
            return output;
        }
        protected void btnSaveAsPDF_Click(object sender, EventArgs e)
        {
            //string inputUsername = Context.User.Identity.Name;
            //string inputUsername = Session["AccountUsername"].ToString();
            string rStatus = "accepted";

            dbCaseNumber = Session["caseNumberOfThisSelectedReport"].ToString();

            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["FileDatabaseConnectionString2"].ConnectionString);

            connection.Open();
            SqlCommand myCommand = new SqlCommand("SELECT CaseNumber, Username, Date, Subject, Description, Remarks, CreatedDateTime FROM Report WHERE ReportStatus = @reportStatus AND CaseNumber = @cNum", connection);

            //myCommand.Parameters.AddWithValue("@AccountUsername", inputUsername); //Taking the latest report of that user only. //Should be click on a particular report number - thats the report that we should take
            myCommand.Parameters.AddWithValue("@reportStatus", rStatus);
            myCommand.Parameters.AddWithValue("@cNum", dbCaseNumber);


            SqlDataReader myReader = myCommand.ExecuteReader();

            while (myReader.Read())
            {
                //dbCaseNumber = (myReader["CaseNumber"].ToString());
                dbUsername        = (myReader["Username"].ToString());
                dbDate            = (myReader["Date"].ToString());
                dbSubject         = (myReader["Subject"].ToString());
                dbDescription     = (myReader["Description"].ToString());
                dbRemarks         = (myReader["Remarks"].ToString());
                dbCreatedDateTime = (myReader["CreatedDateTime"].ToString());
            }
            connection.Close();

            //Creating a pdf document
            PdfDocument doc = new PdfDocument();

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

            //Draw the contents of page
            AlignText(page);

            // + Encryption (Joanne)
            doc.Security.KeySize       = PdfEncryptionKeySize.Key128Bit;
            doc.Security.OwnerPassword = "******";
            doc.Security.UserPassword  = PasswordTxt.Text;
            doc.Security.Permissions   = PdfPermissionsFlags.Print | PdfPermissionsFlags.FillFields;

            //// + DigitalSignature Method 1 (KaiTat)
            //String pfxPath = @"C:\\Program Files (x86)\\e-iceblue\\Spire.pdf\\Demos\\Data\\Demo.pfx";
            //PdfCertificate digi = new PdfCertificate(pfxPath, "e-iceblue");
            //PdfSignature signature = new PdfSignature(doc, page, digi, "demo");
            //signature.ContactInfo = "Harry Hu";
            //signature.Certificated = true;
            //signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill;

            //KT Digital Signature Method 2
            PdfSignatureField signaturefield = new PdfSignatureField(page, "Signature");

            signaturefield.BorderWidth   = 1.0f;
            signaturefield.BorderStyle   = PdfBorderStyle.Solid;
            signaturefield.BorderColor   = new PdfRGBColor(System.Drawing.Color.Black);
            signaturefield.HighlightMode = PdfHighlightMode.Outline;
            signaturefield.Bounds        = new RectangleF(350, 600, 100, 100);


            doc.Form.Fields.Add(signaturefield);



            // + Watermark - Text (Joanne)
            string wmText = "Report #" + dbCaseNumber + " by " + Context.User.Identity.Name;

            PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 2, page.Canvas.ClientSize.Height / 3));

            brush.Graphics.SetTransparency(0.3f);
            brush.Graphics.Save();
            brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
            brush.Graphics.RotateTransform(-45);
            brush.Graphics.DrawString(wmText, new PdfFont(PdfFontFamily.Helvetica, 20), PdfBrushes.Black, 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
            brush.Graphics.Restore();
            brush.Graphics.SetTransparency(1);
            page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(1, 1), page.Canvas.ClientSize));



            //Save pdf to a location
            //doc.SaveToFile("C:\\Users\\User\\Desktop\\CreatePDFTest" + dbCaseNumber + ".pdf");
            doc.SaveToFile("C:\\Saved PDF\\" + dbCaseNumber + ".pdf");
            //Kt testing
            //doc.SaveToFile("C:\\Users\\Kai Tat\\Desktop\\CreatePDFTest" + dbCaseNumber + ".pdf");


            //Launching the PDF File
            System.Diagnostics.Process.Start("C:\\Saved PDF\\" + dbCaseNumber + ".pdf");
            //Kt testing
            //System.Diagnostics.Process.Start("C:\\Users\\Kai Tat\\Desktop\\CreatePDFTest" + dbCaseNumber + ".pdf");


            //Add to logs
            ActionLogs.Action action = ActionLogs.Action.ReportSavedToPdf;
            ActionLogs.Log(Context.User.Identity.Name, action);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Main method for running the sample.
        /// </summary>
        public static SampleOutputInfo[] Run()
        {
            PdfFixedDocument document  = new PdfFixedDocument();
            PdfStandardFont  helvetica = new PdfStandardFont(PdfStandardFontFace.Helvetica, 12);
            PdfBrush         brush     = new PdfBrush();

            PdfPage page = document.Pages.Add();

            // First name
            page.Graphics.DrawString("First name:", helvetica, brush, 50, 50);
            PdfTextBoxField firstNameTextBox = new PdfTextBoxField("firstname");

            page.Fields.Add(firstNameTextBox);
            firstNameTextBox.Widgets[0].Font            = helvetica;
            firstNameTextBox.Widgets[0].VisualRectangle = new PdfVisualRectangle(150, 45, 200, 20);
            firstNameTextBox.Widgets[0].BorderColor     = PdfRgbColor.Black;
            firstNameTextBox.Widgets[0].BorderWidth     = 1;

            // Last name
            page.Graphics.DrawString("Last name:", helvetica, brush, 50, 80);
            PdfTextBoxField lastNameTextBox = new PdfTextBoxField("lastname");

            page.Fields.Add(lastNameTextBox);
            lastNameTextBox.Widgets[0].Font            = helvetica;
            lastNameTextBox.Widgets[0].VisualRectangle = new PdfVisualRectangle(150, 75, 200, 20);
            lastNameTextBox.Widgets[0].BorderColor     = PdfRgbColor.Black;
            lastNameTextBox.Widgets[0].BorderWidth     = 1;

            // Sex
            page.Graphics.DrawString("Sex:", helvetica, brush, 50, 110);
            PdfRadioButtonField  sexRadioButton = new PdfRadioButtonField("sex");
            PdfRadioButtonWidget maleRadioItem  = new PdfRadioButtonWidget();

            sexRadioButton.Widgets.Add(maleRadioItem);
            PdfRadioButtonWidget femaleRadioItem = new PdfRadioButtonWidget();

            sexRadioButton.Widgets.Add(femaleRadioItem);
            page.Fields.Add(sexRadioButton);

            page.Graphics.DrawString("Male", helvetica, brush, 180, 110);
            maleRadioItem.ExportValue     = "M";
            maleRadioItem.CheckStyle      = PdfCheckStyle.Circle;
            maleRadioItem.VisualRectangle = new PdfVisualRectangle(150, 105, 20, 20);
            maleRadioItem.BorderColor     = PdfRgbColor.Black;
            maleRadioItem.BorderWidth     = 1;

            page.Graphics.DrawString("Female", helvetica, brush, 280, 110);
            femaleRadioItem.ExportValue     = "F";
            femaleRadioItem.CheckStyle      = PdfCheckStyle.Circle;
            femaleRadioItem.VisualRectangle = new PdfVisualRectangle(250, 105, 20, 20);
            femaleRadioItem.BorderColor     = PdfRgbColor.Black;
            femaleRadioItem.BorderWidth     = 1;

            // First car
            page.Graphics.DrawString("First car:", helvetica, brush, 50, 140);
            PdfComboBoxField firstCarList = new PdfComboBoxField("firstcar");

            firstCarList.Items.Add(new PdfListItem("Mercedes", "Mercedes"));
            firstCarList.Items.Add(new PdfListItem("BMW", "BMW"));
            firstCarList.Items.Add(new PdfListItem("Audi", "Audi"));
            firstCarList.Items.Add(new PdfListItem("Volkswagen", "Volkswagen"));
            firstCarList.Items.Add(new PdfListItem("Porsche", "Porsche"));
            firstCarList.Items.Add(new PdfListItem("Honda", "Honda"));
            firstCarList.Items.Add(new PdfListItem("Toyota", "Toyota"));
            firstCarList.Items.Add(new PdfListItem("Lexus", "Lexus"));
            firstCarList.Items.Add(new PdfListItem("Infiniti", "Infiniti"));
            firstCarList.Items.Add(new PdfListItem("Acura", "Acura"));
            page.Fields.Add(firstCarList);
            firstCarList.Widgets[0].Font            = helvetica;
            firstCarList.Widgets[0].VisualRectangle = new PdfVisualRectangle(150, 135, 200, 20);
            firstCarList.Widgets[0].BorderColor     = PdfRgbColor.Black;
            firstCarList.Widgets[0].BorderWidth     = 1;

            // Second car
            page.Graphics.DrawString("Second car:", helvetica, brush, 50, 170);
            PdfListBoxField secondCarList = new PdfListBoxField("secondcar");

            secondCarList.Items.Add(new PdfListItem("Mercedes", "Mercedes"));
            secondCarList.Items.Add(new PdfListItem("BMW", "BMW"));
            secondCarList.Items.Add(new PdfListItem("Audi", "Audi"));
            secondCarList.Items.Add(new PdfListItem("Volkswagen", "Volkswagen"));
            secondCarList.Items.Add(new PdfListItem("Porsche", "Porsche"));
            secondCarList.Items.Add(new PdfListItem("Honda", "Honda"));
            secondCarList.Items.Add(new PdfListItem("Toyota", "Toyota"));
            secondCarList.Items.Add(new PdfListItem("Lexus", "Lexus"));
            secondCarList.Items.Add(new PdfListItem("Infiniti", "Infiniti"));
            secondCarList.Items.Add(new PdfListItem("Acura", "Acura"));
            page.Fields.Add(secondCarList);
            secondCarList.Widgets[0].Font            = helvetica;
            secondCarList.Widgets[0].VisualRectangle = new PdfVisualRectangle(150, 165, 200, 60);
            secondCarList.Widgets[0].BorderColor     = PdfRgbColor.Black;
            secondCarList.Widgets[0].BorderWidth     = 1;

            // I agree
            page.Graphics.DrawString("I agree:", helvetica, brush, 50, 240);
            PdfCheckBoxField agreeCheckBox = new PdfCheckBoxField("agree");

            page.Fields.Add(agreeCheckBox);
            agreeCheckBox.Widgets[0].Font = helvetica;
            (agreeCheckBox.Widgets[0] as PdfCheckWidget).ExportValue = "YES";
            (agreeCheckBox.Widgets[0] as PdfCheckWidget).CheckStyle  = PdfCheckStyle.Check;
            agreeCheckBox.Widgets[0].VisualRectangle = new PdfVisualRectangle(150, 235, 20, 20);
            agreeCheckBox.Widgets[0].BorderColor     = PdfRgbColor.Black;
            agreeCheckBox.Widgets[0].BorderWidth     = 1;

            // Sign here
            page.Graphics.DrawString("Sign here:", helvetica, brush, 50, 270);
            PdfSignatureField signHereField = new PdfSignatureField("signhere");

            page.Fields.Add(signHereField);
            signHereField.Widgets[0].Font            = helvetica;
            signHereField.Widgets[0].VisualRectangle = new PdfVisualRectangle(150, 265, 200, 60);

            // Submit form
            PdfPushButtonField submitBtn = new PdfPushButtonField("submit");

            page.Fields.Add(submitBtn);
            submitBtn.Widgets[0].VisualRectangle = new PdfVisualRectangle(450, 45, 150, 30);
            (submitBtn.Widgets[0] as PdfPushButtonWidget).Caption = "Submit form";
            submitBtn.Widgets[0].BackgroundColor = PdfRgbColor.LightGray;
            PdfSubmitFormAction submitFormAction = new PdfSubmitFormAction();

            submitFormAction.DataFormat = PdfSubmitDataFormat.FDF;
            submitFormAction.Fields.Add("firstname");
            submitFormAction.Fields.Add("lastname");
            submitFormAction.Fields.Add("sex");
            submitFormAction.Fields.Add("firstcar");
            submitFormAction.Fields.Add("secondcar");
            submitFormAction.Fields.Add("agree");
            submitFormAction.Fields.Add("signhere");
            submitFormAction.SubmitFields = true;
            submitFormAction.Url          = "http://www.xfiniumsoft.com/";
            submitBtn.Widgets[0].MouseUp  = submitFormAction;

            // Reset form
            PdfPushButtonField resetBtn = new PdfPushButtonField("reset");

            page.Fields.Add(resetBtn);
            resetBtn.Widgets[0].VisualRectangle = new PdfVisualRectangle(450, 85, 150, 30);
            (resetBtn.Widgets[0] as PdfPushButtonWidget).Caption = "Reset form";
            resetBtn.Widgets[0].BackgroundColor = PdfRgbColor.LightGray;
            PdfResetFormAction resetFormAction = new PdfResetFormAction();

            resetBtn.Widgets[0].MouseUp = resetFormAction;

            // Print form
            PdfPushButtonField printBtn = new PdfPushButtonField("print");

            page.Fields.Add(printBtn);
            printBtn.Widgets[0].VisualRectangle = new PdfVisualRectangle(450, 125, 150, 30);
            (printBtn.Widgets[0] as PdfPushButtonWidget).Caption = "Print form";
            printBtn.Widgets[0].BackgroundColor = PdfRgbColor.LightGray;
            PdfJavaScriptAction printAction = new PdfJavaScriptAction();

            printAction.Script          = "this.print(true);\n";
            printBtn.Widgets[0].MouseUp = printAction;

            SampleOutputInfo[] output = new SampleOutputInfo[] { new SampleOutputInfo(document, "xfinium.pdf.sample.formgenerator.pdf") };
            return(output);
        }
Ejemplo n.º 14
0
 private static CompositeProperty asCompositeProperty(PdfSignatureField o)
 {
     return(new CompositeProperty(o.Name, typeof(byte[])));
 }
Ejemplo n.º 15
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");
        }