public void Go()
        {
            using (PdfReader reader = new PdfReader(GetTestReader()))
            {
                var outputFile = Helpers.IO.GetClassOutputPath(this);

                using (var stream = new FileStream(outputFile, FileMode.Create))
                {
                    using (PdfStamper stamper = new PdfStamper(reader, stream))
                    {
                        AcroFields form        = stamper.AcroFields;
                        var        fldPosition = form.GetFieldPositions(NAME)[0];
                        Rectangle  rectangle   = fldPosition.position;
                        string     base64Image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
                        Regex      regex       = new Regex(@"^data:image/(?<mediaType>[^;]+);base64,(?<data>.*)");
                        Match      match       = regex.Match(base64Image);
                        Image      image       = Image.GetInstance(
                            Convert.FromBase64String(match.Groups["data"].Value)
                            );
                        // best fit if image bigger than form field
                        if (image.Height > rectangle.Height || image.Width > rectangle.Width)
                        {
                            image.ScaleAbsolute(rectangle);
                        }
                        // form field top left - change parameters as needed to set different position
                        image.SetAbsolutePosition(rectangle.Left + 2, rectangle.Top - 8);
                        stamper.GetOverContent(fldPosition.page).AddImage(image);
                    }
                }
            }
        }
Beispiel #2
0
// ---------------------------------------------------------------------------
        public byte[] FillTemplate(byte[] pdf, Movie movie)
        {
            using (MemoryStream ms = new MemoryStream()) {
                PdfReader reader = new PdfReader(pdf);
                using (PdfStamper stamper = new PdfStamper(reader, ms)) {
                    AcroFields form  = stamper.AcroFields;
                    BaseColor  color = WebColors.GetRGBColor(
                        "#" + movie.entry.category.color
                        );
                    PushbuttonField bt = form.GetNewPushbuttonFromField(POSTER);
                    bt.Layout           = PushbuttonField.LAYOUT_ICON_ONLY;
                    bt.ProportionalIcon = true;
                    bt.Image            = Image.GetInstance(Path.Combine(IMAGE, movie.Imdb + ".jpg"));
                    bt.BackgroundColor  = color;
                    form.ReplacePushbuttonField(POSTER, bt.Field);

                    PdfContentByte           canvas = stamper.GetOverContent(1);
                    float                    size   = 12;
                    AcroFields.FieldPosition f      = form.GetFieldPositions(TEXT)[0];
                    while (AddParagraph(CreateMovieParagraph(movie, size),
                                        canvas, f, true) && size > 6)
                    {
                        size -= 0.2f;
                    }
                    AddParagraph(CreateMovieParagraph(movie, size), canvas, f, false);

                    form.SetField(YEAR, movie.Year.ToString());
                    form.SetFieldProperty(YEAR, "bgcolor", color, null);
                    form.SetField(YEAR, movie.Year.ToString());
                    stamper.FormFlattening = true;
                }
                return(ms.ToArray());
            }
        }
        // would be nice if we could use ColumnText, but there's no way to get **remaining** text:
        // http://itext.2136553.n4.nabble.com/Remain-Text-on-ColumnText-td2146469.html
        public void FitSingleLine(AcroFields acroFields,
                                  string toFit, string fieldName,
                                  out string fits, out string overflows)
        {
            ValidateFitSingleLineText(acroFields, fieldName);

            var fieldWidth = acroFields.GetFieldPositions(fieldName)[0].position.Width;
            var fontSize   = GetFontSize(acroFields, fieldName);
            var baseFont   = GetStandardFont(acroFields, fieldName);

            var delimiter = Delimiter.ToString();
            var splitter  = new char[] { Delimiter };
            var split     = toFit.Split(splitter, StringSplitOptions.RemoveEmptyEntries)
                            .Select(x => x.Trim()).ToArray();

            var paddedWidth = fieldWidth - baseFont.GetWidthPoint("0", fontSize) * 2;

            int count = 0;

            for (; count < split.Length;)
            {
                string testString = string.Join(delimiter.ToString(), split.Take(++count).ToArray());
                var    testWidth  = baseFont.GetWidthPoint(testString, fontSize);
                if (paddedWidth < testWidth)
                {
                    --count;
                    break;
                }
            }

            fits      = string.Join(delimiter, split.Take(count).ToArray());
            overflows = string.Join(delimiter, split.Skip(count).Take(split.Length - count).ToArray());
        }
Beispiel #4
0
        public SignaturePermissions InspectSignature(AcroFields fields, String name, SignaturePermissions perms)
        {
            IList <AcroFields.FieldPosition> fps = fields.GetFieldPositions(name);

            if (fps != null && fps.Count > 0)
            {
                AcroFields.FieldPosition fp = fps[0];
                Rectangle pos = fp.position;
                if (pos.Width == 0 || pos.Height == 0)
                {
                    Console.WriteLine("Invisible signature");
                }
                else
                {
                    Console.WriteLine("Field on page {0}; llx: {1}, lly: {2}, urx: {3}; ury: {4}",
                                      fp.page, pos.Left, pos.Bottom, pos.Right, pos.Top);
                }
            }

            PdfPKCS7 pkcs7 = VerifySignature(fields, name);

            Console.WriteLine("Digest algorithm: " + pkcs7.GetHashAlgorithm());
            Console.WriteLine("Encryption algorithm: " + pkcs7.GetEncryptionAlgorithm());
            Console.WriteLine("Filter subtype: " + pkcs7.GetFilterSubtype());
            X509Certificate cert = pkcs7.SigningCertificate;

            Console.WriteLine("Name of the signer: " + CertificateInfo.GetSubjectFields(cert).GetField("CN"));
            if (pkcs7.SignName != null)
            {
                Console.WriteLine("Alternative name of the signer: " + pkcs7.SignName);
            }

            Console.WriteLine("Signed on: " + pkcs7.SignDate.ToString("yyyy-MM-dd HH:mm:ss.ff"));
            if (!pkcs7.TimeStampDate.Equals(DateTime.MaxValue))
            {
                Console.WriteLine("TimeStamp: " + pkcs7.TimeStampDate.ToString("yyyy-MM-dd HH:mm:ss.ff"));
                TimeStampToken ts = pkcs7.TimeStampToken;
                Console.WriteLine("TimeStamp service: " + ts.TimeStampInfo.Tsa);
                Console.WriteLine("Timestamp verified? " + pkcs7.VerifyTimestampImprint());
            }
            Console.WriteLine("Location: " + pkcs7.Location);
            Console.WriteLine("Reason: " + pkcs7.Reason);
            PdfDictionary sigDict = fields.GetSignatureDictionary(name);
            PdfString     contact = sigDict.GetAsString(PdfName.CONTACTINFO);

            if (contact != null)
            {
                Console.WriteLine("Contact info: " + contact);
            }
            perms = new SignaturePermissions(sigDict, perms);
            Console.WriteLine("Signature type: " + (perms.Certification ? "certification" : "approval"));
            Console.WriteLine("Filling out fields allowed: " + perms.FillInAllowed);
            Console.WriteLine("Adding annotations allowed: " + perms.AnnotationsAllowed);
            foreach (SignaturePermissions.FieldLock Lock in perms.FieldLocks)
            {
                Console.WriteLine("Lock: " + Lock);
            }
            return(perms);
        }
        /// <summary>
        /// 根据数据填充模板并获取一个一个pdf文件流
        /// </summary>
        /// <param name="listPara">数据参数</param>
        /// <returns>所有的pdf文件字节数组,并装在一个数组中</returns>
        public static List <byte[]> GetPdfs(List <Dictionary <string, string> > listPara)
        {
            //获取中文字体,第三个参数表示为是否潜入字体,但只要是编码字体就都会嵌入。
            BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);


            List <byte[]> pdfStreams = new List <byte[]>();

            foreach (Dictionary <string, string> para in listPara)
            {
                //读取模板文件
                PdfReader reader = new PdfReader(@"C:\Users\Administrator\Desktop\template.pdf");

                //创建文件流用来保存填充模板后的文件
                MemoryStream stream = new MemoryStream();

                PdfStamper stamp = new PdfStamper(reader, stream);

                stamp.AcroFields.AddSubstitutionFont(baseFont);

                AcroFields form = stamp.AcroFields;
                stamp.FormFlattening = true;//表单文本框锁定
                //填充表单
                foreach (KeyValuePair <string, string> parameter in para)
                {
                    //要输入中文就要设置域的字体;
                    form.SetFieldProperty(parameter.Key, "textfont", baseFont, null);
                    //为需要赋值的域设置值;
                    form.SetField(parameter.Key, parameter.Value);
                }

                //添加图片
                // 通过域名获取所在页和坐标,左下角为起点
                float[] positions = form.GetFieldPositions("sender");
                int     pageNo    = (int)positions[0];
                float   x         = positions[1];
                float   y         = positions[2];
                // 读图片
                Image image = Image.GetInstance(@"C:\Users\Administrator\Desktop\02.png");
                // 获取操作的页面
                PdfContentByte under = stamp.GetOverContent(pageNo);
                // 根据域的大小缩放图片
                image.ScaleToFit(positions[3] - positions[1], positions[4] - positions[2]);
                // 添加图片
                image.SetAbsolutePosition(x, y);
                under.AddImage(image);


                stamp.Close();
                reader.Close();

                byte[] result = stream.ToArray();
                pdfStreams.Add(result);
            }
            return(pdfStreams);
        }
