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

C#中将XFA表单转换为兼容浏览器的静态PDF问题求助

解决XFA转静态PDF后浏览器显示异常的问题

你的问题出在仅移除了XFA表单数据,但未将生成的AcroForm字段扁平化为静态内容,导致浏览器仍尝试加载XFA相关逻辑,从而出现提示。以下是修改后的代码及关键说明:

关键改动点

  • 移除XFA后,调用form.FlattenFields()将所有表单字段转换为静态文本/图形,彻底消除表单的可编辑性和XFA依赖
  • 调整字段处理逻辑,确保在扁平化前完成字段值和样式的设置
  • 增加空值检查,避免原PDF无表单时出现异常

修改后的完整代码

using System;
using System.Collections.Generic;
using System.IO;
using iText.Forms;
using iText.Forms.Fields;
using iText.Kernel.Colors;
using iText.Kernel.Pdf;

namespace iText.Samples.Sandbox.Acroforms
{
    public class RemoveXFA
    {
        public static readonly string DEST = @"C:\temp\xfa-form-filled.pdf";
        public static readonly string SRC = @"C:\temp\xfa-form.pdf";

        public static void Main(string[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();

            new RemoveXFA().ManipulatePdf(DEST);
        }

        protected void ManipulatePdf(string dest)
        {
            PdfReader reader = new PdfReader(SRC);
            PdfWriter writer = new PdfWriter(dest);
            PdfDocument pdfDoc = new PdfDocument(reader, writer);

            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
            
            if (form != null)
            {
                form.RemoveXfaForm();

                IDictionary<string, PdfFormField> fields = form.GetAllFormFields();
                foreach (var kvp in fields)
                {
                    if (kvp.Key.Contains("Total"))
                    {
                        kvp.Value.SetColor(ColorConstants.RED);
                    }
                    kvp.Value.SetValue("X");
                }

                // 核心操作:将可编辑字段转为静态内容,确保浏览器正常显示
                form.FlattenFields();
            }

            pdfDoc.Close();
        }
    }
}

额外说明

  1. 扁平化的必要性:浏览器原生不支持XFA表单,移除XFA后如果保留AcroForm字段,部分浏览器仍可能无法正确渲染;扁平化后字段变为静态内容,所有PDF阅读器都能正常显示。
  2. 版本兼容性:确保使用的iText 7版本是最新稳定版,且已引用itext.forms、itext.kernel等必要NuGet包。

内容的提问来源于stack exchange,提问作者František Rýsl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 00:42:33