【问题标题】:Identify different field types in a fillable PDF识别可填写 PDF 中的不同字段类型
【发布时间】:2018-01-10 23:46:55
【问题描述】:

我是 C# 和 PDFsharp 的新手,所以我不确定检查不同字段类型的最佳方法是什么。现在我正在使用以下代码替换文本字段中的值,但这是因为我知道该字段是一个复选框。

但是如果我要遍历从 PDF 获得的字段,我如何检查该字段是复选框还是文本字段或完全是其他东西?

PdfCheckBoxField currentField = (PdfCheckBoxField)(form["CheckBox2"]);
currentField.Checked = true;

如果我像这样遍历所有字段,我该如何检查字段类型:

for (int i=0; i<form.Count; i++)
{
   field = form.Names[i];
}

我在 PDFsharp 网站上没有找到很多关于此的信息。任何帮助将不胜感激。

【问题讨论】:

  • 我不知道任何 pdfsharp 详细信息,但如果您将字段转换为使用它们的特殊类型,您显然可以从使用 typeof 测试它们的类型开始。
  • @mkl 发表您的评论作为答案。这不是 PDFsharp 问题,而是 C# 菜鸟问题。

标签: c# pdf pdfsharp


【解决方案1】:

确定您为form["CheckBox2"] 获得哪种类型的表单字段,特别是您可以将其转换为哪个特定表单字段类的最自然方法是简单地确定该对象的类型。这可以通过使用is 关键字测试类型兼容性或使用typeof 和GetType() 测试类型标识来完成:

var currentField = form["CheckBox2"];
if (currentField is PdfCheckBoxField)
{
    // the type of currentField is compatible with PdfCheckBoxField
    PdfCheckBoxField currentCheckBox = (PdfCheckBoxField)currentField;
    ...
}

或

var currentField = form["CheckBox2"];
if (currentField != null && currentField.GetType() == typeof(PdfCheckBoxField))
{
    // the type of currentField is PdfCheckBoxField
    PdfCheckBoxField currentCheckBox = (PdfCheckBoxField)currentField;
    ...
}

从 C# 7 开始,is 关键字支持pattern matching:

var currentField = form["CheckBox2"];
if (currentField is PdfCheckBoxField currentCheckBox)
{
    // the type of currentField is compatible with PdfCheckBoxField
    // a PdfCheckBoxField variable currentCheckBox here already is declared and initialized with currentField
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-20
    • 2017-04-18
    • 2020-03-15
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    相关资源
    最近更新 更多