Beispiel #6
0
        public float[] GetFieldPositions(string fieldName)
        {
            var output    = new float[5];
            var positions = pdfFormFields.GetFieldPositions(fieldName)[0];


            output[1] = positions.position.Left;
            output[2] = positions.position.Bottom;
            output[3] = positions.position.Right;
            output[4] = positions.position.Top;
            return(output);
        }
        /// <summary>
        /// METODO 3: Sostituire un acrofield di tipo signature con un acrofield di tipo checkbox
        /// Locking for a checkbox and checking it
        /// </summary>
        /// <param name="fieldName">string Name of the signaturefield to substitute</param>
        public void SubstituteSignature(string fieldName)
        {
            //Checking if argument is null
            if (fieldName == null)
            {
                throw new ArgumentNullException(fieldName);
            }

            //Getting fields
            AcroFields form = reader.AcroFields;

            //Checking if document has no fields
            if (form.Fields.Count == 0)
            {
                throw new DocumentHasNoFieldsException();
            }

            //Looking for a signatureBox with the given name
            var result = form.Fields
                         .Where(kvp =>
                                form.GetTranslatedFieldName(kvp.Key).Equals(fieldName) &&
                                form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_SIGNATURE
                                )
                         .Select(kvp => new { kvp.Key, Position = form.GetFieldPositions(kvp.Key) })
                         ?.FirstOrDefault();

            //Checking if the query had results
            if (result == null)
            {
                throw new FieldNotFoundException(fieldName, AcroFields.FIELD_TYPE_SIGNATURE);
            }

            //Removing field
            form.RemoveField(result.Key);

            //Creating new checkbox with signaturefield's coordinates
            //Note: We're replacing the first occurrence
            RadioCheckField checkbox = new RadioCheckField(stamper.Writer, result.Position[0].position, "i_was_a_signature_field", "Yes")
            {
                //Setting look
                CheckType       = RadioCheckField.TYPE_CHECK,
                Checked         = true,
                BorderWidth     = BaseField.BORDER_WIDTH_THIN,
                BorderColor     = BaseColor.BLACK,
                BackgroundColor = BaseColor.WHITE
            };

            //Adding checbox in signaturefield's page
            stamper.AddAnnotation(checkbox.CheckField, result.Position[0].page);
        }
Beispiel #8
0
        private void AssertSignaturePosition(string signatureName,
                                             int expectedPage, float expectedLeft, float expectedTop, float expectedWidth, float expectedHeight)
        {
            AcroFields fields = this.pdfReader.AcroFields;
            IList <AcroFields.FieldPosition> positions = fields.GetFieldPositions(signatureName);

            Assert.AreEqual(1, positions.Count());
            Assert.AreEqual(expectedPage, positions[0].page);
            Rectangle rectangle = positions[0].position;

            Assert.AreEqual(Math.Round(expectedLeft), Math.Round(rectangle.Left));
            Assert.AreEqual(Math.Round(expectedTop), Math.Round(rectangle.Top));
            Assert.AreEqual(Math.Round(expectedWidth), Math.Round(rectangle.Width));
            Assert.AreEqual(Math.Round(expectedHeight), Math.Round(rectangle.Height));
        }
Beispiel #9
0
        private static AcroFieldProperties GetAcroFieldProperties(AcroFields pdfForm, string acroFieldName, int pageNumber)
        {
            IList <AcroFields.FieldPosition> position = pdfForm.GetFieldPositions(acroFieldName);

            return(new AcroFieldProperties {
                Name = acroFieldName,
                Type = pdfForm.GetFieldType(acroFieldName),
                SelectOptions = pdfForm.GetSelectOptions(acroFieldName),
                Text = pdfForm.GetTextProperties(acroFieldName),
                PageNumber = pageNumber,
                LeftPos = position[0].position.Left,
                BottomPos = position[0].position.Bottom,
                RightPos = position[0].position.Right,
                TopPos = position[0].position.Top
            });
        }
        public void Go()
        {
            var           outputFile   = Helpers.IO.GetClassOutputPath(this);
            var           testField    = "title";
            var           testText     = "0";
            List <string> testTextList = new List <string>();

            for (int i = 1; i <= 76; ++i)
            {
                testTextList.Add(string.Format("{0}[{1}]", testText, i));
            }
            var   baseFont   = BaseFont.CreateFont();
            float testSize   = 8f;
            char  delimiter  = ',';
            var   testJoined = string.Join(delimiter.ToString(), testTextList.ToArray());

            using (var reader = Helpers.IO.GetInputReader(fileName))
            {
                using (var stream = new FileStream(outputFile, FileMode.Create))
                {
                    using (var stamper = new PdfStamper(reader, stream))
                    {
                        AcroFields fields = stamper.AcroFields;
                        var        width  = fields.GetFieldPositions("title")[0].position.Width;

                        fields.SetFieldProperty(
                            testField, "textfont", baseFont, null
                            );
                        fields.SetFieldProperty(
                            testField, "textsize", testSize, null
                            );

                        string fit;
                        string over;
                        Console.WriteLine("TEST STRING: {0}\n", testJoined);

                        FitSingleLine(fields, testJoined, "title", out fit, out over);
                        Console.WriteLine("fit: {0}\n", fit);
                        Console.WriteLine("over: {0}\n", over);

                        fields.SetField(testField, fit);
                    }
                }
            }
        }
        Queue <Tuple <string, string, string> > Fill109Rows(IEnumerable <MissionLog> logs, AcroFields fields, string fieldName)
        {
            AcroFields.Item item      = fields.GetFieldItem(fieldName);
            PdfDictionary   merged    = item.GetMerged(0);
            TextField       textField = new TextField(null, null, null);

            fields.DecodeGenericDictionary(merged, textField);

            var   collection = new Queue <Tuple <string, string, string> >();
            float fieldWidth = fields.GetFieldPositions(fieldName)[0].position.Width;
            float padRight   = textField.Font.GetWidthPoint("m", textField.FontSize);

            foreach (var log in logs)
            {
                if (log.Data == null)
                {
                    continue;
                }

                string formTime     = log.Time.ToString("HHmm");
                string formOperator = (log.Person ?? new Member()).LastName;

                foreach (var logMsg in log.Data.Replace("\r", "").Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    int left  = 0;
                    int right = logMsg.Length - 1;

                    while (left < right)
                    {
                        string part = logMsg.Substring(left, right - left + 1);
                        while (left < right && (textField.Font.GetWidthPoint(part, textField.FontSize) + padRight) > fieldWidth)
                        {
                            right = left + part.LastIndexOf(' ');
                            part  = logMsg.Substring(left, right - left);
                        }
                        collection.Enqueue(new Tuple <string, string, string>(formTime, part, formOperator));
                        formTime = "";
                        left     = right;
                        right    = logMsg.Length - 1;
                    }
                }
            }

            return(collection);
        }
Beispiel #12
0
        private static Rectangle GetDestinationRect(string pdfPath, int pageIndex)
        {
            using (PdfReader reader = new PdfReader(pdfPath))
            {
                reader.SelectPages(pageIndex.ToString());
                AcroFields af = reader.AcroFields;
                var        fieldDestination = af.Fields.SingleOrDefault(kv => kv.Key.Length == 2 && Char.IsNumber(kv.Key[1]));

                if (fieldDestination.Key == null)
                {
                    throw new Exception("No box found on the page");
                }

                var positions = af.GetFieldPositions(fieldDestination.Key);
                var destRect  = positions.First().position;
                return(destRect);
            }
        }
            string fill_field_by_chars(AcroFields form, string field_key, string text)
            {
                IList <AcroFields.FieldPosition> p = form.GetFieldPositions(field_key);
                float width = p[0].position.Width;

                text = FieldPreparation.Prepare(text);
                int end = 0;

                for (int e = 1; e <= text.Length; e++)
                {
                    float w = baseFont.GetWidthPoint(text.Substring(0, e).Trim(), (float)fontSize);
                    if (w > width)
                    {
                        break;
                    }
                    end = e;
                }
                set_field(form, field_key, text.Substring(0, end).Trim());
                return(text.Substring(end));
            }
            string fill_field_by_words(AcroFields form, string field_key, string text)
            {
                IList <AcroFields.FieldPosition> p = form.GetFieldPositions(field_key);
                float width = p[0].position.Width;

                text = FieldPreparation.Prepare(text);
                int end = 0;

                for (Match m = Regex.Match(text, @".+?([\-\,\:\.]+|(?=\s)|$)"); m.Success; m = m.NextMatch())
                {
                    int   e = m.Index + m.Length;
                    float w = baseFont.GetWidthPoint(text.Substring(0, e).Trim(), (float)fontSize);
                    if (w > width)
                    {
                        break;
                    }
                    end = e;
                }
                set_field(form, field_key, text.Substring(0, end).Trim());
                return(text.Substring(end));
            }
        public string GenerateMembercard(MemberCard card, string memberYear, string memberActive)
        {
            if (card == null || card.Member == null)
            {
                return(string.Empty);
            }
            string filename = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\Templates\\Pdf\\Template_Membercard.pdf";

            this.FilePath = Path.GetTempPath() + (object)Guid.NewGuid() + ".pdf";
            try
            {
                using (FileStream fileStream = new FileStream(this.FilePath, FileMode.Create))
                {
                    PdfReader  reader     = new PdfReader(filename);
                    PdfStamper pdfStamper = new PdfStamper(reader, (Stream)fileStream);
                    pdfStamper.Writer.CloseStream = false;
                    AcroFields acroFields = pdfStamper.AcroFields;
                    acroFields.SetField("txtName", card.Member.Fullname);
                    acroFields.SetField("txtYear", memberYear);
                    acroFields.SetField("txtMemberType", memberActive);
                    iTextSharp.text.Image     instance    = iTextSharp.text.Image.GetInstance(this.GenerateBarcode(card.Id), new BaseColor((int)byte.MaxValue, (int)byte.MaxValue, (int)byte.MaxValue));
                    PdfContentByte            overContent = pdfStamper.GetOverContent(1);
                    iTextSharp.text.Rectangle position    = acroFields.GetFieldPositions("txtQrCode").First <AcroFields.FieldPosition>().position;
                    instance.ScaleToFit(position.Width, position.Height);
                    instance.SetAbsolutePosition((float)((double)position.Right - (double)instance.ScaledWidth + ((double)position.Width - (double)instance.ScaledWidth) / 2.0), position.Bottom + (float)(((double)position.Height - (double)instance.ScaledHeight) / 2.0));
                    overContent.AddImage(instance);
                    pdfStamper.FormFlattening = true;
                    pdfStamper.Close();
                    reader.Close();
                    MembercardService.logger.Info("Membercard PDF created: " + this.FilePath);
                }
            }
            catch (IOException ex)
            {
                MembercardService.logger.Error("Could not create temporary PDF file:" + ex.Message);
                return(string.Empty);
            }
            return(this.FilePath);
        }
Beispiel #16
0
        private static void FillFormFields(PdfStamper pdfStamper, ConsularApptVM consularAppt)
        {
            AcroFields pdfFormFields = pdfStamper.AcroFields;

            pdfFormFields.SetField("Name", consularAppt.Name);
            pdfFormFields.SetField("PassportNumber", consularAppt.PassportNumber);
            pdfFormFields.SetField("AppointmentDate", String.Format("{0:dd MMM, yyyy [dddd]}", consularAppt.AppointmentDate));
            pdfFormFields.SetField("QueueNumber", consularAppt.QueueNumber.ToString());
            AppointmentType appointmentType = ConsularAppointmentTypes.GetAppointmentType(consularAppt.AppointmentType);

            pdfFormFields.SetField("ServiceType", appointmentType.Description);
            pdfFormFields.SetField("Name2", consularAppt.Name);
            pdfFormFields.SetField("PassportNumber2", consularAppt.PassportNumber);
            pdfFormFields.SetField("PhoneNumber", consularAppt.ContactPhone);
            pdfFormFields.SetField("Email", consularAppt.ContactEmail);
            iTextSharp.text.Image txtImage = null;
            using (var memStream = Graphics.GenerateQrCodeStream(GetQrCodeString(consularAppt)))
            {
                memStream.Position = 0;
                txtImage           = iTextSharp.text.Image.GetInstance(memStream);
            }

            var   fp     = pdfFormFields.GetFieldPositions("QRCode");
            float right  = fp[0].position.Right;
            float left   = fp[0].position.Left;
            float top    = fp[0].position.Top;
            float bottom = fp[0].position.Bottom;

            txtImage.ScaleToFit(115, 115);
            txtImage.SetAbsolutePosition(left, bottom);

            int            pageNum     = 1;
            PdfContentByte contentByte = pdfStamper.GetOverContent(pageNum);

            contentByte.AddImage(txtImage);

            pdfStamper.FormFlattening = false;
        }
Beispiel #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="testFile"></param>
        /// <param name="profile"></param>
        /// <param name="passwords"></param>
        /// <param name="numberOfSignatures"></param>
        /// <param name="allowMultisigning"></param>
        public static void TestSignature(string testFile, ConversionProfile profile, JobPasswords passwords, int numberOfSignatures, bool allowMultisigning)
        {
            PdfReader pdfReader;

            if (profile.PdfSettings.Security.Enabled)
            {
                if (profile.PdfSettings.Security.RequireUserPassword)
                {
                    pdfReader = new PdfReader(testFile, Encoding.Default.GetBytes(passwords.PdfUserPassword));
                }
                else
                {
                    pdfReader = new PdfReader(testFile, Encoding.Default.GetBytes(passwords.PdfOwnerPassword));
                }
            }
            else
            {
                pdfReader = new PdfReader(testFile);
            }

            AcroFields af = pdfReader.AcroFields;

            //Stop here if no Signing was requested
            if (!profile.PdfSettings.Signature.Enabled)
            {
                Assert.AreEqual(0, af.GetSignatureNames().Count, "SignatureName(s) in unsigned file." + Environment.NewLine + "(" + testFile + ")");
                return;
            }
            //Proceed with checking the number of signatures
            Assert.AreEqual(numberOfSignatures, af.GetSignatureNames().Count, "Number of SignatureNames must be " + numberOfSignatures + Environment.NewLine + "(" + testFile + ")");

            #region Verify the last or single signature in document, which must be always valid
            String   signatureName = af.GetSignatureNames()[numberOfSignatures - 1];
            PdfPKCS7 pk            = af.VerifySignature(signatureName);

            Assert.IsTrue(pk.Verify(), "(Last) Signature in document, is not valid.");
            Assert.IsTrue(af.SignatureCoversWholeDocument(signatureName), "(Last) signature in document, does not cover whole document.");

            TimeSpan ts = DateTime.Now.ToUniversalTime() - pk.TimeStampDate;
            Assert.IsTrue(Math.Abs(ts.TotalHours) < 1, "Time stamp has a difference bigger than 1h from now." + Environment.NewLine + "(" + testFile + ")");

            Assert.AreEqual(profile.PdfSettings.Signature.SignLocation, pk.Location, "Wrong SignLocation." + Environment.NewLine + "(" + testFile + ")");
            Assert.AreEqual(profile.PdfSettings.Signature.SignReason, pk.Reason, "Wrong SignReason." + Environment.NewLine + "(" + testFile + ")");

            if (profile.PdfSettings.Signature.DisplaySignatureInDocument)
            {
                switch (profile.PdfSettings.Signature.SignaturePage)
                {
                case SignaturePage.FirstPage:
                    Assert.AreEqual(1, af.GetFieldPositions(signatureName)[0].page, "Signature is not on the first page." + Environment.NewLine + "(" + testFile + ")");
                    break;

                case SignaturePage.CustomPage:
                    if (profile.PdfSettings.Signature.SignatureCustomPage > pdfReader.NumberOfPages)
                    {
                        Assert.AreEqual(pdfReader.NumberOfPages, af.GetFieldPositions(signatureName)[0].page, "Signature is not on the requested page." + Environment.NewLine + "(" + testFile + ")");
                    }
                    else
                    {
                        Assert.AreEqual(profile.PdfSettings.Signature.SignatureCustomPage, af.GetFieldPositions(signatureName)[0].page, "Signature is not on the requested page." + Environment.NewLine + "(" + testFile + ")");
                    }
                    break;

                case SignaturePage.LastPage:
                    Assert.AreEqual(pdfReader.NumberOfPages, af.GetFieldPositions(signatureName)[0].page, "Signature is not on the last Page." + Environment.NewLine + "(" + testFile + ")");
                    break;
                }
                Assert.AreEqual(profile.PdfSettings.Signature.LeftX, (int)af.GetFieldPositions(signatureName)[0].position.GetLeft(0), "Wrong position for LeftX." + Environment.NewLine + "(" + testFile + ")");
                Assert.AreEqual(profile.PdfSettings.Signature.LeftY, (int)af.GetFieldPositions(signatureName)[0].position.GetBottom(0), "Wrong position for LeftY." + Environment.NewLine + "(" + testFile + ")");
                Assert.AreEqual(profile.PdfSettings.Signature.RightX, (int)af.GetFieldPositions(signatureName)[0].position.GetRight(0), "Wrong position for RightX." + Environment.NewLine + "(" + testFile + ")");
                Assert.AreEqual(profile.PdfSettings.Signature.RightY, (int)af.GetFieldPositions(signatureName)[0].position.GetTop(0), "Wrong position for RightY." + Environment.NewLine + "(" + testFile + ")");
            }
            else
            {
                Assert.AreEqual(1, af.GetFieldPositions(signatureName)[0].page, "Wrong position for \"invisible\" signature." + Environment.NewLine + "(" + testFile + ")");
                Assert.AreEqual(0, (int)af.GetFieldPositions(signatureName)[0].position.GetLeft(0), "Wrong position for \"invisible\" signature." + Environment.NewLine + "(" + testFile + ")");
                Assert.AreEqual(0, (int)af.GetFieldPositions(signatureName)[0].position.GetBottom(0), "Wrong position for \"invisible\" signature." + Environment.NewLine + "(" + testFile + ")");
                Assert.AreEqual(0, (int)af.GetFieldPositions(signatureName)[0].position.GetRight(0), "Wrong position for \"invisible\" signature." + Environment.NewLine + "(" + testFile + ")");
                Assert.AreEqual(0, (int)af.GetFieldPositions(signatureName)[0].position.GetTop(0), "Wrong position for \"invisible\" signature." + Environment.NewLine + "(" + testFile + ")");
            }
            #endregion

            /*
             * var stamper = new PdfStamper(pdfReader, );
             *
             * if (profile.PdfSettings.Signature.AllowMultiSigning)
             *  Assert.AreEqual(0, stamper.SignatureAppearance);
             * else
             *  Assert.AreEqual(1, stamper.SignatureAppearance);
             *
             * stamper.Close();
             */

            /*
             * //Check validity of previous signatures. They must be valid if multi signing is allowed, otherwise they must be invalid.
             * for (int i = 1; i < numberOfSignatures; i++)
             * {
             *  String previousSignName = af.GetSignatureNames()[i-1];
             *  //PdfPKCS7 previousPk = af.VerifySignature(previousSignName);
             *
             *  if (allowMultisigning)
             *  {
             *      var sig = af.VerifySignature(previousSignName);
             *      Assert.IsTrue(sig.Verify(), "");
             *      Assert.IsTrue(af.SignatureCoversWholeDocument(previousSignName),
             *          "Last or single signature in document, does not cover whole document , although multi signing was enabled.");
             *  }
             *  else
             *  {
             *      var sig = af.VerifySignature(previousSignName);
             *      Assert.IsFalse(sig.Verify(), "");
             *      Assert.IsFalse(af.SignatureCoversWholeDocument(previousSignName),
             *          "Last or single signature in document, covers whole document , although multi signing was disabled.");
             *  }
             * }
             */
        }
Beispiel #18
0
        public async Task <JsonResult> GetDocumentMeta(string document_id) // Save the
        {
            try
            {
                Guid id;
                if (Guid.TryParse(document_id, out id))
                {
                    //Grab the desired file
                    Marine_Permit_Palace.Models.Document document = _DocumentSerivce.Get(id);
                    MemoryStream PDF_Mem = new MemoryStream();
                    MemoryStream file    = new MemoryStream(System.IO.File.ReadAllBytes(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "dist", "documents", document.TemplateName)));
                    file.CopyTo(PDF_Mem);
                    using (PdfReader reader = new PdfReader(System.IO.File.ReadAllBytes(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "dist", "documents", document.TemplateName))))
                        using (PdfStamper stamper = new PdfStamper(reader, PDF_Mem, '\0', false))
                        {
                            stamper.FormFlattening = false;
                            AcroFields pdfFormFields = stamper.AcroFields;
                            //AcroFields.FieldPosition

                            ApplicationUser user = await _UserManager.GetUserAsync(User);

                            if (user != null)
                            {
                                //populate all the known fields based on user information
                                //AutoFillManager.AutoFillBasedOnUser(user, pdfFormFields);
                            }

                            List <PDFPage> pages      = new List <PDFPage>();
                            List <string>  FieldNames = pdfFormFields.Fields.Select(e => e.Key).ToList();

                            foreach (string field in FieldNames)
                            {
                                var Position = pdfFormFields.GetFieldPositions(field).FirstOrDefault();
                                if (Position == null)
                                {
                                    continue;
                                }

                                if (pages.FirstOrDefault(e => e.page_number == Position.page) == null)
                                {
                                    pages.Add(new PDFPage()
                                    {
                                        page_number = Position.page, page = reader.GetPageSize(Position.page), document_meta = new List <DocumentMeta>()
                                    });
                                }

                                int indexOfPage = pages.FindIndex(e => e.page_number == Position.page);

                                string value = pdfFormFields.GetField(field);

                                string field_type;
                                switch (reader.AcroFields.GetFieldType(field))
                                {
                                case AcroFields.FIELD_TYPE_CHECKBOX:
                                    field_type = ("Checkbox");
                                    break;

                                case AcroFields.FIELD_TYPE_COMBO:
                                    field_type = ("Combobox");
                                    break;

                                case AcroFields.FIELD_TYPE_LIST:
                                    field_type = ("List");
                                    break;

                                case AcroFields.FIELD_TYPE_NONE:
                                    field_type = ("None");
                                    break;

                                case AcroFields.FIELD_TYPE_PUSHBUTTON:
                                    field_type = ("Pushbutton");
                                    break;

                                case AcroFields.FIELD_TYPE_RADIOBUTTON:
                                    field_type = ("Radiobutton");
                                    break;

                                case AcroFields.FIELD_TYPE_SIGNATURE:
                                    field_type = ("Signature");
                                    break;

                                case AcroFields.FIELD_TYPE_TEXT:
                                    field_type = ("Text");
                                    break;

                                default:
                                    field_type = ("?");
                                    break;
                                }
                                pages[indexOfPage].document_meta.Add(new DocumentMeta()
                                {
                                    field_name     = field,
                                    field_position = Position,
                                    value          = value,
                                    field_type     = field_type
                                });
                            }

                            return(Json(new
                            {
                                result = "Success",
                                status_code = 200,
                                pages
                            }));
                        }
                }
                else
                {
                    return(Json(new Result("Failure", "Incorrect Guid Format", 406)));
                }
            }
            catch (Exception ex)
            {
                return(Json(new Result()
                {
                    reason = $"Something went wrong while reading the file: See Exception...  {ex.Message}",
                    result = "Failure",
                    status_code = 500
                }));
            }
        }
Beispiel #19
0
        public async Task <JsonResult> GetSubmittedDocumentMeta(string submitted_document_id)
        {
            try
            {
                Guid id;
                if (Guid.TryParse(submitted_document_id, out id))
                {
                    //Grab the desired file
                    SubmittedDocument SubmittedDocument = _SubmittedDocumentService.GetPopulated(id);

                    ApplicationUser user = await _UserManager.GetUserAsync(User);

                    var DocAssignees    = _DocumentAsigneeService.GetByDocument(SubmittedDocument.IdSubmittedDocument);
                    var UserPermissions = DocAssignees.FirstOrDefault(e => e.IdAssigneeId == user.Id);
                    if (UserPermissions == null || !UserPermissions.IsActive)
                    {
                        return(Json(new Result()
                        {
                            reason = "User does not have permission to view this document",
                            result = "Failure",
                            status_code = 401
                        }));
                    }


                    Marine_Permit_Palace.Models.Document document = _DocumentSerivce.Get(SubmittedDocument.DocumentId);
                    MemoryStream PDF_Mem = new MemoryStream();
                    MemoryStream file    = new MemoryStream(System.IO.File.ReadAllBytes(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "dist", "documents", document.TemplateName)));
                    file.CopyTo(PDF_Mem);
                    using (PdfReader reader = new PdfReader(System.IO.File.ReadAllBytes(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "dist", "documents", document.TemplateName))))
                        using (PdfStamper stamper = new PdfStamper(reader, PDF_Mem, '\0', false))
                        {
                            stamper.FormFlattening = false;
                            AcroFields pdfFormFields = stamper.AcroFields;

                            if (user != null)
                            {
                                //populate all the known fields based on user information
                                AutoFillManager.AutoFillBasedOnUser(user, pdfFormFields);
                            }

                            string RequestingUserId = user.Id;

                            List <string> FieldNames = pdfFormFields.Fields.Select(e => e.Key).ToList();
                            //List<DocumentMeta> JsonDocument = new List<DocumentMeta>();
                            List <PDFPage> pages = new List <PDFPage>();
                            foreach (string field in FieldNames)
                            {
                                var Position = pdfFormFields.GetFieldPositions(field).FirstOrDefault();
                                if (Position == null)
                                {
                                    continue;
                                }

                                if (pages.FirstOrDefault(e => e.page_number == Position.page) == null)
                                {
                                    pages.Add(new PDFPage()
                                    {
                                        page_number = Position.page, page = reader.GetPageSize(Position.page), document_meta = new List <DocumentMeta>()
                                    });
                                }

                                int indexOfPage = pages.FindIndex(e => e.page_number == Position.page);


                                string field_type;
                                switch (reader.AcroFields.GetFieldType(field))
                                {
                                case AcroFields.FIELD_TYPE_CHECKBOX:
                                    field_type = ("Checkbox");
                                    break;

                                case AcroFields.FIELD_TYPE_COMBO:
                                    field_type = ("Combobox");
                                    break;

                                case AcroFields.FIELD_TYPE_LIST:
                                    field_type = ("List");
                                    break;

                                case AcroFields.FIELD_TYPE_NONE:
                                    field_type = ("None");
                                    break;

                                case AcroFields.FIELD_TYPE_PUSHBUTTON:
                                    field_type = ("Pushbutton");
                                    break;

                                case AcroFields.FIELD_TYPE_RADIOBUTTON:
                                    field_type = ("Radiobutton");
                                    break;

                                case AcroFields.FIELD_TYPE_SIGNATURE:
                                    field_type = ("Signature");
                                    break;

                                case AcroFields.FIELD_TYPE_TEXT:
                                    field_type = ("Text");
                                    break;

                                default:
                                    field_type = ("?");
                                    break;
                                }
                                string value, disabled_message = null;
                                bool   IsAllowedToEdit = true;

                                FieldData field_data    = SubmittedDocument[field];
                                var       AssigneeDodID = "";
                                if (field_data == null)
                                {
                                    value = pdfFormFields.GetField(field);
                                }
                                else
                                {
                                    value = field_data.value;
                                    if (!string.IsNullOrEmpty(field_data.user_assigned))
                                    {
                                        var OtherUser = await _UserManager.FindByIdAsync(field_data.user_assigned);

                                        if (OtherUser != null)
                                        {
                                            AssigneeDodID   = OtherUser.UserName;
                                            IsAllowedToEdit = RequestingUserId == field_data.user_assigned;
                                            if (!IsAllowedToEdit)
                                            {
                                                disabled_message = $"This field is assigned to {OtherUser.Rank}. {OtherUser.LastName}, {OtherUser.FirstName}";
                                            }
                                        }
                                    }
                                }

                                pages[indexOfPage].document_meta.Add(new DocumentMeta()
                                {
                                    field_name       = field,
                                    field_position   = Position,
                                    value            = value,
                                    field_type       = field_type,
                                    assigned_to      = AssigneeDodID,
                                    disabled_message = disabled_message,
                                    is_disabled      = !IsAllowedToEdit
                                });
                            }


                            return(Json(new
                            {
                                result = "Success",
                                status_code = 200,
                                pages
                            }));
                        }
                }
                else
                {
                    return(Json(new Result("Failure", "Incorrect Guid Format", 406)));
                }
            }
            catch (Exception ex)
            {
                return(Json(new Result()
                {
                    reason = $"Something went wrong while reading the file: See Exception...  {ex.Message}",
                    result = "Failure",
                    status_code = 500
                }));
            }
        }
