Exemplo n.º 1
0
        //Calc totals for each budget sheet
        void calcTotals(userInfo user, DateTime startD, DateTime endD, IDictionary <string, PdfFormField> coverFields, PdfFormField toSet)
        {
            //Fill in the sums
            for (int i = 1; i <= 7; i++)
            {
                double totalSum = 0.0;
                for (int j = 1; j <= 31; j++)
                {
                    coverFields.TryGetValue("PG" + i + "_Hours" + j, out toSet);
                    var tempVal = toSet.GetValue();
                    if (tempVal != null)
                    {
                        totalSum += Convert.ToDouble(tempVal.ToString());
                    }
                }

                coverFields.TryGetValue("sumpage" + i, out toSet);
                toSet.SetValue(totalSum.ToString("F2"));
            }

            //Fill SumTotal field
            double total = 0.0;

            for (int i = 1; i <= 31; i++)
            {
                coverFields.TryGetValue("SumRow" + i, out toSet);
                var temp = toSet.GetValue();
                if (temp != null)
                {
                    total += Convert.ToDouble(temp.ToString());
                }
            }

            coverFields.TryGetValue("SumTotal", out toSet);
            toSet.SetValue(total.ToString("F2"));

            for (int i = 1; i <= 5; i++)
            {
                coverFields.TryGetValue("sumpage" + i, out toSet);
                string val = toSet.GetValueAsString();

                if (!(val == "" || val == "0.00"))
                {
                    coverFields.TryGetValue("PG" + i + "_Budget Code 2", out toSet);
                    string budFileName = toSet.GetValueAsString();

                    if (!(budFileName == null || budFileName == ""))
                    {
                        budFileName = createPDFFileName(user, budFileName, startD);
                        createSignTimeSheet(user, startD, endD, i, budFileName, coverFields);
                    }
                }
            }
        }
Exemplo n.º 2
0
 /// <summary>Sets the name indicating the field to be signed.</summary>
 /// <remarks>
 /// Sets the name indicating the field to be signed. The field can already be presented in the
 /// document but shall not be signed. If the field is not presented in the document, it will be created.
 /// </remarks>
 /// <param name="fieldName">The name indicating the field to be signed.</param>
 public virtual void SetFieldName(String fieldName)
 {
     if (fieldName != null)
     {
         if (fieldName.IndexOf('.') >= 0)
         {
             throw new ArgumentException(PdfException.FieldNamesCannotContainADot);
         }
         PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(document, true);
         if (acroForm.GetField(fieldName) != null)
         {
             PdfFormField field = acroForm.GetField(fieldName);
             if (!PdfName.Sig.Equals(field.GetFormType()))
             {
                 throw new ArgumentException(PdfException.FieldTypeIsNotASignatureFieldType);
             }
             if (field.GetValue() != null)
             {
                 throw new ArgumentException(PdfException.FieldAlreadySigned);
             }
             appearance.SetFieldName(fieldName);
             IList <PdfWidgetAnnotation> widgets = field.GetWidgets();
             if (widgets.Count > 0)
             {
                 PdfWidgetAnnotation widget = widgets[0];
                 appearance.SetPageRect(GetWidgetRectangle(widget));
                 appearance.SetPageNumber(GetWidgetPageNumber(widget));
             }
         }
         this.fieldName = fieldName;
     }
 }
