使用 PDFSharp 填充 PdfRadioButtonField

Populate PdfRadioButtonField using PDFSharp

我正在使用来自 http://www.pdfsharp.net 的 PDFSharp 版本 1.50.4740-beta5,它是我从 NuGet 安装的。

我可以填写文本表单域和复选框表单域,但我根本无法使用单选按钮。我没有收到错误。 SelectedIndex在我设置为1前后都是-1。

Stack Overflow 上的几篇文章帮助我走到了这一步。有没有人使用这个产品成功地填充了单选按钮表单字段? 这是示例 PDF 的 link:http://www.myblackmer.com/bluebook/interactiveform_enabled.pdf

(在你推荐iTextPdf之前,我已经评估过了,Aspose.PDF不实用)

        //using PdfSharp.Pdf.IO;
        //using PdfSharp.Pdf;
        //using PdfSharp.Pdf.AcroForms;
        string fileName = "x:\interactiveform_enabled.pdf";
        PdfSharp.Pdf.PdfDocument pdfDocument = PdfReader.Open(fileName);

        //The populated fields are not visible by default
        if (pdfDocument.AcroForm.Elements.ContainsKey("/NeedAppearances"))
        {
            pdfDocument.AcroForm.Elements["/NeedAppearances"] = new PdfBoolean(true);
        }
        else
        {
            pdfDocument.AcroForm.Elements.Add("/NeedAppearances", new PdfBoolean(true));
        }

        PdfRadioButtonField currentField = (PdfRadioButtonField)(pdfDocument.AcroForm.Fields["Sex"]);
        currentField.ReadOnly = false;
        currentField.SelectedIndex = 1;

        pdfDocument.Flatten();
        pdfDocument.Save("x:\interactiveform_enabled_2.pdf");

以下对我有用:

  1. 找出单选按钮的可能值,例如使用 PDF 工具
  2. Value 属性 与 PdfName 实例一起使用(不是 PdfString!)
  3. 在值名称
  4. 前使用前缀/

例如,如果要设置选项 "choice1" 选择:

var radio = (PdfRadioButtonField)form.Fields["MyRadioButtonField"];
radio.Value = new PdfName("/choice1");

我在 https://forum.pdfsharp.net/viewtopic.php?f=2&t=632

找到了解决方案

由于这是 Google 搜索“PDFSharp radio buttons”时的第一名,我想我会分享对我有用的东西。

我为 PdfRadioButtonField 对象创建了扩展函数:

  • 获取所有选项值及其索引
  • 通过索引号设置单选字段的值
  • 按值设置单选字段的值

在下面的例子中,ErPdfRadioOption是:

public class ErPdfRadioOption
{
    public int Index { get; set; }
    public string Value { get; set; }
}

获取单选字段的所有可用选项


public static List<ErPdfRadioOption> FindOptions(this PdfRadioButtonField source) {
    if (source == null) return null;
    List<ErPdfRadioOption> options = new List<ErPdfRadioOption>();

    PdfArray kids = source.Elements.GetArray("/Kids");

    int i = 0;
    foreach (var kid in kids) {
        PdfReference kidRef = (PdfReference)kid;
        PdfDictionary dict = (PdfDictionary)kidRef.Value;
        PdfDictionary dict2 = dict.Elements.GetDictionary("/AP");
        PdfDictionary dict3 = dict2.Elements.GetDictionary("/N");

        if (dict3.Elements.Keys.Count != 2)
            throw new Exception("Option dictionary should only have two values");

        foreach (var key in dict3.Elements.Keys)
            if (key != "/Off") { // "Off" is a reserved value that all non-selected radio options have
                ErPdfRadioOption option = new ErPdfRadioOption() { Index = i, Value = key };
                options.Add(option);
            }
        i++;
    }

    return options;
}

用法

PdfDocument source;
PdfAcroField field = source.AcroForm.Fields[...]; //name or index of the field
PdfRadioButtonField radioField = field as PdfRadioButtonField;
return radioField.FindOptions();