Beispiel #20
0
        private static MessageReport.Signature InspectSignature(AcroFields fields, String name, SignaturePermissions perms)
        {
            MessageReport.Signature sigInfo = new MessageReport.Signature();

            IList <AcroFields.FieldPosition> fps = fields.GetFieldPositions(name);

            if (fps != null && fps.Count > 0)
            {
                AcroFields.FieldPosition fp = fps[0];
                Rectangle pos = fp.position;
                if (pos.Width == 0 || pos.Height == 0)
                {
                    sigInfo.visible = false;
                }
                else
                {
                    sigInfo.visible = true;
                }
            }

            PdfPKCS7 pkcs7 = VerifySignature(fields, name, ref sigInfo);

            sigInfo.digestAlgorithm     = pkcs7.GetHashAlgorithm();
            sigInfo.encryptionAlgorithm = pkcs7.GetEncryptionAlgorithm();
            sigInfo.isRevocationValid   = pkcs7.IsRevocationValid();


            X509Certificate cert = pkcs7.SigningCertificate;

            sigInfo.signerName = CertificateInfo.GetSubjectFields(cert).GetField("CN");

            if (pkcs7.SignName != null)
            {
                sigInfo.signerName = pkcs7.SignName;
            }

            sigInfo.signDate = pkcs7.SignDate.ToString("yyyy-MM-dd HH:mm:ss.ff");

            if (!pkcs7.TimeStampDate.Equals(DateTime.MaxValue))
            {
                sigInfo.isTimestampped = true;
                sigInfo.timestampDate  = pkcs7.TimeStampDate.ToString("yyyy-MM-dd HH:mm:ss.ff");

                TimeStampToken ts = pkcs7.TimeStampToken;
                sigInfo.timestampName = ts.TimeStampInfo.Tsa.ToString();
            }

            sigInfo.signLocation = pkcs7.Location;
            sigInfo.signReason   = pkcs7.Reason;

            PdfDictionary sigDict = fields.GetSignatureDictionary(name);
            PdfString     contact = sigDict.GetAsString(PdfName.CONTACTINFO);

            if (contact != null)
            {
                Console.WriteLine("Contact info: " + contact);
            }
            perms = new SignaturePermissions(sigDict, perms);

            sigInfo.signatureType = (perms.Certification ? "certification" : "approval");


            return(sigInfo);
        }
Beispiel #21
0
    public List <string> AddSignature(string svgString, string[] fileString)
    {
        List <string> savePaths = new List <string>();

        svgString = svgString.Split(',')[1];
        Byte[] bytes = Convert.FromBase64String(svgString);
        iTextSharp.text.Image itextImage = iTextSharp.text.Image.GetInstance(bytes);
        foreach (var file in fileString)
        {
            try
            {
                string fullPath       = System.Web.HttpContext.Current.Server.MapPath("~" + file.Replace(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath, ""));
                int    idx            = fullPath.LastIndexOf('.');
                int    idx2           = file.LastIndexOf('.');
                string fileEnd        = "_signed" + Path.GetRandomFileName() + ".pdf";
                string saveFileString = fullPath.Substring(0, idx) + fileEnd;
                string relSaveString  = file.Substring(0, idx2) + fileEnd;;
                using (Stream inputPdfStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read))


                    using (Stream outputPdfStream = new FileStream(saveFileString, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        var reader         = new PdfReader(inputPdfStream);
                        var stamper        = new PdfStamper(reader, outputPdfStream);
                        var pdfContentByte = stamper.GetOverContent(1);

                        AcroFields formFields = stamper.AcroFields;
                        if (formFields.Fields.ContainsKey("signature"))
                        {
                            int i = 0;
                            foreach (var field in formFields.Fields)
                            {
                                if (field.Key == "signature")
                                {
                                    AcroFields.FieldPosition f = formFields.GetFieldPositions(field.Key)[i];
                                    int page = formFields.GetFieldPositions(field.Key)[i].page;//get(i).page;
                                    formFields.SetField("Start_date", DateTime.Now.ToString("yyyy/MM/dd"));
                                    iTextSharp.text.Rectangle rect = f.position;
                                    itextImage.ScaleToFit(rect.Width, rect.Height);
                                    int p = reader.NumberOfPages;

                                    itextImage.SetAbsolutePosition(rect.Left, rect.Bottom);
                                    i++;
                                    pdfContentByte = stamper.GetOverContent(page);
                                    pdfContentByte.AddImage(itextImage);
                                }
                            }
                        }
                        stamper.FormFlattening = true;
                        stamper.Close();
                    }
                System.IO.File.Delete(fullPath);
                savePaths.Add(relSaveString);
            }
            catch (Exception ex)
            {
                // write to log
                throw (ex);
            }
        }
        return(savePaths);
    }
Beispiel #22
0
        public static void FillInPdfTemplateFields(string templatPath, Stream pdfOut, Dictionary <string, string> hashTable, byte[] qrCode, bool isEncrypt)
        {
            PdfReader  pdfReader  = new PdfReader(templatPath);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, pdfOut);

            try
            {
                if (isEncrypt)
                {
                    pdfStamper.SetEncryption(PdfWriter.STRENGTH40BITS, null, null, PdfWriter.AllowPrinting);
                }

                StreamUtil.AddToResourceSearch(Assembly.Load("iTextAsian"));
                BaseFont font = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

                AcroFields pdfFormFields = pdfStamper.AcroFields;
                foreach (KeyValuePair <string, AcroFields.Item> de in pdfFormFields.Fields)
                {
                    string fieldKey = de.Key.ToString();
                    if (string.IsNullOrWhiteSpace(fieldKey))
                    {
                        continue;
                    }

                    if (fieldKey.Contains("img_"))
                    {
                        int    page   = Convert.ToInt32(fieldKey.Split('_')[1]);
                        string hasKey = fieldKey.Split('_')[2];
                        //if (hashTable.ContainsKey(hasKey))
                        //{
                        IList <AcroFields.FieldPosition> fieldPositions = pdfFormFields.GetFieldPositions(fieldKey);
                        AcroFields.FieldPosition         fieldPosition  = fieldPositions[0];
                        iTextSharp.text.Image            image          = iTextSharp.text.Image.GetInstance(qrCode);
                        image.ScaleToFit(fieldPosition.position.Width, fieldPosition.position.Height);
                        float x = fieldPosition.position.Left;
                        float y = fieldPosition.position.Top - image.ScaledHeight;
                        image.SetAbsolutePosition(x, y);
                        var pdfContentByte = pdfStamper.GetOverContent(page);
                        pdfContentByte.AddImage(image);
                        //}
                    }
                    else if (hashTable.ContainsKey(fieldKey))
                    {
                        pdfFormFields.SetFieldProperty(fieldKey, "textfont", font, null);
                        string fieldValue = hashTable[fieldKey];
                        if (string.IsNullOrWhiteSpace(fieldValue))
                        {
                            fieldValue = string.Empty;
                        }
                        pdfFormFields.SetField(fieldKey, fieldValue);
                    }
                }

                pdfStamper.FormFlattening = true;
            }
            catch (Exception)
            {
            }
            finally
            {
                pdfStamper.Close();
                pdfReader.Close();
            }
        }
Beispiel #23
0
        public void SignPDF(string SignaturePath)
        {
            float[] ApplicantSignature01 = null;
            float[] ApplicantSignature02 = null;
            float[] ApplicantSignature03 = null;
            ApplicantSignature01 = pdfFormFields.GetFieldPositions("applicantsignature01");
            ApplicantSignature02 = pdfFormFields.GetFieldPositions("applicantsignature02");
            ApplicantSignature03 = pdfFormFields.GetFieldPositions("applicantsignature03");

            iTextSharp.text.Image mySignature01 = iTextSharp.text.Image.GetInstance(SignaturePath);
            iTextSharp.text.Image mySignature02 = iTextSharp.text.Image.GetInstance(SignaturePath);
            iTextSharp.text.Image mySignature03 = iTextSharp.text.Image.GetInstance(SignaturePath);
            iTextSharp.text.Image mySignature04 = iTextSharp.text.Image.GetInstance(SignaturePath);

//Place applicantsignature01 ***************************************
            //Scale Image
            mySignature01.ScaleToFit(ApplicantSignature01[3] - ApplicantSignature01[1], ApplicantSignature01[4] - ApplicantSignature01[2]);
            //Set Position
            mySignature01.SetAbsolutePosition(ApplicantSignature01[1] +
                                              ((ApplicantSignature01[3] - ApplicantSignature01[1]) - mySignature01.ScaledWidth) / 2, ApplicantSignature01[4] - mySignature01.ScaledHeight);

            //Place Image
            PdfContentByte contentByte = pdfStamper.GetOverContent((int)ApplicantSignature01[0]);

            contentByte.AddImage(mySignature01);

//Place applicantsignature02 ***************************************
            //Scale Image
            mySignature02.ScaleToFit(ApplicantSignature02[3] - ApplicantSignature02[1], ApplicantSignature02[4] - ApplicantSignature02[2]);
            //Set Position
            mySignature02.SetAbsolutePosition(ApplicantSignature02[1] +
                                              ((ApplicantSignature02[3] - ApplicantSignature02[1]) - mySignature02.ScaledWidth) / 2, ApplicantSignature02[4] - mySignature02.ScaledHeight);

            //Place Image
            contentByte = pdfStamper.GetOverContent((int)ApplicantSignature02[0]);
            contentByte.AddImage(mySignature02);

//Place applicantsignature03 ***************************************
            //Scale Image
            mySignature03.ScaleToFit(ApplicantSignature03[3] - ApplicantSignature03[1], ApplicantSignature03[4] - ApplicantSignature03[2]);
            //Set Position
            mySignature03.SetAbsolutePosition(ApplicantSignature03[1] +
                                              ((ApplicantSignature03[3] - ApplicantSignature03[1]) - mySignature03.ScaledWidth) / 2, ApplicantSignature03[4] - mySignature03.ScaledHeight);

            //Place Image
            contentByte = pdfStamper.GetOverContent((int)ApplicantSignature03[0]);
            contentByte.AddImage(mySignature03);

//Place Signature on Additional Pages
            float[] SignaturePort = null;
            SignaturePort = pdfFormFields.GetFieldPositions("SignaturePort");
            if (SignaturePort != null)
            {
                int numsigs = SignaturePort.Length / 5;
                for (int i = 0; i < numsigs; i++)
                {
                    mySignature04.ScaleToFit(SignaturePort[3 + (i * 5)] - SignaturePort[1 + (i * 5)], SignaturePort[4 + (i * 5)] - SignaturePort[2 + (i * 5)]);
                    //Set Position
                    mySignature04.SetAbsolutePosition(SignaturePort[1] +
                                                      ((SignaturePort[3 + (i * 5)] - SignaturePort[1 + (i * 5)]) - mySignature04.ScaledWidth) / 2, SignaturePort[4 + (i * 5)] - mySignature04.ScaledHeight);

                    //Place Image
                    contentByte = pdfStamper.GetOverContent((int)SignaturePort[i * 5]);
                    contentByte.AddImage(mySignature04);
                }
            }

            pdfFormFields.SetField("appdate", DateTime.Now.ToShortDateString());
        }
Beispiel #24
0
        public void SetEvisaArabicFieldValue(string fieldName, string fieldValue)
        {
            try
            {
                _reader       = new PdfReader(fileName);
                pdfFormFields = _reader.AcroFields;
                var field = pdfFormFields.GetFieldItem(fieldName).GetValue(0);
                Console.WriteLine(field.ToString());
                var outfileName = fileName.Replace(".pdf", DateTime.Now.Ticks + ".pdf");
                _pdfStamper = new PdfStamper(_reader, new FileStream(outfileName, FileMode.Create));

                var ARIALUNI_TFF =
                    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "trado.TTF");
                var bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                var f  = new iTextSharp.text.Font(bf);

                var overContent   = _pdfStamper.GetOverContent(1); //1 means page 1
                var fieldPosition = pdfFormFields.GetFieldPositions(fieldName)[0].position;

                var ct = new ColumnText(overContent)
                {
                    RunDirection = PdfWriter.RUN_DIRECTION_RTL, YLine = 5
                };
                if (rdCenter.Checked)
                {
                    ct.SetSimpleColumn(fieldPosition.Left, fieldPosition.Bottom - fieldPosition.Height / 2,
                                       fieldPosition.Right, fieldPosition.Top - fieldPosition.Height / 2, 0, Element.ALIGN_CENTER);
                }
                else if (rdRight.Checked)
                {
                    ct.SetSimpleColumn(fieldPosition.Left, fieldPosition.Bottom - fieldPosition.Height / 2,
                                       fieldPosition.Right, fieldPosition.Top - fieldPosition.Height / 2, 0, Element.ALIGN_RIGHT);
                }
                if (rdLeft.Checked)
                {
                    ct.SetSimpleColumn(fieldPosition.Left, fieldPosition.Bottom - fieldPosition.Height / 2,
                                       fieldPosition.Right, fieldPosition.Top - fieldPosition.Height / 2, 0, Element.ALIGN_LEFT);
                }
                if (rdUseFieldAlignment.Checked)
                {
                    ct.SetSimpleColumn(fieldPosition.Left, fieldPosition.Bottom - fieldPosition.Height / 2,
                                       fieldPosition.Right, fieldPosition.Top - fieldPosition.Height / 2, 0, Element.ALIGN_LEFT);
                }

                ct.SetText(new Phrase(fieldValue, f));
                ct.Go();

                //uncomment to draw rectangle
                //var rect = new iTextSharp.text.Rectangle(fieldPosition.Left, fieldPosition.Bottom - fieldPosition.Height / 2, fieldPosition.Right, fieldPosition.Top - fieldPosition.Height / 2);
                //rect.Border = iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER;
                //rect.BorderWidth = 5;
                //rect.BorderColor = new BaseColor(0, 0, 0);

                //overContent.Rectangle(rect);
                _pdfStamper.Close();
                Process.Start(outfileName);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
Beispiel #25
0
        /// <summary>
        /// Handles the Click event of the BtnGenerateReport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void BtnGenerateReport_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtPDFFile.Text))
            {
                _formFields.Clear();

                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (FileStream fs = File.OpenRead(txtPDFFile.Text))
                        {
                            fs.CopyTo(ms);
                        }

                        PdfReader.unethicalreading = true;
                        PdfReader  pdfReader     = new PdfReader(ms.ToArray());
                        AcroFields pdfFormFields = pdfReader.AcroFields;

                        foreach (KeyValuePair <string, AcroFields.Item> kvp in pdfFormFields.Fields)
                        {
                            FormField formField = new FormField
                            {
                                FieldName  = pdfFormFields.GetTranslatedFieldName(kvp.Key),
                                FieldValue = pdfFormFields.GetField(kvp.Key),
                                FieldType  = GetFormFieldType(pdfFormFields.GetFieldType(kvp.Key))
                            };

                            AcroFields.Item field  = pdfFormFields.GetFieldItem(kvp.Key);
                            PdfDictionary   merged = field.GetMerged(0);
                            TextField       fld    = new TextField(null, null, null);
                            pdfFormFields.DecodeGenericDictionary(merged, fld);

                            formField.FontName = GetFontName(fld.Font);
                            string fontSize = (fld.FontSize == 0.0f) ? "Auto" : fld.FontSize.ToString();
                            formField.FontSize = fontSize;

                            List <AcroFields.FieldPosition> fieldPositions = pdfFormFields.GetFieldPositions(kvp.Key).ToList();
                            float pageHeight = pdfReader.GetPageSizeWithRotation(fieldPositions[0].page).Height;
                            formField.FieldPositionTop    = (pageHeight - fieldPositions[0].position.Top);
                            formField.FieldPositionBottom = (pageHeight - fieldPositions[0].position.Bottom);
                            formField.FieldPositionLeft   = fieldPositions[0].position.Left;
                            formField.FieldPositionRight  = fieldPositions[0].position.Right;
                            formField.FieldHeight         = fieldPositions[0].position.Height;
                            formField.FieldWidth          = fieldPositions[0].position.Width;
                            formField.PageNumber          = fieldPositions[0].page;

                            _formFields.Add(formField);
                        }

                        GenerateTreeViewDisplay();
                        pnlSaveOptions.Enabled = true;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("There was an issue with processing the request. Message: \n\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    pnlSaveOptions.Enabled = pnlSaveOptions.Enabled ? true : false;
                }
            }
        }
Beispiel #26
0
        private void MakeSigningTest()
        {
            PdfReader pdfReader;

            if (_th.Profile.PdfSettings.Security.Enabled)
            {
                if (_th.Profile.PdfSettings.Security.RequireUserPassword)
                {
                    pdfReader = new PdfReader(_th.Job.OutputFiles[0], Encoding.Default.GetBytes(_th.Job.Passwords.PdfUserPassword));
                }
                else
                {
                    pdfReader = new PdfReader(_th.Job.OutputFiles[0], Encoding.Default.GetBytes(_th.Job.Passwords.PdfOwnerPassword));
                }
            }
            else
            {
                pdfReader = new PdfReader(_th.Job.OutputFiles[0]);
            }
            AcroFields af = pdfReader.AcroFields;

            //Stop here if no Signing was requested
            if (!_th.Profile.PdfSettings.Signature.Enabled)
            {
                Assert.AreEqual(0, af.GetSignatureNames().Count, "SignatureName(s) in unsingned file.");
                return;
            }
            //Go on to verify the Signature
            Assert.AreEqual(1, af.GetSignatureNames().Count, "Number of SignatureNames must be 1.");

            String   signName = af.GetSignatureNames()[0];
            PdfPKCS7 pk       = af.VerifySignature(signName);

            var      now = DateTime.UtcNow;
            TimeSpan ts  = now - pk.TimeStampDate;

            Assert.IsTrue(Math.Abs(ts.TotalMinutes) < 30, "Timestamp has a difference, bigger than 1h from now. Now is {0}, signature timestamp: {1}, difference: {2}", now, pk.TimeStampDate, ts);

            Assert.AreEqual(_th.Profile.PdfSettings.Signature.SignLocation, pk.Location, "Wrong SignLocation");
            Assert.AreEqual(_th.Profile.PdfSettings.Signature.SignReason, pk.Reason, "Wrong SignReason");

            if (_th.Profile.PdfSettings.Signature.DisplaySignatureInDocument)
            {
                switch (_th.Profile.PdfSettings.Signature.SignaturePage)
                {
                case SignaturePage.FirstPage:
                    Assert.AreEqual(1, af.GetFieldPositions(signName)[0].page, "Signature is not on the first page");
                    break;

                case SignaturePage.CustomPage:
                    if (_th.Profile.PdfSettings.Signature.SignatureCustomPage > pdfReader.NumberOfPages)
                    {
                        Assert.AreEqual(pdfReader.NumberOfPages, af.GetFieldPositions(signName)[0].page, "Signature is not on requested page");
                    }
                    else
                    {
                        Assert.AreEqual(_th.Profile.PdfSettings.Signature.SignatureCustomPage, af.GetFieldPositions(signName)[0].page, "Signature is not on requested page");
                    }
                    break;

                case SignaturePage.LastPage:
                    Assert.AreEqual(pdfReader.NumberOfPages, af.GetFieldPositions(signName)[0].page, "Signature is not on last Page");
                    break;
                }
                Assert.AreEqual(_th.Profile.PdfSettings.Signature.LeftX, (int)af.GetFieldPositions(signName)[0].position.GetLeft(0), "Wrong Position for LeftX");
                Assert.AreEqual(_th.Profile.PdfSettings.Signature.LeftY, (int)af.GetFieldPositions(signName)[0].position.GetBottom(0), "Wrong Position for LeftY");
                Assert.AreEqual(_th.Profile.PdfSettings.Signature.RightX, (int)af.GetFieldPositions(signName)[0].position.GetRight(0), "Wrong Position for RightX");
                Assert.AreEqual(_th.Profile.PdfSettings.Signature.RightY, (int)af.GetFieldPositions(signName)[0].position.GetTop(0), "Wrong Position for RightY");
            }
            else
            {
                Assert.AreEqual(1, af.GetFieldPositions(signName)[0].page, "Wrong position for \"invisible\" signature");
                Assert.AreEqual(0, (int)af.GetFieldPositions(signName)[0].position.GetLeft(0), "Wrong position for \"invisible\" signature");
                Assert.AreEqual(0, (int)af.GetFieldPositions(signName)[0].position.GetBottom(0), "Wrong position for \"invisible\" signature");
                Assert.AreEqual(0, (int)af.GetFieldPositions(signName)[0].position.GetRight(0), "Wrong position for \"invisible\" signature");
                Assert.AreEqual(0, (int)af.GetFieldPositions(signName)[0].position.GetTop(0), "Wrong position for \"invisible\" signature");
            }
        }