Exemplo n.º 3
0
        private static void GetFormFieldProperties(PdfPage page, PdfWidgetAnnot widget, PdfFormField field)
        {
            Console.WriteLine("===========================================");
            if (field != null)
            {
                Console.WriteLine("Name: " + field.GetFullName());
                Console.WriteLine("Value: " + field.GetValue());
                Console.WriteLine("Tooltip: " + field.GetTooltip());
                string options = "";
                for (int i = 0; i < field.GetNumOptions(); i++)
                {
                    options += field.GetOptionValue(i) + " | ";
                }
                Console.WriteLine("Options: " + options);
                Console.WriteLine("MaxLength: " + field.GetMaxLength());
                Console.WriteLine("Multiline: " + (field.GetFlags() & Pdfix.kFieldFlagMultiline).ToString());
                Console.WriteLine("IsFormatted: " + (field.GetAAction(PdfActionEventType.kActionEventFieldFormat) != null).ToString());
                Console.WriteLine("Required: " + ((field.GetFlags() & Pdfix.kFieldFlagRequired).ToString()).ToString());
                Console.WriteLine("ReadOnly: " + ((field.GetFlags() & Pdfix.kFieldFlagReadOnly).ToString()).ToString());
                Console.WriteLine("IsFormatted: " + (field.GetAAction(PdfActionEventType.kActionEventFieldCalculate) != null).ToString());
                Console.WriteLine("IsChecked: " + (field.GetValue() == field.GetWidgetExportValue(widget)).ToString());
                Console.WriteLine("FieldType: " + field.GetType().ToString());
            }

            if (page != null && widget != null)
            {
                // widget specific properties
                var bbox      = widget.GetBBox();
                var page_view = page.AcquirePageView(1, PdfRotate.kRotate0);
                var rect      = page_view.RectToDevice(bbox);
                page_view.Release();

                // calculate widget annot position in % of the page width
                var left   = (double)rect.left / (double)page_view.GetDeviceWidth();
                var top    = (double)rect.top / (double)page_view.GetDeviceHeight();
                var width  = (double)(rect.right - rect.left) / (double)page_view.GetDeviceWidth();
                var height = (double)(rect.bottom - rect.top) / (double)page_view.GetDeviceHeight();

                Console.WriteLine("TabOrder: " + (_tabOrder++).ToString());
                Console.WriteLine("Left: " + left.ToString() + ", Top: " + top.ToString());
                Console.WriteLine("Width: " + width.ToString() + ", Height: " + height.ToString());
            }
        }
Exemplo n.º 4
0
        public virtual void FormFieldTest01()
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(sourceFolder + "formFieldFile.pdf"));
            PdfAcroForm form   = PdfAcroForm.GetAcroForm(pdfDoc, false);
            IDictionary <String, PdfFormField> fields = form.GetFormFields();
            PdfFormField field = fields.Get("Text1");

            NUnit.Framework.Assert.IsTrue(fields.Count == 6);
            NUnit.Framework.Assert.IsTrue(field.GetFieldName().ToUnicodeString().Equals("Text1"));
            NUnit.Framework.Assert.IsTrue(field.GetValue().ToString().Equals("TestField"));
        }
Exemplo n.º 5
0
        private PdfFormField MergeFieldsWithTheSameName(PdfFormField existingField, PdfFormField newField)
        {
            String    fullFieldName = newField.GetFieldName().ToUnicodeString();
            PdfString fieldName     = newField.GetPdfObject().GetAsString(PdfName.T);

            newField.GetPdfObject().Remove(PdfName.T);
            newField.GetPdfObject().Remove(PdfName.P);
            existingField = formTo.GetField(fullFieldName);
            PdfArray kids = existingField.GetKids();

            if (kids != null && !kids.IsEmpty())
            {
                existingField.AddKid(newField);
                return(existingField);
            }
            existingField.GetPdfObject().Remove(PdfName.T);
            existingField.GetPdfObject().Remove(PdfName.P);
            formTo.GetFields().Remove(existingField.GetPdfObject());
            PdfFormField mergedField = PdfFormField.CreateEmptyField(documentTo);

            mergedField.Put(PdfName.FT, existingField.GetFormType()).Put(PdfName.T, fieldName);
            PdfDictionary parent = existingField.GetParent();

            if (parent != null)
            {
                mergedField.Put(PdfName.Parent, parent);
                PdfArray parentKids = parent.GetAsArray(PdfName.Kids);
                for (int i = 0; i < parentKids.Size(); i++)
                {
                    PdfObject obj = parentKids.Get(i);
                    if (obj == existingField.GetPdfObject())
                    {
                        parentKids.Set(i, mergedField.GetPdfObject());
                        break;
                    }
                }
            }
            kids = existingField.GetKids();
            if (kids != null)
            {
                mergedField.Put(PdfName.Kids, kids);
            }
            mergedField.AddKid(existingField).AddKid(newField);
            PdfObject value = existingField.GetValue();

            if (value != null)
            {
                mergedField.Put(PdfName.V, existingField.GetPdfObject().Get(PdfName.V));
            }
            return(mergedField);
        }
Exemplo n.º 6
0
            public virtual bool CheckWhetherSignatureCoversWholeDocument(PdfFormField signatureField)
            {
                rangeIsCorrect = false;
                PdfDictionary signature = (PdfDictionary)signatureField.GetValue();

                int[] byteRange = ((PdfArray)signature.Get(PdfName.ByteRange)).ToIntArray();
                try {
                    if (4 != byteRange.Length || 0 != byteRange[0] || tokens.GetSafeFile().Length() != byteRange[2] + byteRange
                        [3])
                    {
                        return(false);
                    }
                }
                catch (System.IO.IOException) {
                    // That's not expected because if the signature is invalid, it should have already failed
                    return(false);
                }
                contentsStart = byteRange[1];
                contentsEnd   = byteRange[2];
                long signatureOffset;

                if (null != signature.GetIndirectReference())
                {
                    signatureOffset = signature.GetIndirectReference().GetOffset();
                    searchInV       = true;
                }
                else
                {
                    signatureOffset = signatureField.GetPdfObject().GetIndirectReference().GetOffset();
                    searchInV       = false;
                    contentsLevel++;
                }
                try {
                    tokens.Seek(signatureOffset);
                    tokens.NextValidToken();
                    ReadObject(false, false);
                }
                catch (System.IO.IOException) {
                    // That's not expected because if the signature is invalid, it should have already failed
                    return(false);
                }
                return(rangeIsCorrect);
            }
