如何使用iTextSharp填充单选按钮

时间:2014-06-05 14:52:09

标签: c# pdf itextsharp

我有一个表,其中一列是YesNo,类型为varchar(3)。我的PDF文件中有两个单选按钮,它们是一个数组:

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

enter image description here

我在我的代码中设置了这样的文本框:

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

如何根据行值选择YES或NO单选按钮?

我可以这样做:

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

或者我得到这个值并根据它选择单选按钮,如下所示:

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

我的SQL表:

enter image description here

我正在尝试关注此网站:Website example

我实际进行转换的功能:

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");
    }

PDFHelper类:

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

1 个答案:

答案 0 :(得分:3)

您的问题令人困惑,因为它使用的reader对象没有引用iTextSharp的PdfReader类,而且它使用了formFieldMap类型的category对象是未知的(它似乎与iTextSharp无关)。非常欢迎您的编辑了解这个问题。

您提到的字段名称看起来好像是XFA表单中的字段,但您引用的文章谈到填写AcroForm文档,因此我们假设您的表单确实是作为XFA表单生成的,但后来转换为AcroForm。

在这种情况下,没有人能够告诉您选择哪些值来设置单选按钮而不会看到PDF。请下载chapter 6 of my book并阅读第6.3.5节,更具体地说是检查表单及其字段。在页183,您可以读到一组单选按钮的可能值是&#34;关&#34; - 没有选择单选按钮 - 或在表单中定义的代码。

例如:在本书的示例中,spec组的可能值为toroanimformFields.SetField("category", "spec"); 等......

这意味着你可以在这个组中设置一个单选框:

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

或:

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

或:

pg1rb

等等。

因此,如果要在名为formFields.SetField("pg1rb", "Yes"); 的无线电组中设置单选按钮,首先需要知道哪些是可能的值。您假设可能的值为&#34;是&#34;和&#34;不&#34;在这种情况下,您可以使用:

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

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]);

但可能的值也可能是&#34; 1&#34;和&#34; 0&#34;,&#34; On&#34;和&#34;关&#34;,&#34;真&#34;和&#34; false&#34;,......可能的值是由创建表单的人选择的。

您可以使用第182页的代码以编程方式获取这些值:

sb

检查写入{{1}}对象的内容,并获得您要查找的值。