1

I have a table and one of the column is YesNo which is of type varchar(3). I have two radio buttons in my PDF file which is in an array:

pg1rb (radio group field)
 --> c1 (radio button one (yes))
 --> c2 (radio button two (no))

enter image description here

I set textboxes like this in my code:

formFieldMap["topmostSubform[0].Page1[0].f1_01_0_[0]"] = reader.GetValue(0).ToString();

How can I select YES or NO radio button based on the row value?

Can I do something like this:

formFieldMap["pg1rb"] = reader.GetBoolean(10); //10 is the 9th column which is Yes/No value

Or do I get the value and based on it select the radio button, something like this:

if (reader.GetValue(10).ToString() == "Yes") {
     formFieldMap["pg1rb"][c1] = "1";
else {
     formFieldMap["pg1rb"][c2] = "1";
}

My SQL table:

enter image description here

I am trying to follow this site: Website example

My function that actually does the conversion:

public void writeData(string k, string c)
    {
        Conn = new SqlConnection(cString);
        Conn.Open();

        //MessageBox.Show(k);
        //MessageBox.Show(c);

        var pdfPath = Path.Combine(Server.MapPath("~/PDFTemplates/forme.pdf"));

        // Get the form fields for this PDF and fill them in!
        var formFieldMap = PDFHelper.GetFormFieldNames(pdfPath);

        //if more than multiple entries, verify by name and the last four ssn
        sqlCode = "SELECT * FROM [DSPCONTENT01].[dbo].[TablePDFTest] WHERE [name] = '" + k + "' AND [ssn3] = " + c + "";
        //sqlCode = "SELECT * FROM [DSPCONTENT01].[dbo].[TablePDFTest] WHERE [name] = @name2 AND [ssn3] = @ssnnum";
        //MessageBox.Show("" + sqlCode.ToString());

        using (SqlCommand command = new SqlCommand(sqlCode, Conn))
        {
            command.CommandType = CommandType.Text;
            //command.Parameters.AddWithValue("name2", k);
            //command.Parameters.AddWithValue("ssnnum", c);

            using (reader = command.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    if (reader.Read())
                    {
                        //MessageBox.Show(reader.GetValue(0).ToString());
                        /*formFieldMap["topmostSubform[0].Page1[0].f1_01_0_[0]"] = reader.GetValue(0).ToString();
                        formFieldMap["topmostSubform[0].Page1[0].f1_02_0_[0]"] = reader.GetValue(1).ToString();
                        formFieldMap["topmostSubform[0].Page1[0].f1_04_0_[0]"] = reader.GetValue(2).ToString();
                        formFieldMap["topmostSubform[0].Page1[0].f1_05_0_[0]"] = reader.GetValue(3).ToString();
                        formFieldMap["topmostSubform[0].Page1[0].f1_07_0_[0]"] = reader.GetValue(4).ToString();
                        formFieldMap["topmostSubform[0].Page1[0].social[0].TextField1[0]"] = reader.GetValue(5).ToString();
                        formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[0]"] = reader.GetValue(6).ToString();
                        formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[1]"] = reader.GetValue(7).ToString();
                        formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[2]"] = reader.GetValue(8).ToString();
                        formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[3]"] = reader.GetValue(9).ToString();*/
                        if (reader.GetValue(10).ToString() == "Yes")
                        {
                            //MessageBox.Show("YES");
                        }
                        else if (reader.GetValue(10).ToString() == "No")
                        {
                            //MessageBox.Show("NO");
                        }
                    }
                }
            }
        }

        // Requester's name and address (hard-coded)
        formFieldMap["topmostSubform[0].Page1[0].f1_06_0_[0]"] = "Medical Group\n12 Westchester Ave\nPurchase, NY 10121";

        var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);

        PDFHelper.ReturnPDF(pdfContents, "Completed-W9.pdf");
    }

The PDFHelper class:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.IO;
using iTextSharp.text.pdf;

public class PDFHelper
{
    public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
    {
        var fields = new Dictionary<string, string>();

        var reader = new PdfReader(pdfPath);
        foreach (DictionaryEntry entry in reader.AcroFields.Fields)
            fields.Add(entry.Key.ToString(), string.Empty);
        reader.Close();

        return fields;
    }

    public static byte[] GeneratePDF(string pdfPath, Dictionary<string, string> formFieldMap)
    {
        var output = new MemoryStream();
        var reader = new PdfReader(pdfPath);
        var stamper = new PdfStamper(reader, output);
        var formFields = stamper.AcroFields;

        foreach (var fieldName in formFieldMap.Keys)
            formFields.SetField(fieldName, formFieldMap[fieldName]);

        stamper.FormFlattening = false;
        stamper.Close();
        reader.Close();

        return output.ToArray();
    }

    // See http://stackoverflow.com/questions/4491156/get-the-export-value-of-a-checkbox-using-itextsharp/
    public static string GetExportValue(AcroFields.Item item)
    {
        var valueDict = item.GetValue(0);
        var appearanceDict = valueDict.GetAsDict(PdfName.AP);

        if (appearanceDict != null)
        {
            var normalAppearances = appearanceDict.GetAsDict(PdfName.N);
            // /D is for the "down" appearances.

            // if there are normal appearances, one key will be "Off", and the other
            // will be the export value... there should only be two.
            if (normalAppearances != null)
            {
                foreach (var curKey in normalAppearances.Keys)
                    if (!PdfName.OFF.Equals(curKey))
                        return curKey.ToString().Substring(1); // string will have a leading '/' character, so remove it!
            }
        }

        // if that doesn't work, there might be an /AS key, whose value is a name with 
        // the export value, again with a leading '/', so remove it!
        var curVal = valueDict.GetAsName(PdfName.AS);
        if (curVal != null)
            return curVal.ToString().Substring(1);
        else
            return string.Empty;
    }

