You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#调用iText转换HTML下拉列表为可编辑PDF的渲染问题

iText转换HTML下拉框为可编辑PDF解决方案

你当前代码无法渲染select/option标签为可编辑下拉域,可按以下步骤修复:

前置依赖检查

确保你使用的iText 7 + pdfHTML组件版本不低于7.1.15,低于该版本的pdfHTML对select表单的转换支持存在已知缺陷,不会自动生成AcroForm的Choice下拉域。

HTML代码修正

HTML中的select标签必须满足两个要求才会被识别为表单域:

  • 必须设置非空的name属性,无name属性的表单控件iText会直接渲染为普通静态文本
  • 建议显式设置width样式,避免默认宽度为0导致控件不可见

示例正确的HTML片段:

<select name="userCity" style="width: 220px;">
  <option value="bj">北京</option>
  <option value="sh">上海</option>
  <option value="gz" selected>广州</option>
  <option value="sz">深圳</option>
</select>

C#代码修正

你不需要提前手动创建PdfAcroForm实例,开启SetCreateAcroForm(true)后HtmlConverter会自动生成表单,多余的提前创建操作可能引发冲突,修正后的代码如下:

string dest = "h2PMethod1_1.pdf";
PdfWriter pdfWriter = new PdfWriter(dest);
ConverterProperties converterProperties = new ConverterProperties();            
// 开启AcroForm自动生成
converterProperties.SetCreateAcroForm(true);

using (iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(pdfWriter))
{
    Document document = HtmlConverter.ConvertToDocument(htmlString, pdfDocument, converterProperties);
    document.Close();
}

可选:自定义下拉域属性

转换完成后你也可以手动读取AcroForm修改下拉域的配置,示例如下:

using (iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(new PdfReader(dest), new PdfWriter("modified.pdf")))
{
    PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDocument, true);
    // 按name属性获取生成的下拉域
    PdfChoiceFormField cityField = (PdfChoiceFormField)form.GetField("userCity");
    // 追加新选项
    cityField.SetOptions(new List<string> {"杭州", "成都", "武汉"});
    // 设置默认选中值
    cityField.SetValue("gz");
    pdfDocument.Close();
}

内容的提问来源于stack exchange,提问作者SMI Studio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 02:12:02