如何使用iTextSharp填充单选按钮 [英] How to use iTextSharp to populate radio button

查看:86
本文介绍了如何使用iTextSharp填充单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我的SQL表:

我正在尝试关注此网站:网站示例

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

PDFHelper类:

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

推荐答案

您的问题令人困惑,因为它使用了未引用iTextSharp的PdfReader类的reader对象,并且使用了其中的formFieldMap对象类型未知(它似乎与iTextSharp无关).非常欢迎您进行编辑以理解该问题.

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.

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

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.

在这种情况下,没有人不会看到您告诉您选择哪个值来设置单选按钮,而不会看到PDF.请下载我的书的第6章,并阅读第6.3.5节,尤其是在检查表单及其字段.在第183页上,您可以看到一组单选按钮的可能值为关"(未选择单选按钮)或在表单本身中定义的代码.

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.

例如:在本书的示例中,category组的可能值是spectoroanim等...

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

或:

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

或:

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

以此类推.

因此,如果要在名为pg1rb的单选按钮组中设置单选按钮,则首先需要知道哪些是可能的值.您假定可能的值为是"和否",在这种情况下,您可以使用:

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

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

但是可能的值也可以是"1"和"0","On"和"Off","true"和"false",....可能的值由创建表单的人选择.

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.

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

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

检查写入sb对象的内容,您将找到所需的值.

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

这篇关于如何使用iTextSharp填充单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