簡體   English   中英

使用 PDFSharp 填充 PdfRadioButtonField

[英]Populate PdfRadioButtonField using PDFSharp

我使用的是來自http://www.pdfsharp.net 的PDFSharp 1.50.4740-beta5 版本,我從 NuGet 安裝了該版本。

我可以填寫文本表單字段和復選框表單字段,但我根本無法使用單選按鈕。 我沒有收到錯誤。 SelectedIndex 在我將其設置為 1 之前和之后都是 -1。

Stack Overflow 上的幾篇文章幫助我走到了這一步。 是否有人使用此產品成功填充了單選按鈕表單字段? 這是示例 PDF 的鏈接: 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. 在值名稱前使用前綴/

例如,如果要設置選項“choice1”被選中:

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

我在https://forum.pdfsharp.net/viewtopic.php?f=2&t=632找到了解決方案

由於這是在 Google 搜索“PDFSharp 單選按鈕”中排名第一,我想我會分享似乎對我有用的內容。

我為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 論壇中的這篇文章: https ://forum.pdfsharp.net/viewtopic.php ? f =2& t = 3561#p11386

使用 PDFsharp 版本 1.50.5147

根據克里斯的回答,重點是您必須將所有選項的值設置為 \\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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM