예제 #1
0
        /// <summary>
        ///     enumerate each PdfAcroField, convert it's value to clr type, use reflection to set that value to the clr object
        ///     BaseDoc
        /// </summary>
        /// <param name="DocData"></param>
        /// <param name="DocRevStrict"></param>
        /// <returns></returns>
        public override BaseDoc Read(byte[] DocData, bool DocRevStrict = false)
        {
            using (MemoryStream _MemoryStream = new MemoryStream(DocData))
                using (PdfDocument _PdfDocument = PdfReader.Open(_MemoryStream, PdfDocumentOpenMode.ReadOnly))
                {
                    DocProcessingInstructions _DocProcessingInstructions = ReadDocPI(_PdfDocument);

                    BaseDoc _BaseDoc = Runtime.ActivateBaseDoc(
                        _DocProcessingInstructions.DocTypeName,
                        DocRevStrict
                        ? _DocProcessingInstructions.solutionVersion
                        : TemplateController.Instance.TopDocRev(_DocProcessingInstructions.DocTypeName));

                    Type _BaseDocType = _BaseDoc.GetType();

                    for (int i = 0; i < _PdfDocument.AcroForm.Fields.Elements.Count; i++)
                    {
                        PdfAcroField      _Field             = _PdfDocument.AcroForm.Fields[i];
                        CompositeProperty _CompositeProperty = _Field.AsCompositeProperty();
                        string            _Value             = string.Format("{0}", _Field.Value);

                        PropertyInfo _PropertyInfo = _BaseDocType.GetProperty(_CompositeProperty.Name, _CompositeProperty.PropertyType);
                        _PropertyInfo.SetValue(_BaseDoc, Convert.ChangeType(_Value, _PropertyInfo.PropertyType), null);
                    }

                    return(SetPI(_BaseDoc, _DocProcessingInstructions));
                }
        }
예제 #2
0
        private static void AddBoxForAcroField(TemplatePage page, PdfPage pdfPage, PdfAcroField field, int fieldNumber)
        {
            if (!field.Elements.ContainsKey("/Rect"))
            {
                return;
            }
            var rect = field.Elements["/Rect"] as PdfArray; // or PdfRectangle?

            if (rect is null)
            {
                return;
            }

            var name = $"Pdf field {fieldNumber}";

            if (field.Elements.ContainsKey("/TU"))
            {
                if (field.Elements["/TU"] is PdfString description &&
                    !string.IsNullOrWhiteSpace(description.Value))
                {
                    name = Strings.CleanKeyName(description.Value.ReplaceAsciiCompatible());
                }
            }

            AddTemplateBox(page, pdfPage, rect, name !);
        }
예제 #3
0
        static PdfPage?GetPageFromField(PdfDocument myDocument, string focusFieldName, out int pageNum)
        {
            pageNum = 0;
            PdfAcroField currentField = (PdfAcroField)(myDocument.AcroForm.Fields[focusFieldName]);

            if (currentField == null)
            {
                return(null);
            }

            // get the page element
            var focusPageReference = (PdfReference)currentField.Elements["/P"];

            // loop through our pages to match the reference
            foreach (var page in myDocument.Pages)
            {
                pageNum++;
                if (page.Reference == focusPageReference)
                {
                    return(page);
                }
            }
            // could not find a page for this field
            return(null);
        }
예제 #4
0
        public override byte[] WriteByte <T>(T source, bool includeProcessingInformation = true)
        {
            using (MemoryStream _MemoryStream = TemplateController.Instance.OpenRead(
                       source.DocTypeName,
                       source.solutionVersion,
                       TEMPLATE_PDF))

                using (PdfDocument _PdfDocument = PdfReader.Open(_MemoryStream, PdfDocumentOpenMode.Modify))
                {
                    Type baseDocType = source.GetType();

                    for (int i = 0; i < _PdfDocument.AcroForm.Fields.Elements.Count; i++)
                    {
                        PdfAcroField _Field = _PdfDocument.AcroForm.Fields[i];
                        _Field.Value = new PdfString(string.Format("{0}", baseDocType.GetProperty(_Field.Name).GetValue(source, null)));
                    }

                    if (includeProcessingInformation)
                    {
                        WritePI(source, _PdfDocument);
                    }

                    _PdfDocument.Save(_MemoryStream);

                    return(_MemoryStream.ToArray());
                }
        }
예제 #5
0
 private static (XFont?font, XBrush?brush) GetFontBrush(PdfAcroField field)
 {
     if (field is PdfTextField textField)
     {
         return(textField.Font, new XSolidBrush(textField.ForeColor));
     }
     return(null, null);
 }
예제 #6
0
        private void FillField(PdfAcroField field, int index, string value)
        {
            field.Value = new PdfString(value);
            //if (field is PdfTextField textField)
            //{

            //}
        }
예제 #7
0
        private static XRect GetLayout(PdfAcroField field, PdfPage page)
        {
            var height = page.Height.Point;
            var rect   = field.Elements["/Rect"];

            if (rect is PdfArray array)
            {
                var elements = array.ToArray();
                var x        = GetValue(elements[0]);
                var y        = GetValue(elements[3]);
                var w        = GetValue(elements[2]) - x;
                var h        = y - GetValue(elements[1]);
                return(new XRect(x, height - y, w, h));
            }
            return(new XRect());
        }
예제 #8
0
        public static CompositeProperty AsCompositeProperty(this PdfAcroField o)
        {
            CompositeProperty _CompositeProperty = asCompositeProperty((dynamic)o);

            if (o.Flags == PdfAcroFieldFlags.Required)
            {
                if (_CompositeProperty.PropertyType != typeof(string))
                {
                    if (_CompositeProperty.PropertyType != typeof(byte[]))
                    {
                        _CompositeProperty.PropertyType = typeof(Nullable <>).MakeGenericType(Nullable.GetUnderlyingType(_CompositeProperty.PropertyType) ?? _CompositeProperty.PropertyType);
                    }
                }
            }

            return(_CompositeProperty);
        }
예제 #9
0
        static void Main(string[] args)
        {
            // Get a fresh copy of a sample PDF form file
            string filename;

            filename = "fw4.pdf";
            //filename = "fss4.pdf";
            //filename = "fw9.pdf";
            //filename = "f8822.pdf";

            while (!File.Exists(Path.Combine("d:/WImageTest/PDFs", filename)))
            {
                if (DialogResult.Yes ==
                    MessageBox.Show("This sample needs a PDF form that is not included with this release.\n" +
                                    "Please download the Form W-4 from http://www.irs.gov" +
                                    "\nSelect Yes to open this URL in your browser.\n" +
                                    "Select No to exit this sample now.",
                                    "PDFsharp FillFormFields sample",
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question))
                {
                    Process.Start("../../SampleForms/ReadMe.txt");
                    Process.Start("http://www.irs.gov/");
                    MessageBox.Show("Close this dialog to continue the sample after downloading the W-4 form to the appropriate folder.",
                                    "PDFsharp FillFormFields sample");
                }
                else
                {
                    return;
                }
            }

            File.Copy(Path.Combine("../../../../PDFs", filename),
                      Path.Combine(Directory.GetCurrentDirectory(), filename), true);

            // Open the file
            PdfDocument document = PdfReader.Open(filename, PdfDocumentOpenMode.Modify);

            // Get the root object of all interactive form fields
            PdfAcroForm form = document.AcroForm;

            // Get all form fields of the whole document
            PdfAcroField.PdfAcroFieldCollection fields = form.Fields;

            // Get all form fields of the whole document
            string[] names = fields.Names;
            names = fields.DescendantNames;

            // Fill some value in each field
            for (int idx = 0; idx < names.Length; idx++)
            {
                string       fqName = names[idx];
                PdfAcroField field  = fields[fqName];

                PdfTextField        txtField;
                PdfRadioButtonField radField;
                PdfCheckBoxField    chkField;
                PdfListBoxField     lbxField;
                PdfComboBoxField    cbxField;
                PdfGenericField     genField;

                if ((txtField = field as PdfTextField) != null)
                {
                    //
                    txtField.Text = "Hello";
                }
                else if ((radField = field as PdfRadioButtonField) != null)
                {
                    radField.SelectedIndex = 0;
                }
                else if ((chkField = field as PdfCheckBoxField) != null)
                {
                    chkField.Checked = idx % 2 == 0;
                }
                else if ((lbxField = field as PdfListBoxField) != null)
                {
                    lbxField.SelectedIndex = 0;
                }
                else if ((cbxField = field as PdfComboBoxField) != null)
                {
                    cbxField.SelectedIndex = 0;
                }
                else if ((genField = field as PdfGenericField) != null)
                {
                }
            }

            // Save the document...
            document.Save(filename);
            // ...and start a viewer.
            Process.Start(filename);
        }
