/// <summary> /// METODO 4: Selezionare un acrofield di tipo radiobutton /// Selecting a radiobutton acrofield /// </summary> /// <param name="fieldName">string Name of the radiobutton to select</param> /// <param name="valueToSelect">string Value to select</param> public void SelectRadiobutton(string fieldName, string valueToSelect) { //Checking if argument is null if (fieldName == null) { throw new ArgumentNullException("fieldName"); } if (valueToSelect == null) { throw new ArgumentNullException("valueToSelect"); } //Getting forms AcroFields form = stamper.AcroFields; //Checking if document has no fields if (form.Fields.Count == 0) { throw new DocumentHasNoFieldsException(); } //Looking for a radiobutton with the given name var result = form.Fields .Where(kvp => form.GetTranslatedFieldName(kvp.Key).Equals(fieldName) && form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_RADIOBUTTON) .Select(kvp => new { kvp.Key, States = form.GetAppearanceStates(kvp.Key) }) ?.FirstOrDefault(); //Checking if the query had results if (result == null) { throw new FieldNotFoundException(fieldName, AcroFields.FIELD_TYPE_RADIOBUTTON); } //Checking if value to select exists if (!result.States.Contains(valueToSelect)) { throw new RadiobuttonValueNotFoundException(fieldName, valueToSelect); } //Setting the value form.SetField(form.GetTranslatedFieldName(result.Key), valueToSelect); }
/// <summary> /// METODO 2: Flaggare un acrofield di tipo checkbox /// Looking for a checkbox and checking it /// </summary> /// <param name="fieldName">string Name of the checkbox to check</param> /// <returns>bool Operation result</returns> public void FlagCheckbox(string fieldName) { //Checking if argument is null if (fieldName == null) { throw new ArgumentNullException(fieldName); } //Getting forms AcroFields form = stamper.AcroFields; //Checking if document has no fields if (form.Fields.Count == 0) { throw new DocumentHasNoFieldsException(); } //Looking for a checkbox with the given name var result = form.Fields .Where(kvp => form.GetTranslatedFieldName(kvp.Key).Equals(fieldName) && form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_CHECKBOX ) .Select(kvp => new { kvp.Key, Name = form.GetTranslatedFieldName(kvp.Key), Values = form.GetAppearanceStates(form.GetTranslatedFieldName(kvp.Key)) }) ?.FirstOrDefault(); //Checking if the query had results if (result == null) { throw new FieldNotFoundException(fieldName, AcroFields.FIELD_TYPE_CHECKBOX); } //If the box isn't checked, we check it if (form.GetField(result.Key).Equals(result.Values[0]) || form.GetField(result.Key).Length == 0) { //Changing state and returning true (in case of error it returns false) form.SetField(result.Name, result.Values[1]); } }
/// <summary> /// METODO 5: Inserire un testo in un acrofield ti tipo testo /// Inserting the given text into a textfield /// </summary> /// <param name="fieldName">string Name of the textfield to modify</param> /// <param name="text">string Text to insert</param> public void InsertTextInField(string fieldName, string text) { //Checking if argument is null if (fieldName == null) { throw new ArgumentNullException("fieldName"); } if (text == null) { throw new ArgumentNullException("valueToSelect"); } //Getting forms AcroFields form = stamper.AcroFields; //Checking if document has no fields if (form.Fields.Count == 0) { throw new DocumentHasNoFieldsException(); } //Looking for a text-field with the given name var result = form.Fields .Where(kvp => form.GetTranslatedFieldName(kvp.Key).Equals(fieldName) && form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_TEXT ) .Select(kvp => form.GetTranslatedFieldName(kvp.Key)) ?.FirstOrDefault(); //Checking if the query had results if (result == null) { throw new FieldNotFoundException(fieldName, AcroFields.FIELD_TYPE_RADIOBUTTON); } //Setting the given text form.SetField(fieldName, text); }
/// <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); }
/// <summary> /// Fill a fillable form fields /// </summary> public void FillForm() { using (PdfReader reader = new PdfReader(_pathSource)) { using (PdfStamper stamper = new PdfStamper(reader, new FileStream(_pathDest, FileMode.Create))) { AcroFields form = stamper.AcroFields; foreach (KeyValuePair <string, AcroFields.Item> kvp in form.Fields) { string translatedFileName = form.GetTranslatedFieldName(kvp.Key); var value = _values.FirstOrDefault(v => v.Key == translatedFileName); if (value.Value != null) { form.SetField(translatedFileName, value.Value.ToString()); } } } } }
/// <summary> /// METODO 1: ricerca di un acrofield generico per name, /// l’oggetto ritornato deve indicare il tipo di acrofield(checkbox, textbox, signaturefield, radiobutton). /// </summary> /// <param name="fieldName">Field name</param> /// <returns>Field name</returns> public int GetAcrofieldType(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 checkbox/radiobutton/signature/text withe the given name var result = form.Fields .Where(kvp => form.GetTranslatedFieldName(kvp.Key).Equals(fieldName) && ( form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_CHECKBOX || form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_RADIOBUTTON || form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_SIGNATURE || form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_TEXT ) ) .Select(kvp => form.GetFieldType(kvp.Key))?.FirstOrDefault(); //If field not found (default is 0), throw an exception if (result == 0) { throw new FieldNotFoundException(fieldName); } //Returning the field's type return((int)result); }
//Read all 'Form values/keys' from an existing multi-page PDF document public void ReadPDFformDataPageWise() { PdfReader reader = new PdfReader(Server.MapPath(P_InputStream3)); AcroFields form = reader.AcroFields; try { for (int page = 1; page <= reader.NumberOfPages; page++) { foreach (KeyValuePair<string, AcroFields.Item> kvp in form.Fields) { switch (form.GetFieldType(kvp.Key)) { case AcroFields.FIELD_TYPE_CHECKBOX: case AcroFields.FIELD_TYPE_COMBO: case AcroFields.FIELD_TYPE_LIST: case AcroFields.FIELD_TYPE_RADIOBUTTON: case AcroFields.FIELD_TYPE_NONE: case AcroFields.FIELD_TYPE_PUSHBUTTON: case AcroFields.FIELD_TYPE_SIGNATURE: case AcroFields.FIELD_TYPE_TEXT: int fileType = form.GetFieldType(kvp.Key); string fieldValue = form.GetField(kvp.Key); string translatedFileName = form.GetTranslatedFieldName(kvp.Key); break; } } } } catch { } finally { reader.Close(); } }
//Select Pdf private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { PdfReader.unethicalreading = true; inputFileName = openFileDialog1.SafeFileName; extension = Path.GetExtension(inputFileName); this.PDFPath = openFileDialog1.FileName; if (extension == ".pdf") { PdfReader reader = new PdfReader(this.PDFPath); AcroFields form = reader.AcroFields; pdfForm = reader; // 2. Get the acroform! if (pdfForm == null) { Console.WriteLine("No form available"); } else { try { foreach (KeyValuePair <string, AcroFields.Item> kvp in form.Fields) { switch (form.GetFieldType(kvp.Key)) { case AcroFields.FIELD_TYPE_CHECKBOX: // string translatedCheckboxName = form.GetTranslatedFieldName(kvp.Key); //checkboxCount.Add(translatedCheckboxName); // break; case AcroFields.FIELD_TYPE_COMBO: case AcroFields.FIELD_TYPE_LIST: case AcroFields.FIELD_TYPE_RADIOBUTTON: case AcroFields.FIELD_TYPE_NONE: case AcroFields.FIELD_TYPE_PUSHBUTTON: case AcroFields.FIELD_TYPE_SIGNATURE: case AcroFields.FIELD_TYPE_TEXT: int fileType = form.GetFieldType(kvp.Key); string fieldValue = form.GetField(kvp.Key); string translatedFileName = form.GetTranslatedFieldName(kvp.Key); formsNtype.Add(translatedFileName); break; } } } catch { } /*finally * { * reader.Close(); * }*/ Console.WriteLine("Form Selected"); // 3. Filling the acroform fields... } } else if (extension == ".XLSX") { ReadExistingExcel(JsonData); } }
private void button3_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog1 = new SaveFileDialog { Filter = "PDF files|*.pdf", DefaultExt = "pdf", AddExtension = true }; saveFileDialog1.ShowDialog(); path = saveFileDialog1.FileName; Console.Write(JsonData); using (PdfStamper stamper = new PdfStamper(pdfForm, new FileStream(path, FileMode.Create))) { AcroFields fields = stamper.AcroFields; // fields.GenerateAppearances = true; // String[] checkboxstates = fields.GetAppearanceStates("topmostSubform[0].Page1[0].CheckBox2[0]"); // set form fields foreach (KeyValuePair <string, AcroFields.Item> kvp in fields.Fields) { count++; if (formsNtype[count - 1].StartsWith("topmostSubform")) { Console.Write(formsNtype[count - 1].Substring(27, formsNtype[count - 1].Length - 27) + System.Environment.NewLine); currentCheckbox = null; currentItem = null; } else { Console.Write(formsNtype[count - 1] + System.Environment.NewLine); currentCheckbox = "0"; currentItem = "0"; } switch (fields.GetFieldType(kvp.Key)) { case AcroFields.FIELD_TYPE_CHECKBOX: currentCheckbox = string.IsNullOrEmpty(currentCheckbox) ? formsNtype[count - 1].Substring(27, formsNtype[count - 1].Length - 27): fields.GetTranslatedFieldName(kvp.Key); //currentCheckbox = fields.GetTranslatedFieldName(kvp.Key); fields.SetField(currentCheckbox, JsonData[currentCheckbox].ToString()); break; case AcroFields.FIELD_TYPE_COMBO: case AcroFields.FIELD_TYPE_LIST: case AcroFields.FIELD_TYPE_RADIOBUTTON: String[] radioStates = fields.GetAppearanceStates("topmostSubform[0].Page1[0].RadioButtonList[0]"); string currentRadio = formsNtype[count - 1].Substring(27, formsNtype[count - 1].Length - 27); fields.SetField(currentRadio, JsonData[currentRadio].ToString()); break; case AcroFields.FIELD_TYPE_NONE: case AcroFields.FIELD_TYPE_PUSHBUTTON: case AcroFields.FIELD_TYPE_SIGNATURE: case AcroFields.FIELD_TYPE_TEXT: currentItem = string.IsNullOrEmpty(currentItem) ? formsNtype[count - 1].Substring(27, formsNtype[count - 1].Length - 27): fields.GetTranslatedFieldName(kvp.Key); // currentItem = fields.GetTranslatedFieldName(kvp.Key); fields.SetField(currentItem, JsonData[currentItem].ToString()); break; //fields.GenerateAppearances = true; // Console.Write(formsNtype[count - 1] + System.Environment.NewLine); } } // flatten form fields and close document stamper.FormFlattening = true; stamper.Close(); } }
/// <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; } } }