Beispiel #1
0
        private Field[] GetFormFields(string sourcePath)
        {
            var pdfDoc = new PDFDoc(sourcePath);

            var formFields = new List <Field>();
            var itr        = pdfDoc.GetFieldIterator();

            for (; itr.HasNext(); itr.Next())
            {
                formFields.Add(itr.Current());
            }

            return(formFields.ToArray());
        }
Beispiel #2
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            // Relative path to the folder containing test files.
            string input_path  = "../../TestFiles/";
            string output_path = "../../TestFiles/Output/";

            // Example 1)
            // Iterate over all form fields in the document. Display all field names.
            try
            {
                using (PDFDoc doc = new PDFDoc(input_path + "form1.pdf"))
                {
                    doc.InitSecurityHandler();

                    FieldIterator itr;
                    for (itr = doc.GetFieldIterator(); itr.HasNext(); itr.Next())
                    {
                        Console.WriteLine("Field name: {0:s}", itr.Current().GetName());
                        Console.WriteLine("Field partial name: {0:s}", itr.Current().GetPartialName());

                        Console.Write("Field type: ");
                        Field.Type type = itr.Current().GetType();
                        switch (type)
                        {
                        case Field.Type.e_button:
                            Console.WriteLine("Button"); break;

                        case Field.Type.e_text:
                            Console.WriteLine("Text"); break;

                        case Field.Type.e_choice:
                            Console.WriteLine("Choice"); break;

                        case Field.Type.e_signature:
                            Console.WriteLine("Signature"); break;
                        }

                        Console.WriteLine("------------------------------");
                    }

                    Console.WriteLine("Done.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // Example 2) Import XFDF into FDF, then merge data from FDF into PDF
            try
            {
                // XFDF to FDF
                // form fields
                Console.WriteLine("Import form field data from XFDF to FDF.");

                FDFDoc fdf_doc1 = new FDFDoc(FDFDoc.CreateFromXFDF(input_path + "form1_data.xfdf"));
                fdf_doc1.Save(output_path + "form1_data.fdf");

                // annotations
                Console.WriteLine("Import annotations from XFDF to FDF.");

                FDFDoc fdf_doc2 = new FDFDoc(FDFDoc.CreateFromXFDF(input_path + "form1_annots.xfdf"));
                fdf_doc2.Save(output_path + "form1_annots.fdf");

                // FDF to PDF
                // form fields
                Console.WriteLine("Merge form field data from FDF.");

                using (PDFDoc doc = new PDFDoc(input_path + "form1.pdf"))
                {
                    doc.InitSecurityHandler();
                    doc.FDFMerge(fdf_doc1);

                    // To use PDFNet form field appearance generation instead of relying on
                    // Acrobat, uncomment the following two lines:
                    // doc.RefreshFieldAppearances();
                    // doc.GetAcroForm().Put("NeedAppearances", Obj.CreateBool(false));

                    doc.Save(output_path + "form1_filled.pdf", SDFDoc.SaveOptions.e_linearized);

                    // annotations
                    Console.WriteLine("Merge annotations from FDF.");

                    doc.FDFMerge(fdf_doc2);
                    doc.Save(output_path + "form1_filled_with_annots.pdf", SDFDoc.SaveOptions.e_linearized);

                    Console.WriteLine("Done.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // Example 3) Extract data from PDF to FDF, then export FDF as XFDF
            try
            {
                // PDF to FDF
                using (PDFDoc in_doc = new PDFDoc(output_path + "form1_filled_with_annots.pdf"))
                {
                    in_doc.InitSecurityHandler();

                    // form fields only
                    Console.WriteLine("Extract form fields data to FDF.");

                    FDFDoc doc_fields = in_doc.FDFExtract(PDFDoc.ExtractFlag.e_forms_only);
                    doc_fields.SetPdfFileName("../form1_filled_with_annots.pdf");
                    doc_fields.Save(output_path + "form1_filled_data.fdf");

                    // annotations only
                    Console.WriteLine("Extract annotations to FDF.");

                    FDFDoc doc_annots = in_doc.FDFExtract(PDFDoc.ExtractFlag.e_annots_only);
                    doc_annots.SetPdfFileName("../form1_filled_with_annots.pdf");
                    doc_annots.Save(output_path + "form1_filled_annot.fdf");

                    // both form fields and annotations
                    Console.WriteLine("Extract both form fields and annotations to FDF.");

                    FDFDoc doc_both = in_doc.FDFExtract(PDFDoc.ExtractFlag.e_both);
                    doc_both.SetPdfFileName("../form1_filled_with_annots.pdf");
                    doc_both.Save(output_path + "form1_filled_both.fdf");

                    // FDF to XFDF
                    // form fields
                    Console.WriteLine("Export form field data from FDF to XFDF.");

                    doc_fields.SaveAsXFDF(output_path + "form1_filled_data.xfdf");

                    // annotations
                    Console.WriteLine("Export annotations from FDF to XFDF.");

                    doc_annots.SaveAsXFDF(output_path + "form1_filled_annot.xfdf");

                    // both form fields and annotations
                    Console.WriteLine("Export both form fields and annotations from FDF to XFDF.");

                    doc_both.SaveAsXFDF(output_path + "form1_filled_both.xfdf");

                    Console.WriteLine("Done.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // Example 4) Merge/Extract XFDF into/from PDF
            try
            {
                // Merge XFDF from string
                PDFDoc in_doc = new PDFDoc(input_path + "numbered.pdf");
                {
                    in_doc.InitSecurityHandler();

                    Console.WriteLine("Merge XFDF string into PDF.");

                    string str = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xfdf xmlns=\"http://ns.adobe.com/xfdf\" xml:space=\"preserve\"><square subject=\"Rectangle\" page=\"0\" name=\"cf4d2e58-e9c5-2a58-5b4d-9b4b1a330e45\" title=\"user\" creationdate=\"D:20120827112326-07'00'\" date=\"D:20120827112326-07'00'\" rect=\"227.7814207650273,597.6174863387978,437.07103825136608,705.0491803278688\" color=\"#000000\" interior-color=\"#FFFF00\" flags=\"print\" width=\"1\"><popup flags=\"print,nozoom,norotate\" open=\"no\" page=\"0\" rect=\"0,792,0,792\" /></square></xfdf>";

                    using (FDFDoc fdoc = new FDFDoc(FDFDoc.CreateFromXFDF(str)))
                    {
                        in_doc.FDFMerge(fdoc);
                        in_doc.Save(output_path + "numbered_modified.pdf", SDFDoc.SaveOptions.e_linearized);
                        Console.WriteLine("Merge complete.");
                    }

                    // Extract XFDF as string
                    Console.WriteLine("Extract XFDF as a string.");
                    FDFDoc fdoc_new = in_doc.FDFExtract(PDFDoc.ExtractFlag.e_both);
                    string XFDF_str = fdoc_new.SaveAsXFDF();
                    Console.WriteLine("Extracted XFDF: ");
                    Console.WriteLine(XFDF_str);
                    Console.WriteLine("Extract complete.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // Example 5) Read FDF files directly
            try
            {
                FDFDoc           doc = new FDFDoc(output_path + "form1_filled_data.fdf");
                FDFFieldIterator itr = doc.GetFieldIterator();
                for (; itr.HasNext(); itr.Next())
                {
                    Console.WriteLine("Field name: {0:s}", itr.Current().GetName());
                    Console.WriteLine("Field partial name: {0:s}", itr.Current().GetPartialName());
                    Console.WriteLine("------------------------------");
                }

                Console.WriteLine("Done.");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // Example 6) Direct generation of FDF.
            try
            {
                FDFDoc doc = new FDFDoc();

                // Create new fields (i.e. key/value pairs).
                doc.FieldCreate("Company", (int)Field.Type.e_text, "PDFTron Systems");
                doc.FieldCreate("First Name", (int)Field.Type.e_text, "John");
                doc.FieldCreate("Last Name", (int)Field.Type.e_text, "Doe");
                // ...

                // doc.SetPdfFileName("mydoc.pdf");
                doc.Save(output_path + "sample_output.fdf");
                Console.WriteLine("Done. Results saved in sample_output.fdf");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #3
0
        // TODO: pass this sucker FullName, Address + City + State + Zip, DayNumberZip, DayNumberNumber, Email, String of TaxMapIDs, SignatureImgPath
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            // string input_path =  "../../../../TestFiles/";
            string output_path = @"C:\Users\dbaker.SDGLOCAL\Documents\Visual Studio 2013\Projects\FillAndFlattenPdf\FillAndFlattenPdf\pdf\";

            // Fill-in forms / Modify values of existing fields.
            // Search for specific fields in the document.
            try
            {
                using (PDFDoc doc = new PDFDoc(output_path + "rp305r.pdf"))
                    using (Stamper s = new Stamper(Stamper.SizeType.e_relative_scale, 0.3, 0.3))
                    {
                        doc.InitSecurityHandler();

                        Image img = Image.Create(doc, @"C:\Users\dbaker.SDGLOCAL\Documents\Visual Studio 2013\Projects\FillAndFlattenPdf\FillAndFlattenPdf\pdf\sig.png");
                        s.SetSize(Stamper.SizeType.e_relative_scale, 0.3, 0.3);
                        //set position of the image to the center, left of PDF pages
                        s.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_left, Stamper.VerticalAlignment.e_vertical_bottom);
                        s.SetPosition(80, 110);
                        s.SetFontColor(new ColorPt(0, 0, 0, 0));
                        //s.SetRotation(180);
                        s.SetAsBackground(false);
                        //only stamp first 2 pages
                        s.StampImage(doc, img, new PageSet(1, 1));

                        FieldIterator itr;
                        for (itr = doc.GetFieldIterator(); itr.HasNext(); itr.Next())
                        {
                            Field field = itr.Current();
                            Console.WriteLine("Field name: {0}", field.GetName());
                            Console.WriteLine("Field partial name: {0}", field.GetPartialName());

                            Console.Write("Field type: ");
                            Field.Type type = field.GetType();
                            switch (type)
                            {
                            //case Field.Type.e_button:
                            //    Console.WriteLine("Button");
                            //    break;
                            //case Field.Type.e_radio:
                            //    Console.WriteLine("Radio button");
                            //    break;
                            //case Field.Type.e_check:
                            //    field.SetValue(true);
                            //    Console.WriteLine("Check box");
                            //    break;
                            case Field.Type.e_text:
                            {
                                Console.WriteLine("Text");

                                // Edit all variable text in the document
                                String old_value = "none";
                                if (field.GetValue() != null)
                                {
                                    old_value = field.GetValue().GetAsPDFText();
                                }

                                string FieldName = field.GetName().ToString();
                                Console.Write("\n-" + FieldName + "-\n");
                                switch (FieldName)
                                {
                                case "Date":
                                    field.SetValue("CurrentDate");
                                    break;

                                case "Name and mailing address of landowners 1":
                                    field.SetValue("Full Name");
                                    break;

                                case "Name and mailing address of landowners 2":
                                    field.SetValue("Street Address");
                                    break;

                                case "Name and mailing address of landowners 3":
                                    field.SetValue("City + State + Zip");
                                    break;

                                //case "Name and mailing address of landowners 4":
                                //    field.SetValue("You Shouldn't Need Me");
                                //    break;
                                case "Email address":
                                    field.SetValue("Email");
                                    break;

                                case "Evening Number":
                                    field.SetValue("Evening Number");
                                    break;

                                case "Day Number":
                                    field.SetValue("Day Number");
                                    break;

                                //case "Day Area Code":
                                //    field.SetValue("Don't Use");
                                //    break;
                                case "Year 2":
                                    field.SetValue("Lst");
                                    break;

                                case "Year 1":
                                    field.SetValue("CrYr");
                                    break;

                                //case "Following parcels - Tax Map Numbers1":
                                //    field.SetValue("Don't Use Me. I'm too short");
                                //    break;
                                case "Following parcels - Tax Map Numbers2":
                                    field.SetValue(" Tax Map Numbers2");
                                    break;

                                case "Following parcels - Tax Map Numbers3":
                                    field.SetValue(" Tax Map Numbers3");
                                    break;

                                default:
                                    break;
                                }
                            }
                            break;
                                //case Field.Type.e_choice:
                                //    Console.WriteLine("Choice");
                                //    break;
                                //case Field.Type.e_signature:
                                //    Console.WriteLine("Signature");
                                //    break;
                            }

                            Console.WriteLine("------------------------------");
                        }

                        // Search for a specific field
                        //Field fld = doc.GetField("employee.name.first");
                        //if (fld != null)
                        //{
                        //    Console.WriteLine("Field search for {0} was successful.", fld.GetName());
                        //}
                        //else
                        //{
                        //    Console.WriteLine("Field search failed.");
                        //}

                        // Regenerate field appearances.
                        doc.RefreshFieldAppearances();
                        doc.Save(output_path + "forms_test_edit.pdf", 0);
                        Console.WriteLine("Done. Results saved to forms_test_edit.pdf");
                        //Console.ReadKey();
                    }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #4
0
        static void PrintSignaturesInfo(string in_docpath)
        {
            Console.Out.WriteLine("================================================================================");
            Console.Out.WriteLine("Reading and printing digital signature information");

            using (PDFDoc doc = new PDFDoc(in_docpath))
            {
                if (!doc.HasSignatures())
                {
                    Console.Out.WriteLine("Doc has no signatures.");
                    Console.Out.WriteLine("================================================================================");
                    return;
                }
                else
                {
                    Console.Out.WriteLine("Doc has signatures.");
                }


                for (FieldIterator fitr = doc.GetFieldIterator(); fitr.HasNext(); fitr.Next())
                {
                    if (fitr.Current().IsLockedByDigitalSignature())
                    {
                        Console.Out.WriteLine("==========\nField locked by a digital signature");
                    }
                    else
                    {
                        Console.Out.WriteLine("==========\nField not locked by a digital signature");
                    }

                    Console.Out.WriteLine("Field name: " + fitr.Current().GetName());
                    Console.Out.WriteLine("==========");
                }

                Console.Out.WriteLine("====================\nNow iterating over digital signatures only.\n====================");

                DigitalSignatureFieldIterator digsig_fitr = doc.GetDigitalSignatureFieldIterator();
                for (; digsig_fitr.HasNext(); digsig_fitr.Next())
                {
                    Console.Out.WriteLine("==========");
                    Console.Out.WriteLine("Field name of digital signature: " + new Field(digsig_fitr.Current().GetSDFObj()).GetName());

                    DigitalSignatureField digsigfield = digsig_fitr.Current();
                    if (!digsigfield.HasCryptographicSignature())
                    {
                        Console.Out.WriteLine("Either digital signature field lacks a digital signature dictionary, " +
                                              "or digital signature dictionary lacks a cryptographic hash entry. " +
                                              "Digital signature field is not presently considered signed.\n" +
                                              "==========");
                        continue;
                    }

                    int cert_count = digsigfield.GetCertCount();
                    Console.Out.WriteLine("Cert count: " + cert_count);
                    for (int i = 0; i < cert_count; ++i)
                    {
                        byte[] cert = digsigfield.GetCert(i);
                        Console.Out.WriteLine("Cert #" + i + " size: " + cert.Length);
                    }

                    DigitalSignatureField.SubFilterType subfilter = digsigfield.GetSubFilter();

                    Console.Out.WriteLine("Subfilter type: " + (int)subfilter);

                    if (subfilter != DigitalSignatureField.SubFilterType.e_ETSI_RFC3161)
                    {
                        Console.Out.WriteLine("Signature's signer: " + digsigfield.GetSignatureName());

                        Date signing_time = digsigfield.GetSigningTime();
                        if (signing_time.IsValid())
                        {
                            Console.Out.WriteLine("Signing day: " + (int)signing_time.day);
                        }

                        Console.Out.WriteLine("Location: " + digsigfield.GetLocation());
                        Console.Out.WriteLine("Reason: " + digsigfield.GetReason());
                        Console.Out.WriteLine("Contact info: " + digsigfield.GetContactInfo());
                    }
                    else
                    {
                        Console.Out.WriteLine("SubFilter == e_ETSI_RFC3161 (DocTimeStamp; no signing info)\n");
                    }

                    Console.Out.WriteLine(((digsigfield.HasVisibleAppearance()) ? "Visible" : "Not visible"));

                    DigitalSignatureField.DocumentPermissions digsig_doc_perms = digsigfield.GetDocumentPermissions();
                    string[] locked_fields = digsigfield.GetLockedFields();
                    foreach (string field_name in locked_fields)
                    {
                        Console.Out.WriteLine("This digital signature locks a field named: " + field_name);
                    }

                    switch (digsig_doc_perms)
                    {
                    case DigitalSignatureField.DocumentPermissions.e_no_changes_allowed:
                        Console.Out.WriteLine("No changes to the document can be made without invalidating this digital signature.");
                        break;

                    case DigitalSignatureField.DocumentPermissions.e_formfilling_signing_allowed:
                        Console.Out.WriteLine("Page template instantiation, form filling, and signing digital signatures are allowed without invalidating this digital signature.");
                        break;

                    case DigitalSignatureField.DocumentPermissions.e_annotating_formfilling_signing_allowed:
                        Console.Out.WriteLine("Annotating, page template instantiation, form filling, and signing digital signatures are allowed without invalidating this digital signature.");
                        break;

                    case DigitalSignatureField.DocumentPermissions.e_unrestricted:
                        Console.Out.WriteLine("Document not restricted by this digital signature.");
                        break;

                    default:
                        throw new Exception("Unrecognized digital signature document permission level.");
                    }
                    Console.Out.WriteLine("==========");
                }
            }

            Console.Out.WriteLine("================================================================================");
        }
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            // Relative path to the folder containing test files.
            // string input_path =  "../../TestFiles/";
            string output_path = "../../TestFiles/Output/";

            // The vector used to store the name and count of all fields.
            // This is used later on to clone the fields
            Dictionary <string, int> field_names = new Dictionary <string, int>();

            //----------------------------------------------------------------------------------
            // Example 1: Programatically create new Form Fields and Widget Annotations.
            //----------------------------------------------------------------------------------
            try
            {
                using (PDFDoc doc = new PDFDoc())
                {
                    // Create a blank new page and add some form fields.
                    Page blank_page = doc.PageCreate();

                    // Text Widget Creation
                    // Create an empty text widget with black text.
                    TextWidget text1 = TextWidget.Create(doc, new Rect(110, 700, 380, 730));
                    text1.SetText("Basic Text Field");
                    text1.RefreshAppearance();
                    blank_page.AnnotPushBack(text1);
                    // Create a vertical text widget with blue text and a yellow background.
                    TextWidget text2 = TextWidget.Create(doc, new Rect(50, 400, 90, 730));
                    text2.SetRotation(90);
                    // Set the text content.
                    text2.SetText("    ****Lucky Stars!****");
                    // Set the font type, text color, font size, border color and background color.
                    text2.SetFont(Font.Create(doc, Font.StandardType1Font.e_helvetica_oblique));
                    text2.SetFontSize(28);
                    text2.SetTextColor(new ColorPt(0, 0, 1), 3);
                    text2.SetBorderColor(new ColorPt(0, 0, 0), 3);
                    text2.SetBackgroundColor(new ColorPt(1, 1, 0), 3);
                    text2.RefreshAppearance();
                    // Add the annotation to the page.
                    blank_page.AnnotPushBack(text2);
                    // Create two new text widget with Field names employee.name.first and employee.name.last
                    // This logic shows how these widgets can be created using either a field name string or
                    // a Field object
                    TextWidget text3 = TextWidget.Create(doc, new Rect(110, 660, 380, 690), "employee.name.first");
                    text3.SetText("Levi");
                    text3.SetFont(Font.Create(doc, Font.StandardType1Font.e_times_bold));
                    text3.RefreshAppearance();
                    blank_page.AnnotPushBack(text3);
                    Field      emp_last_name = doc.FieldCreate("employee.name.last", Field.Type.e_text, "Ackerman");
                    TextWidget text4         = TextWidget.Create(doc, new Rect(110, 620, 380, 650), emp_last_name);
                    text4.SetFont(Font.Create(doc, Font.StandardType1Font.e_times_bold));
                    text4.RefreshAppearance();
                    blank_page.AnnotPushBack(text4);

                    // Signature Widget Creation (unsigned)
                    SignatureWidget signature1 = SignatureWidget.Create(doc, new Rect(110, 560, 260, 610));
                    signature1.RefreshAppearance();
                    blank_page.AnnotPushBack(signature1);

                    // CheckBox Widget Creation
                    // Create a check box widget that is not checked.
                    CheckBoxWidget check1 = CheckBoxWidget.Create(doc, new Rect(140, 490, 170, 520));
                    check1.RefreshAppearance();
                    blank_page.AnnotPushBack(check1);
                    // Create a check box widget that is checked.
                    CheckBoxWidget check2 = CheckBoxWidget.Create(doc, new Rect(190, 490, 250, 540), "employee.name.check1");
                    check2.SetBackgroundColor(new ColorPt(1, 1, 1), 3);
                    check2.SetBorderColor(new ColorPt(0, 0, 0), 3);
                    // Check the widget (by default it is unchecked).
                    check2.SetChecked(true);
                    check2.RefreshAppearance();
                    blank_page.AnnotPushBack(check2);

                    // PushButton Widget Creation
                    PushButtonWidget pushbutton1 = PushButtonWidget.Create(doc, new Rect(380, 490, 520, 540));
                    pushbutton1.SetTextColor(new ColorPt(1, 1, 1), 3);
                    pushbutton1.SetFontSize(36);
                    pushbutton1.SetBackgroundColor(new ColorPt(0, 0, 0), 3);
                    // Add a caption for the pushbutton.
                    pushbutton1.SetStaticCaptionText("PushButton");
                    pushbutton1.RefreshAppearance();
                    blank_page.AnnotPushBack(pushbutton1);

                    // ComboBox Widget Creation
                    ComboBoxWidget combo1 = ComboBoxWidget.Create(doc, new Rect(280, 560, 580, 610));
                    // Add options to the combobox widget.
                    combo1.AddOption("Combo Box No.1");
                    combo1.AddOption("Combo Box No.2");
                    combo1.AddOption("Combo Box No.3");
                    // Make one of the options in the combo box selected by default.
                    combo1.SetSelectedOption("Combo Box No.2");
                    combo1.SetTextColor(new ColorPt(1, 0, 0), 3);
                    combo1.SetFontSize(28);
                    combo1.RefreshAppearance();
                    blank_page.AnnotPushBack(combo1);

                    // ListBox Widget Creation
                    ListBoxWidget list1 = ListBoxWidget.Create(doc, new Rect(400, 620, 580, 730));
                    // Add one option to the listbox widget.
                    list1.AddOption("List Box No.1");
                    // Add multiple options to the listbox widget in a batch.
                    string[] list_options = new string[2] {
                        "List Box No.2", "List Box No.3"
                    };
                    list1.AddOptions(list_options);
                    // Select some of the options in list box as default options
                    list1.SetSelectedOptions(list_options);
                    // Enable list box to have multi-select when editing.
                    list1.GetField().SetFlag(Field.Flag.e_multiselect, true);
                    list1.SetFont(Font.Create(doc, Font.StandardType1Font.e_times_italic));
                    list1.SetTextColor(new ColorPt(1, 0, 0), 3);
                    list1.SetFontSize(28);
                    list1.SetBackgroundColor(new ColorPt(1, 1, 1), 3);
                    list1.RefreshAppearance();
                    blank_page.AnnotPushBack(list1);

                    // RadioButton Widget Creation
                    // Create a radio button group and add three radio buttons in it.
                    RadioButtonGroup  radio_group  = RadioButtonGroup.Create(doc, "RadioGroup");
                    RadioButtonWidget radiobutton1 = radio_group.Add(new Rect(140, 410, 190, 460));
                    radiobutton1.SetBackgroundColor(new ColorPt(1, 1, 0), 3);
                    radiobutton1.RefreshAppearance();
                    RadioButtonWidget radiobutton2 = radio_group.Add(new Rect(310, 410, 360, 460));
                    radiobutton2.SetBackgroundColor(new ColorPt(0, 1, 0), 3);
                    radiobutton2.RefreshAppearance();
                    RadioButtonWidget radiobutton3 = radio_group.Add(new Rect(480, 410, 530, 460));
                    // Enable the third radio button. By default the first one is selected
                    radiobutton3.EnableButton();
                    radiobutton3.SetBackgroundColor(new ColorPt(0, 1, 1), 3);
                    radiobutton3.RefreshAppearance();
                    radio_group.AddGroupButtonsToPage(blank_page);

                    // Custom push button annotation creation
                    PushButtonWidget custom_pushbutton1 = PushButtonWidget.Create(doc, new Rect(260, 320, 360, 360));
                    // Set the annotation appearance.
                    custom_pushbutton1.SetAppearance(CreateCustomButtonAppearance(doc, false), Annot.AnnotationState.e_normal);
                    // Create 'SubmitForm' action. The action will be linked to the button.
                    FileSpec           url           = FileSpec.CreateURL(doc, "http://www.pdftron.com");
                    pdftron.PDF.Action button_action = pdftron.PDF.Action.CreateSubmitForm(url);
                    // Associate the above action with 'Down' event in annotations action dictionary.
                    Obj annot_action = custom_pushbutton1.GetSDFObj().PutDict("AA");
                    annot_action.Put("D", button_action.GetSDFObj());
                    blank_page.AnnotPushBack(custom_pushbutton1);

                    // Add the page as the last page in the document.
                    doc.PagePushBack(blank_page);

                    // If you are not satisfied with the look of default auto-generated appearance
                    // streams you can delete "AP" entry from the Widget annotation and set
                    // "NeedAppearances" flag in AcroForm dictionary:
                    //    doc.GetAcroForm().PutBool("NeedAppearances", true);
                    // This will force the viewer application to auto-generate new appearance streams
                    // every time the document is opened.
                    //
                    // Alternatively you can generate custom annotation appearance using ElementWriter
                    // and then set the "AP" entry in the widget dictionary to the new appearance
                    // stream.
                    //
                    // Yet another option is to pre-populate field entries with dummy text. When
                    // you edit the field values using PDFNet the new field appearances will match
                    // the old ones.
                    doc.RefreshFieldAppearances();

                    doc.Save(output_path + "forms_test1.pdf", 0);

                    Console.WriteLine("Done.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            //----------------------------------------------------------------------------------
            // Example 2:
            // Fill-in forms / Modify values of existing fields.
            // Traverse all form fields in the document (and print out their names).
            // Search for specific fields in the document.
            //----------------------------------------------------------------------------------
            try
            {
                using (PDFDoc doc = new PDFDoc(output_path + "forms_test1.pdf"))
                {
                    doc.InitSecurityHandler();

                    FieldIterator itr;
                    for (itr = doc.GetFieldIterator(); itr.HasNext(); itr.Next())
                    {
                        Field  field          = itr.Current();
                        string cur_field_name = field.GetName();
                        // Add one to the count for this field name for later processing
                        field_names[cur_field_name] = (field_names.ContainsKey(cur_field_name) ? field_names[cur_field_name] + 1 : 1);

                        Console.WriteLine("Field name: {0}", field.GetName());
                        Console.WriteLine("Field partial name: {0}", field.GetPartialName());
                        string str_val = field.GetValueAsString();

                        Console.Write("Field type: ");
                        Field.Type type = field.GetType();
                        switch (type)
                        {
                        case Field.Type.e_button:
                            Console.WriteLine("Button");
                            break;

                        case Field.Type.e_radio:
                            Console.WriteLine("Radio button: Value = " + str_val);
                            break;

                        case Field.Type.e_check:
                            field.SetValue(true);
                            Console.WriteLine("Check box: Value = " + str_val);
                            break;

                        case Field.Type.e_text:
                        {
                            Console.WriteLine("Text");

                            // Edit all variable text in the document
                            String old_value = "none";
                            if (field.GetValue() != null)
                            {
                                old_value = field.GetValue().GetAsPDFText();
                            }

                            field.SetValue("This is a new value. The old one was: " + old_value);
                        }
                        break;

                        case Field.Type.e_choice:
                            Console.WriteLine("Choice");
                            break;

                        case Field.Type.e_signature:
                            Console.WriteLine("Signature");
                            break;
                        }

                        Console.WriteLine("------------------------------");
                    }

                    // Search for a specific field
                    Field fld = doc.GetField("employee.name.first");
                    if (fld != null)
                    {
                        Console.WriteLine("Field search for {0} was successful", fld.GetName());
                    }
                    else
                    {
                        Console.WriteLine("Field search failed.");
                    }

                    // Regenerate field appearances.
                    doc.RefreshFieldAppearances();
                    doc.Save(output_path + "forms_test_edit.pdf", 0);
                    Console.WriteLine("Done.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            //----------------------------------------------------------------------------------
            // Sample: Form templating
            // Replicate pages and form data within a document. Then rename field names to make
            // them unique.
            //----------------------------------------------------------------------------------
            try
            {
                // Sample: Copying the page with forms within the same document
                using (PDFDoc doc = new PDFDoc(output_path + "forms_test1.pdf"))
                {
                    doc.InitSecurityHandler();

                    Page src_page = doc.GetPage(1);
                    doc.PagePushBack(src_page);                      // Append several copies of the second page
                    doc.PagePushBack(src_page);                      // Note that forms are successfully copied
                    doc.PagePushBack(src_page);
                    doc.PagePushBack(src_page);

                    // Now we rename fields in order to make every field unique.
                    // You can use this technique for dynamic template filling where you have a 'master'
                    // form page that should be replicated, but with unique field names on every page.
                    foreach (KeyValuePair <string, int> cur_field in field_names)
                    {
                        RenameAllFields(doc, cur_field.Key, cur_field.Value);
                    }

                    doc.Save(output_path + "forms_test1_cloned.pdf", 0);
                    Console.WriteLine("Done.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            //----------------------------------------------------------------------------------
            // Sample:
            // Flatten all form fields in a document.
            // Note that this sample is intended to show that it is possible to flatten
            // individual fields. PDFNet provides a utility function PDFDoc.FlattenAnnotations()
            // that will automatically flatten all fields.
            //----------------------------------------------------------------------------------
            try
            {
                using (PDFDoc doc = new PDFDoc(output_path + "forms_test1.pdf"))
                {
                    doc.InitSecurityHandler();

                    bool auto = true;
                    if (auto)
                    {
                        doc.FlattenAnnotations();
                    }
                    else                      // Manual flattening
                    {
                        // Traverse all pages
                        PageIterator pitr = doc.GetPageIterator();
                        for (; pitr.HasNext(); pitr.Next())
                        {
                            Page page = pitr.Current();
                            for (int i = page.GetNumAnnots() - 1; i >= 0; --i)
                            {
                                Annot annot = page.GetAnnot(i);
                                if (annot.GetType() == Annot.Type.e_Widget)
                                {
                                    annot.Flatten(page);
                                }
                            }
                        }
                    }

                    doc.Save(output_path + "forms_test1_flattened.pdf", 0);
                    Console.WriteLine("Done.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }