Adding listchoices to Pdfform with c# code

2019-07-11 06:56发布

I'm trying to add choices to a List-field within a pdf form via C# and the itextsharp library. But i cant find a way to do this. The form already exists, i created it with Acrobat. I would like that the Listfield choices from the PDF are the same as in my program. Therefore I want to create the options in the list-fields via itextsharp to reduce the maintenance. But I cant find away to do this. With the PDFstamper from the library I am able to fill the Fields from the form. And Color some fields. Is there a possibility to add options to a List-field via c# Code ? Would be great if someone knows the answer and shows me a way to realize this.

1条回答
霸刀☆藐视天下
2楼-- · 2019-07-11 07:13

If you are using iText 7, it's easy. That's explained in chapter 5 of the iText 7 jump-start tutorial: Manipulating an existing PDF document

PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
Map<String, PdfFormField> fields = form.getFormFields();
List<PdfString> options = new ArrayList<PdfString>();
options.add(new PdfString("Any"));
options.add(new PdfString("8.30 am - 12.30 pm"));
options.add(new PdfString("12.30 pm - 4.30 pm"));
options.add(new PdfString("4.30 pm - 8.30 pm"));
options.add(new PdfString("8.30 pm - 12.30 am"));
options.add(new PdfString("12.30 am - 4.30 am"));
options.add(new PdfString("4.30 am - 8.30 am"));
PdfArray arr = new PdfArray(options);
fields.get("shift").setOptions(arr);

iText 7 currently only exists for Java; the C# version will be released in 2 weeks.

If you are using iText 5, then you need to consult Chapter 8 of iText in Action - Second Edition, more specifically at the ChoiceFields example:

AcroFields form = stamper.getAcroFields();
form.setField("choice_1", "NL");
form.setListSelection("choice_2", new String[]{"German", "Spanish"});
String[] languages = form.getListOptionDisplay("choice_3");
String[] exportvalues = form.getListOptionExport("choice_3");
int n = languages.length;
String[] new_languages = new String[n + 2];
String[] new_exportvalues = new String[n + 2];
for (int i = 0; i < n; i++) {
    new_languages[i] = languages[i];
    new_exportvalues[i] = exportvalues[i];
}
new_languages[n] = "Chinese";
new_exportvalues[n] = "CN";
new_languages[n + 1] = "Japanese";
new_exportvalues[n + 1] = "JP";
form.setListOption("choice_3", new_exportvalues, new_languages);
form.setField("choice_3", "CN");
form.setField("choice_4", "Japanese");

The code above is Java code, but you could also interpret it as "pseudo code" if you don't want to read Java.

All the examples from the iText in Action book are converted to C#. See ChoiceFields.cs for the full iText 5 example.

Important: I am assuming that you have created the form with Acrobat and that your form is based on AcroForm technology. If you have created your form with LiveCycle, you have an XFA form. The code shared in this answer will not work for XFA forms.

查看更多
登录 后发表回答