Exemplo n.º 7
0
        private void WriteSpells(PdfDocument pdfDocument, SpellCasting spellCasting)
        {
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDocument, true);
            IDictionary <string, PdfFormField> fields = form.GetFormFields();

            List <string> Cantrips = new List <string>()
            {
                "cantrip001", "cantrip002", "cantrip003", "cantrip004", "cantrip005", "cantrip006", "cantrip007", "cantrip008"
            };
            List <string> _1st = new List <string>()
            {
                "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112"
            };
            List <string> _2nd = new List <string>()
            {
                "201", "202", "203", "204", "205", "206", "207", "208", "209", "210", "211", "212", "213"
            };
            List <string> _3rd = new List <string>()
            {
                "301", "302", "303", "304", "305", "306", "307", "308", "309", "310", "311", "312", "313"
            };
            List <string> _4th = new List <string>()
            {
                "401", "402", "403", "404", "405", "406", "407", "408", "409", "410", "411", "412", "413"
            };
            List <string> _5th = new List <string>()
            {
                "501", "502", "503", "504", "505", "506", "507", "508", "509", "510"
            };
            List <string> _6th = new List <string>()
            {
                "601", "602", "603", "604", "605", "606", "607", "608", "609"
            };
            List <string> _7th = new List <string>()
            {
                "701", "702", "703", "704", "705", "706", "707", "708", "709"
            };
            List <string> _8th = new List <string>()
            {
                "801", "802", "803", "804", "805", "806", "807"
            };
            List <string> _9th = new List <string>()
            {
                "901", "902", "903", "904", "905", "906", "907"
            };
            List <string> _10th = new List <string>()
            {
                "1001", "1002", "1003", "1004", "1005", "1006", "1007"
            };

            List <Spell> _0  = spellCasting.SpellsKnown.Where(x => x.Level == 0).OrderBy(n => n.Name).Take(11).ToList();
            List <Spell> _1  = spellCasting.SpellsKnown.Where(x => x.Level == 1).OrderByDescending(a => a.prepared).ThenBy(n => n.Name).Take(12).ToList();
            List <Spell> _2  = spellCasting.SpellsKnown.Where(x => x.Level == 2).OrderByDescending(a => a.prepared).ThenBy(n => n.Name).Take(12).ToList();
            List <Spell> _3  = spellCasting.SpellsKnown.Where(x => x.Level == 3).OrderByDescending(a => a.prepared).ThenBy(n => n.Name).Take(12).ToList();
            List <Spell> _4  = spellCasting.SpellsKnown.Where(x => x.Level == 4).OrderByDescending(a => a.prepared).ThenBy(n => n.Name).Take(9).ToList();
            List <Spell> _5  = spellCasting.SpellsKnown.Where(x => x.Level == 5).OrderByDescending(a => a.prepared).ThenBy(n => n.Name).Take(8).ToList();
            List <Spell> _6  = spellCasting.SpellsKnown.Where(x => x.Level == 6).OrderByDescending(a => a.prepared).ThenBy(n => n.Name).Take(8).ToList();
            List <Spell> _7  = spellCasting.SpellsKnown.Where(x => x.Level == 7).OrderByDescending(a => a.prepared).ThenBy(n => n.Name).Take(6).ToList();
            List <Spell> _8  = spellCasting.SpellsKnown.Where(x => x.Level == 8).OrderByDescending(a => a.prepared).ThenBy(n => n.Name).Take(6).ToList();
            List <Spell> _9  = spellCasting.SpellsKnown.Where(x => x.Level == 9).OrderByDescending(a => a.prepared).ThenBy(n => n.Name).Take(6).ToList();
            List <Spell> _10 = spellCasting.SpellsKnown.Where(x => x.Level == 10).OrderByDescending(a => a.prepared).ThenBy(n => n.Name).ToList();

            for (int i = 0; i < _0.Count; i++)
            {
                PdfFormField field = form.GetField(Cantrips[i]);
                if (string.IsNullOrEmpty(field.GetValue().ToString()))
                {
                    field.SetValue(_0[i].Name);
                }
            }

            for (int i = 0; i < _1.Count; i++)
            {
                PdfFormField field = form.GetField(_1st[i]);
                if (string.IsNullOrEmpty(field.GetValue().ToString()))
                {
                    if (_1[i].prepared)
                    {
                        form.GetField($"{_1st[i]}prepaired").SetValue("Yes");
                    }
                    string comp = string.Empty;
                    foreach (Component s in _1[i].Component)
                    {
                        if (string.IsNullOrEmpty(comp))
                        {
                            comp = $"{s}";
                        }
                        else
                        {
                            comp += $", {s}";
                        }
                    }
                    string Name = $"{_1[i].Name}";
                    field.SetValue(Name);
                }
            }

            for (int i = 0; i < _2.Count; i++)
            {
                PdfFormField field = form.GetField(_2nd[i]);
                if (string.IsNullOrEmpty(field.GetValue().ToString()))
                {
                    if (_2[i].prepared)
                    {
                        form.GetField($"{_2nd[i]}prepaired").SetValue("Yes");
                    }
                    field.SetValue(_2[i].Name);
                }
            }

            for (int i = 0; i < _3.Count; i++)
            {
                PdfFormField field = form.GetField(_3rd[i]);
                if (string.IsNullOrEmpty(field.GetValue().ToString()))
                {
                    if (_3[i].prepared)
                    {
                        form.GetField($"{_3rd[i]}prepaired").SetValue("Yes");
                    }
                    field.SetValue(_3[i].Name);
                }
            }

            for (int i = 0; i < _4.Count; i++)
            {
                PdfFormField field = form.GetField(_4th[i]);
                if (string.IsNullOrEmpty(field.GetValue().ToString()))
                {
                    if (_4[i].prepared)
                    {
                        form.GetField($"{_4th[i]}prepaired").SetValue("Yes");
                    }
                    field.SetValue(_4[i].Name);
                }
            }

            for (int i = 0; i < _5.Count; i++)
            {
                PdfFormField field = form.GetField(_5th[i]);
                if (string.IsNullOrEmpty(field.GetValue().ToString()))
                {
                    if (_5[i].prepared)
                    {
                        form.GetField($"{_5th[i]}prepaired").SetValue("Yes");
                    }
                    field.SetValue(_5[i].Name);
                }
            }

            for (int i = 0; i < _6.Count; i++)
            {
                PdfFormField field = form.GetField(_6th[i]);
                if (string.IsNullOrEmpty(field.GetValue().ToString()))
                {
                    if (_6[i].prepared)
                    {
                        form.GetField($"{_6th[i]}prepaired").SetValue("Yes");
                    }
                    field.SetValue(_6[i].Name);
                }
            }

            for (int i = 0; i < _7.Count; i++)
            {
                PdfFormField field = form.GetField(_7th[i]);
                if (string.IsNullOrEmpty(field.GetValue().ToString()))
                {
                    if (_7[i].prepared)
                    {
                        form.GetField($"{_7th[i]}prepaired").SetValue("Yes");
                    }
                    field.SetValue(_7[i].Name);
                }
            }

            for (int i = 0; i < _8.Count; i++)
            {
                PdfFormField field = form.GetField(_8th[i]);
                if (string.IsNullOrEmpty(field.GetValue().ToString()))
                {
                    if (_8[i].prepared)
                    {
                        form.GetField($"{_8th[i]}prepaired").SetValue("Yes");
                    }
                    field.SetValue(_8[i].Name);
                }
            }

            for (int i = 0; i < _9.Count; i++)
            {
                PdfFormField field = form.GetField(_9th[i]);
                if (string.IsNullOrEmpty(field.GetValue().ToString()))
                {
                    if (_9[i].prepared)
                    {
                        form.GetField($"{_9th[i]}prepaired").SetValue("Yes");
                    }
                    field.SetValue(_9[i].Name);
                }
            }

            WriteSpellSlots(spellCasting, form);
        }