    public static void ReturnPDF(byte[] contents)
    {
        ReturnPDF(contents, null);
    }

    public static void ReturnPDF(byte[] contents, string attachmentFilename)
    {
        var response = HttpContext.Current.Response;

        if (!string.IsNullOrEmpty(attachmentFilename))
            response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);

        response.ContentType = "application/pdf";
        response.BinaryWrite(contents);
        response.End();
    }
}

enter image description here

Si8
  • 9,141
  • 22
  • 109
  • 221
  • 1
    Are you sure this is iTextSharp code? Because I'm the original developer of iText (and by extension iTextSharp) and I don't see any iTextSharp code in your question. – Bruno Lowagie Jun 05 '14 at 15:11
  • @BrunoLowagie Hey thanks for the reply. Yes I am sure. I have the itextsharp.dll in my Bin directory and everything. Have you looked at the site example I provided? I was using his code and everything is working but I am not sure how to fill in the RadioButtons... There is a helper class that I am using which makes use of the itextsharp codes. – Si8 Jun 05 '14 at 15:15
  • I would rather see your PDF document. The names of the fields look like XFA fields rather than AcroForm fields. If they are XFA fields, the code from the site you refer to won't work. Furthermore, nobody can answer your question without knowing the possible appearance states of your radio buttons. – Bruno Lowagie Jun 05 '14 at 15:29
  • The `reader` object in your code, is it a `PdfReader` instance? I guess not. That's confusing. And what is that `FormFieldMap`? That's not an iTextSharp class either, is it? – Bruno Lowagie Jun 05 '14 at 15:31
  • I added the code that I am invoking to create the PDF. Hopefully it will shed some light on what I am using? I have just started using iTextSharp so not sure how to exactly answer your questions correctly... I also added the PDF Helper class which is using the iTextSharp.text.pdf namespace. – Si8 Jun 05 '14 at 15:38

1 Answers1

4

Your question was confusing because it used a reader object that didn't refer to iTextSharp's PdfReader class and it used a formFieldMap object of which the type was unknown (it doesn't seem related to iTextSharp). Your edit was very welcome to understand the question.

The field names you mention look as if they are fields in an XFA form, but the article you refer to talks about filling out AcroForm documents, so let's assume that your form was indeed born as an XFA form, but later on converted to an AcroForm.

In this case, nobody will be able to tell you which values to pick to set the radio buttons without seeing the PDF. Please download chapter 6 of my book and read section 6.3.5, more specifically where it says Inspecting the form and its fields. On page 183, you can read that the possible values for a group of radio buttons is either "Off"–no radio button is selected— or a code that is defined in the form itself.

For instance: in the example from the book, the possible values for the category group were spec, toro, anim, etc...

This means that you can set a radio box in that group like this:

formFields.SetField("category", "spec");

or:

formFields..SetField("category", "toro");

or:

formFields.SetField("category", "anim");

and so on.

So, if you want to set a radio button in a radiogroup named pg1rb, you first need to know which are the possible values. You assume that the possible values are "Yes" and "No" in which case you could use:

formFields.SetField("pg1rb", "Yes");

or

formFields.SetField("pg1rb", "No");

But the possible values could also be "1" and "0", "On" and "Off", "true" and "false",... The possible values were chosen by the person who created the form.

You can get these values programmatically by using the code from page 182:

StringBuilder sb = new StringBuilder();
sb.Append("Possible values for pg1rb:");
sb.Append(Environment.NewLine);
states = form.GetAppearanceStates("pg1rb");
for (int i = 0; i < states.Length - 1; i++) {
    sb.Append(states[i]);
    sb.Append(", ");
}
sb.Append(states[states.Length - 1]);

Inspect what was written to the sb object and you have the values you are looking for.

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • Thank you for the great answer. I created the form in Adobe Pro XI and when I double click on either radio button and the Radio Button Properties open up and I only see the Name field which is `pg1rb`. it's the same for either radio buttons – Si8 Jun 05 '14 at 15:56
  • I know it's too much to ask but I can send you my project and you can take a look to see how I can achieve what I am looking to do... I might have checkboxes and radio buttons. – Si8 Jun 05 '14 at 16:01
  • If you do that, I'll have to send you an invoice. If you have a commercial license for your use of iText, you can ask our support team and they can also help you out. If you are making money with iTextSharp and not paying for your use of iTextSharp, then you shouldn't expect premium support. – Bruno Lowagie Jun 05 '14 at 16:09
  • This is a personal project I am working on. Not intended for making money :) – Si8 Jun 05 '14 at 16:11
  • "I might have checkboxes and radio buttons". To make sure, why don't you have a look at the internal structure of the PDF using iText RUPS: http://itextpdf.com/product/itext_rups That's how I check which values to use when filling out a check box or a radio field. – Bruno Lowagie Jun 05 '14 at 16:21
  • Thank you for the link. I just opened my PDF and for some reason it is skipping the Radio button group... hmmmmm – Si8 Jun 05 '14 at 16:28
  • It seems everytime I modify something in the PDF, it goes to the bottom and not skipping it. So I updated my question with what I see using iText RUP. Lets say I wanted to fill it out based on the YES/NO text, how can I do it with my code? – Si8 Jun 05 '14 at 17:04
  • That Worked! After 'multiple', wrong turns, trying to set radio-buttons, the answer is so simple....and correct. THank you. – jdosser Jan 30 '20 at 17:32