结果 (JSON)


[
  {
    "Index": 0,
    "Value": "/Choice1"
  },
  {
    "Index": 1,
    "Value": "/Choice2"
  },
  {
    "Index": 2,
    "Value": "/Choice3"
  }
]

通过索引设置单选字段的选项

您可能认为这就是 SelectedIndex 属性 的用途...但显然不是。


public static void SetOptionByIndex(this PdfRadioButtonField source,int index) {
    if (source == null) return;
    List<ErPdfRadioOption> options = source.FindOptions();
    ErPdfRadioOption selectedOption = options.Find(x => x.Index == index);
    if (selectedOption == null) return; //The specified index does not exist as an option for this radio field
    
    // https://forum.pdfsharp.net/viewtopic.php?f=2&t=3561
    PdfArray kids = (PdfArray)source.Elements["/Kids"];
    int j = 0;
    foreach (var kid in kids) {
        var kidValues = ((PdfReference)kid).Value as PdfDictionary;
        //PdfRectangle rectangle = kidValues.Elements.GetRectangle(PdfAnnotation.Keys.Rect);
        if (j == selectedOption.Index)
            kidValues.Elements.SetValue("/AS", new PdfName(selectedOption.Value));
        else
            kidValues.Elements.SetValue("/AS", new PdfName("/Off"));
        j++;
    }
}

注意:这取决于上面的 FindOptions() 函数。

用法

PdfDocument source;
PdfAcroField field = source.AcroForm.Fields[...]; //name or index of the field
PdfRadioButtonField radioField = field as PdfRadioButtonField;
radioField.SetOptionByIndex(index);

按值设置单选字段的选项


public static void SetOptionByValue(this PdfRadioButtonField source, string value) {
    if (source == null || string.IsNullOrWhiteSpace(value)) return;
    if (!value.StartsWith("/", StringComparison.OrdinalIgnoreCase)) value = "/" + value; //All values start with a '/' character
    List<ErPdfRadioOption> options = source.FindOptions();
    ErPdfRadioOption selectedOption = options.Find(x => x.Value == value);
    if (selectedOption == null) return; //The specified index does not exist as an option for this radio field
    source.SetOptionByIndex(selectedOption.Index);
}

注意:这取决于上面的FindOptions()SetOptionByIndex()函数。

基于 PDFsharp 论坛中的 post:https://forum.pdfsharp.net/viewtopic.php?f=2&t=3561#p11386

使用 PDFsharp 版本 1.50.5147

根据 Chris 的回答,重点是您必须将所有选项的值设置为 \Off,同时将您想要的选项的值设置为 \Choice。为此,您可以使用一个简单的函数,例如:

    //sets a radio button option by setting the index and value and turning the others off
    static void setRadioOption (PdfRadioButtonField field, int option, string optvalue)
    {
        PdfArray kids = (PdfArray)field.Elements["/Kids"];
        int j = 0;
        foreach (var kid in kids)
        {
            var kidValues = ((PdfReference)kid).Value as PdfDictionary;
            if (j == option)
                kidValues.Elements.SetValue("/AS", new PdfName(optvalue));
            else
                kidValues.Elements.SetValue("/AS", new PdfName("/Off"));
            j++;
        }
    }

你要找的是我吗?

private static void SetPdfRadiobutton(PdfDocument document, string fieldname, string newvalue, int item)
    {
        PdfRadioButtonField field = (PdfRadioButtonField)document.AcroForm.Fields[fieldname];
        PdfArray items = (PdfArray)field.Elements["/Kids"];

        for (int i = 0; i < items.Elements.Count; i++)
        {
            PdfDictionary keys = ((PdfReference)items.Elements[i]).Value as PdfDictionary;
            keys.Elements.SetValue("/AS", i == item ? new PdfName(newvalue) : new PdfName("/Off"));
        }

        field.ReadOnly = true;
    }