예제 #10
0
        private static PdfPage?GetPageFromField(PdfDocument document, PdfAcroField field)
        {
            var focusPageReference = (PdfReference)field.Elements["/P"];

            return(document.Pages.Cast <PdfPage>().FirstOrDefault(e => e.Reference == focusPageReference));
        }
예제 #11
0
 private void ImportAcroField(PdfPage page, PdfPage importPage, PdfAcroForm localForm, PdfImportedObjectTable importedObjectTable, PdfAcroField fieldObj, bool isChild)
 {
     if (fieldObj != null)
     {
         PdfDictionary importedObject;
         if (!importedObjectTable.Contains(fieldObj.ObjectID))
         {
             // Do not use PdfObject.DeepCopyClosure as that would also create new Pages when encountering the "/P" Entry  !
             importedObject = ImportClosure(importedObjectTable, _document, fieldObj) as PdfDictionary;
         }
         else
         {
             importedObject = importedObjectTable[fieldObj.ObjectID].Value as PdfDictionary;
         }
         Debug.Assert(importedObject != null, "Imported AcroField is null");
         if (importedObject != null)
         {
             var name = importedObject is PdfAcroField ? ((PdfAcroField)importedObject).FullyQualifiedName : "NoName";
             Debug.WriteLine(String.Format("Importing {0} '{1}' ({2})", importedObject.GetType().Name, name, importedObject.ObjectID));
             if (importedObject.Elements.ContainsKey("/P"))
             {
                 var fieldPage = importedObject.Elements.GetObject(PdfAnnotation.Keys.Page);
                 Debug.Assert(_document._irefTable.Contains(fieldPage.ObjectID), "Page of imported field should exist in current document");
             }
             if (!isChild && !IsInArray(localForm.Fields, importedObject))
             {
                 localForm.Fields.Elements.Add(importedObject);
             }
         }
     }
 }
예제 #12
0
        static void Main(string[] args)
        {
            // Set the name of the filled file
            string filename;

            //filename = "fw4 (Acrobat 4).pdf";
            //filename = "fw4 (Acrobat 5).pdf";
            //filename = "fw4 (Acrobat 6).pdf";
            filename = "fw4 (Acrobat 7).pdf";
            filename = Path.Combine("../../FilledForms", filename);

            // Open the file
            PdfDocument document = PdfReader.Open(filename, PdfDocumentOpenMode.ReadOnly);

            // Get the root object of all interactive form fields
            PdfAcroForm form = document.AcroForm;

            // Get all form fields of the whole document
            PdfAcroField.PdfAcroFieldCollection fields = form.Fields;

            // Get all form fields of the whole document
            string[] names = fields.Names;
            names = fields.DescendantNames;

            // Read the value of each field
            for (int idx = 0; idx < names.Length; idx++)
            {
                string       fqName = names[idx];
                PdfAcroField field  = fields[fqName];

                PdfTextField        txtField;
                PdfRadioButtonField radField;
                PdfCheckBoxField    chkField;
                PdfListBoxField     lbxField;
                PdfComboBoxField    cbxField;
                PdfGenericField     genField;

                if ((txtField = field as PdfTextField) != null)
                {
                    Console.WriteLine(String.Format("text field '{0}': '{1}'", txtField.Name, txtField.Text));
                }
                else if ((radField = field as PdfRadioButtonField) != null)
                {
                    Console.WriteLine(String.Format("radio button '{0}': '{1}'", radField.Name, radField.Value));
                }
                else if ((chkField = field as PdfCheckBoxField) != null)
                {
                    Console.WriteLine(String.Format("radio button '{0}': '{1}'", chkField.Name, chkField.Value));
                }
                else if ((lbxField = field as PdfListBoxField) != null)
                {
                    Console.WriteLine(String.Format("radio button '{0}': '{1}'", lbxField.Name, lbxField.Value));
                }
                else if ((cbxField = field as PdfComboBoxField) != null)
                {
                    Console.WriteLine(String.Format("radio button '{0}': '{1}'", cbxField.Name, cbxField.Value));
                }
                else if ((genField = field as PdfGenericField) != null)
                {
                    Console.WriteLine(String.Format("radio button '{0}': '{1}'", genField.Name, genField.Value));
                }
            }

            // Wait for Return
            Console.ReadLine();
        }
예제 #13
0
 private static CompositeProperty asCompositeProperty(PdfAcroField o)
 {
     return(new CompositeProperty(o.Name, typeof(string)));
 }