Exemplo n.º 8
0
        public async Task <ResponseObject> ExtractJsonFromPDF(string email, string licenseKey, string filePath, List <string> imageList)
        {
            ResponseObject responseObject = new ResponseObject();
            List <string>  errorList      = new List <string>();

            try
            {
                Pdfix pdfix = new Pdfix();
                if (pdfix == null)
                {
                    throw new Exception("Pdfix initialization fail");
                }

                if (!pdfix.Authorize(email, licenseKey))
                {
                    throw new Exception(pdfix.GetError());
                }

                PdfDoc doc = pdfix.OpenDoc(filePath, "");
                if (doc == null)
                {
                    throw new Exception();
                }

                int pageCount = doc.GetNumPages();

                List <PDF> pdfList = new List <PDF>();

                for (int i = 0; i < doc.GetNumPages(); i++)
                {
                    List <PDFObject> pdfObjectList = new List <PDFObject>();

                    PdfPage page   = doc.AcquirePage(i);
                    PDF     pdfObj = new PDF();

                    pdfObj.page     = i.ToString();
                    pdfObj.imageUrl = GetBase64String(imageList[i]);
                    _tabOrder       = 0;
                    int annots = page.GetNumAnnots();

                    for (int j = 0; j < page.GetNumAnnots(); j++)
                    {
                        PdfAnnot        pdfAnnot        = page.GetAnnot(j);
                        PdfAnnotSubtype pdfAnnotSubtype = pdfAnnot.GetSubtype();

                        PdfFormField field     = null;
                        bool         isChecked = false;

                        if (pdfAnnotSubtype == PdfAnnotSubtype.kAnnotLink)
                        {
                            var widget = (PdfLinkAnnot)pdfAnnot;
                            field     = doc.GetFormField(j);
                            isChecked = field.GetValue() == field.GetWidgetExportValue(widget);
                        }
                        if (pdfAnnotSubtype == PdfAnnotSubtype.kAnnotWidget)
                        {
                            var widget = (PdfWidgetAnnot)pdfAnnot;
                            field = widget.GetFormField();
                            if (field == null)
                            {
                                field = doc.GetFormField(j);
                            }

                            isChecked = field.GetValue() == field.GetWidgetExportValue(widget);
                        }

                        if (pdfAnnotSubtype == PdfAnnotSubtype.kAnnotHighlight)
                        {
                            var widget = (PdfTextMarkupAnnot)pdfAnnot;
                            field     = doc.GetFormField(j);
                            isChecked = field.GetValue() == field.GetWidgetExportValue(widget);
                        }

                        if (field == null)
                        {
                            field = doc.GetFormField(j);
                            string fieldName = field.GetFullName();
                            errorList.Add(fieldName);
                            throw new Exception();
                        }

                        PDFObject pdfObject = new PDFObject();
                        pdfObject.fieldName   = field.GetFullName();
                        pdfObject.fieldValue  = field.GetValue();
                        pdfObject.maxLength   = field.GetMaxLength();
                        pdfObject.tooltip     = field.GetTooltip();
                        pdfObject.displayName = field.GetDefaultValue();

                        pdfObject.multiLine   = ((field.GetFlags() & Pdfix.kFieldFlagMultiline) != 0) ? true : false;
                        pdfObject.isFormatted = ((field.GetAAction(PdfActionEventType.kActionEventFieldFormat)) != null) ? true : false;
                        pdfObject.required    = ((field.GetFlags() & Pdfix.kFieldFlagRequired) != 0) ? true : false;
                        pdfObject.readOnly    = ((field.GetFlags() & Pdfix.kFieldFlagReadOnly) != 0) ? true : false;
                        pdfObject.tabOrder    = _tabOrder++;
                        pdfObject.isChecked   = isChecked;
                        pdfObject.fieldType   = GetFieldType(field);

                        List <string> dropdownList = new List <string>();
                        for (int k = 0; k < field.GetOptionCount(); k++)
                        {
                            string optionValue = field.GetOptionValue(k);
                            dropdownList.Add(optionValue);
                        }

                        pdfObject.optionList = dropdownList;

                        PdfRect bbox = pdfAnnot.GetBBox();

                        PdfAnnotAppearance pdfAnnotAppearance = pdfAnnot.GetAppearance();
                        PdfPageView        pageView           = page.AcquirePageView(1.0, PdfRotate.kRotate0);
                        if (pageView == null)
                        {
                            throw new Exception(pdfix.GetError());
                        }

                        var devRect = pageView.RectToDevice(bbox);

                        var x      = devRect.left;
                        var y      = devRect.top;
                        var width  = devRect.right - devRect.left;
                        var height = devRect.bottom - devRect.top;

                        var pageWidth  = pageView.GetDeviceWidth();
                        var pageHeight = pageView.GetDeviceHeight();

                        var pdfvalue   = ((double)x / pageWidth) * 100;
                        var percentage = Convert.ToInt32(Math.Round(pdfvalue, 2));

                        pdfObject.x      = ((double)devRect.left / pageView.GetDeviceWidth()) * 100;
                        pdfObject.y      = ((double)devRect.top / pageView.GetDeviceHeight()) * 100;
                        pdfObject.width  = ((double)(devRect.right - devRect.left) / pageView.GetDeviceWidth()) * 100;
                        pdfObject.height = ((double)(devRect.bottom - devRect.top) / pageView.GetDeviceHeight()) * 100;

                        pageView.Release();

                        pdfObjectList.Add(pdfObject);
                    }
                    pdfObj.pdfObjList = pdfObjectList;
                    pdfObj.width      = 927;
                    pdfObj.height     = 1200;
                    pdfList.Add(pdfObj);
                }


                responseObject.flag    = true;
                responseObject.data    = pdfList;
                responseObject.message = "Document Import Successfully";

                doc.Close();
                pdfix.Destroy();
            }
            catch (Exception ex)
            {
                responseObject.errorList = errorList;
                throw ex;
            }

            return(responseObject);
        }
Exemplo n.º 9
0
        private PdfFormField MergeFieldsWithTheSameName(PdfFormField newField)
        {
            String    fullFieldName = newField.GetFieldName().ToUnicodeString();
            PdfString fieldName     = newField.GetPdfObject().GetAsString(PdfName.T);

            logger.Warn(MessageFormatUtil.Format(iText.IO.LogMessageConstant.DOCUMENT_ALREADY_HAS_FIELD, fullFieldName
                                                 ));
            PdfFormField existingField = formTo.GetField(fullFieldName);

            if (existingField.IsFlushed())
            {
                int index = 0;
                do
                {
                    index++;
                    newField.SetFieldName(fieldName.ToUnicodeString() + "_#" + index);
                    fullFieldName = newField.GetFieldName().ToUnicodeString();
                }while (formTo.GetField(fullFieldName) != null);
                return(newField);
            }
            newField.GetPdfObject().Remove(PdfName.T);
            newField.GetPdfObject().Remove(PdfName.P);
            formTo.GetFields().Remove(existingField.GetPdfObject());
            PdfArray kids = existingField.GetKids();

            if (kids != null && !kids.IsEmpty())
            {
                existingField.AddKid(newField);
                return(existingField);
            }
            existingField.GetPdfObject().Remove(PdfName.T);
            existingField.GetPdfObject().Remove(PdfName.P);
            PdfFormField mergedField = PdfFormField.CreateEmptyField(documentTo);

            mergedField.Put(PdfName.FT, existingField.GetFormType()).Put(PdfName.T, fieldName);
            PdfDictionary parent = existingField.GetParent();

            if (parent != null)
            {
                mergedField.Put(PdfName.Parent, parent);
                PdfArray parentKids = parent.GetAsArray(PdfName.Kids);
                for (int i = 0; i < parentKids.Size(); i++)
                {
                    PdfObject obj = parentKids.Get(i);
                    if (obj == existingField.GetPdfObject())
                    {
                        parentKids.Set(i, mergedField.GetPdfObject());
                        break;
                    }
                }
            }
            kids = existingField.GetKids();
            if (kids != null)
            {
                mergedField.Put(PdfName.Kids, kids);
            }
            mergedField.AddKid(existingField).AddKid(newField);
            PdfObject value = existingField.GetValue();

            if (value != null)
            {
                mergedField.Put(PdfName.V, existingField.GetPdfObject().Get(PdfName.V));
            }
            return(mergedField);
        }
        public ActionResult <PdfScanResult> Get(string pdfCode)
        {
            if (string.IsNullOrEmpty(pdfCode))
            {
                return(BadRequest());
            }

            var templateFilePath = $"{pdfCode}.pdf";

            if (!string.IsNullOrEmpty(_pdfFilesOptions.TemplatePath))
            {
                templateFilePath = $"{_pdfFilesOptions.TemplatePath}{Path.DirectorySeparatorChar}{templateFilePath}";
            }

            if (!System.IO.File.Exists(templateFilePath))
            {
                return(NotFound());
            }

            using PdfReader reader = new PdfReader(templateFilePath);
            reader.SetUnethicalReading(true);
            using PdfDocument pdf = new PdfDocument(reader);

            var scanPages = new PdfScanPage[pdf.GetNumberOfPages()];
            var result    = new PdfScanResult {
                PdfCode = pdfCode,
                Pages   = new List <PdfScanPage>(pdf.GetNumberOfPages())
            };

            //PdfPage pdfPage = pdf.GetPage(1);
            //PdfFormXObject pdfPageCopy = pdfPage.CopyAsFormXObject(pdf);
            //Image pageImage = new Image(pdfPageCopy);
            //ImageData b = new ImageData();
            //PdfImageXObject a = new PdfImageXObject()

            var form   = PdfAcroForm.GetAcroForm(pdf, false);
            var fields = form.GetFormFields();

            foreach (string field in fields.Keys)
            {
                PdfFormField formField = form.GetField(field);
                if (formField.IsReadOnly())
                {
                    continue;
                }

                var pdfValue = formField.GetValue();
                if (formField.GetWidgets() == null)
                {
                    continue;
                }
                if (formField.GetWidgets().Count <= 0)
                {
                    continue;
                }

                bool isButton = (formField is PdfButtonFormField);
                bool isText   = (formField is PdfTextFormField);

                if (!isText && !isButton)
                {
                    continue;
                }

                var page       = formField.GetWidgets().First().GetPage();
                var pageNumber = pdf.GetPageNumber(page);

                PdfScanPage scanPage = scanPages[pageNumber - 1];
                if (scanPage == null)
                {
                    scanPage = new PdfScanPage {
                        Number     = pageNumber,
                        FormFields = new List <PdfScanFormField>()
                    };
                }

                double minLowerLeftX  = double.MaxValue;
                double minLowerLeftY  = double.MaxValue;
                double maxUpperRightX = 0;
                double maxUpperRightY = 0;
                foreach (var widget in formField.GetWidgets())
                {
                    var rectangle = widget.GetRectangle();
                    if (rectangle == null)
                    {
                        continue;
                    }
                    if (rectangle.Size() < 4)
                    {
                        continue;
                    }

                    // API links explanations:
                    //https://itextpdf.com/en/resources/faq/technical-support/itext-7/how-find-absolute-position-and-dimension-field
                    //https://itextpdf.com/en/resources/faq/technical-support/itext-7/how-show-image-text-field-position
                    var lowerLeftX  = rectangle.GetAsNumber(0).GetValue(); //lower left position x
                    var lowerLeftY  = rectangle.GetAsNumber(1).GetValue(); //lower left position y
                    var upperRightX = rectangle.GetAsNumber(2).GetValue(); //upper right position x
                    var upperRightY = rectangle.GetAsNumber(3).GetValue(); //upper right position y

                    if (minLowerLeftX > lowerLeftX)
                    {
                        minLowerLeftX = lowerLeftX;
                    }
                    if (minLowerLeftY > lowerLeftY)
                    {
                        minLowerLeftY = lowerLeftY;
                    }

                    if (maxUpperRightX < upperRightX)
                    {
                        maxUpperRightX = upperRightX;
                    }
                    if (maxUpperRightY < upperRightY)
                    {
                        maxUpperRightY = upperRightY;
                    }
                }

                var scanFormField = new PdfScanFormField
                {
                    Name     = field,
                    Position = new Position
                    {
                        X = minLowerLeftX,
                        Y = minLowerLeftY
                    },
                    Size = new Size
                    {
                        Width  = maxUpperRightX - minLowerLeftX,
                        Height = maxUpperRightY - minLowerLeftY
                    }
                };

                scanPage.FormFields.Add(scanFormField);
                scanPages[pageNumber - 1] = scanPage;
            }

            result.Pages = scanPages.Where(sp => sp != null).ToList();
            return(Ok(result));
        }