我找到了一个很好的示例,展示了如何在此处为新复选框设置复选框导出值(以及其他属性)(请参见“ CreateCheckBoxList”示例):
https://simpledotnetsolutions.wordpress.com/2012/11/01/itextsharp-creating-form-fields/
但是,我需要更改现有复选框的导出值。我尝试以几种不同的方式修改上述示例,但没有任何效果。
请澄清一下,下图显示了我希望使用iText以编程方式更改的checkbox属性:
答案 0 :(得分:0)
PdfReader reader = new PdfReader(@"C:\test.pdf");
AcroFields fields = reader.AcroFields;
int i = 0;
string checkboxExportValues = "Count\tName\tExport Value\r\n";
//loop all fields in the pdf
foreach (KeyValuePair<string, AcroFields.Item> kpv in fields.Fields)
{
string exportValue = "";
switch (fields.GetFieldType(kpv.Key))
{
//if the field is a checkbox, get the field's name and export value
case AcroFields.FIELD_TYPE_CHECKBOX:
AcroFields checkbox = reader.AcroFields;
String[] values = checkbox.GetAppearanceStates(kpv.Key);
//get the last checkbox state, which represents a selected checkbox
foreach (String value in values)
{
exportValue = value;
}
checkboxExportValues = checkboxExportValues + i + "\t" + kpv.Key + "\t" + exportValue + "\r\n";
break;
}
i++;
}
reader.Close();
File.WriteAllText(@"C:\exportValues.txt", checkboxExportValues);
/*
Sample output:
Count Name Export Value
1 Check Box106 Yes
2 Check Box107 Yes
3 Check Box122 1
4 Check Box127 On
5 Check Box128 2
*/
答案 1 :(得分:0)
我也有相同的要求,并找到了您的帖子。由于我没有找到任何相关的内容,因此我自己实施了它。不幸的是,它是Java语言,但您可以将其转换为C#。请注意:
下面是代码:
[...]
case (AcroFields.FIELD_TYPE_CHECKBOX):
PdfDictionary ap = item.getWidget(i).getAsDict(PdfName.AP);
if (ap != null) {
PdfDictionary normalAp = ap.getAsDict(PdfName.N);
changeAppearanceStateNames(normalAp, "NewExportValue", "Check Box106");
PdfDictionary downAp = ap.getAsDict(PdfName.D);
changeAppearanceStateNames(downAp, "NewExportValue", "Check Box106"););
PdfDictionary rolloverAp = ap.getAsDict(PdfName.R);
changeAppearanceStateNames(rolloverAp, "NewExportValue", "Check Box106");
}
break; [...]
private void changeAppearanceStateNames(PdfDictionary appearanceSubdictionary, String newValue, String fieldname) throws NotSpecCompliantException {
if (appearanceSubdictionary != null) {
if(appearanceSubdictionary.size()>2) throw Exception ...
String appearanceSubDictionaryName=null;
//detect name for the checked value
for(Object key : appearanceSubdictionary.getKeys()) {
String name = PdfName.decodeName(((PdfName)key).toString());
if(!name.equals("Off")) {
appearanceSubDictionaryName=name;
}
}
//update it
if(appearanceSubDictionaryName!=null) {
PdfObject appearanceSubDictionaryValue = appearanceSubdictionary.get(new PdfName(appearanceSubDictionaryName));
appearanceSubdictionary.remove(new PdfName(appearanceSubDictionaryName));
appearanceSubdictionary.put(new PdfName(newValue),appearanceSubDictionaryValue);
}
//else {
//theoretically create a new appearance here. Details can be seen in the #RadioCheckField
//however since only the export value should be changed it is assumed that the actual appearance dictionary does already exists
//}
}
}