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

使用iText 5.5扁平化横向PDF时签名出现旋转问题求助

横向PDF部分字段扁平化异常问题

初始状态

初始横向PDF文档排版正常,内容为横向布局。

处理后状态

使用iTextSharp v5.5对指定字段进行扁平化处理后,文档出现排版错乱(内容偏移、布局不符合原横向格式)。

问题代码

//read the file as byte array
PdfReader reader = new PdfReader(b);
using (var ms = new MemoryStream())
{
    var stamper = new iTextSharp.text.pdf.PdfStamper(reader, ms);
    stamper.AnnotationFlattening = true;
    stamper.FormFlattening = true;                    
    // loop through the required fields to flatten, flatten specific fields
    foreach (string name in fieldNames2Flatten)
    {
        stamper.PartialFormFlattening(name);
    }

    stamper.Close();
    reader.Close();
}

技术建议

  • 修正扁平化属性设置顺序:
    全局FormFlattening = true会覆盖局部字段扁平化的配置,应移除该设置,仅通过PartialFormFlattening处理指定字段,保留AnnotationFlattening = true(若需扁平化注释)。调整后代码逻辑:先遍历指定字段调用PartialFormFlattening,再按需设置注释扁平化属性。

  • 修复页面旋转丢失问题:
    横向PDF依赖页面旋转属性,扁平化过程中易丢失该配置导致布局错乱,可在初始化PdfStamper后添加页面旋转修正逻辑:

    for (int i = 1; i <= reader.NumberOfPages; i++)
    {
        int rotation = reader.GetPageRotation(i);
        if (rotation != 0)
        {
            var pageSize = reader.GetPageSize(i);
            stamper.GetUnderContent(i).SetLiteral($"q 0 1 -1 0 0 {pageSize.Height} cm\n");
            stamper.GetOverContent(i).SetLiteral($"Q\n");
            reader.SetPageRotation(i, 0);
        }
    }
    
  • 验证字段坐标匹配性:
    检查目标字段的定义坐标是否适配原横向页面的旋转状态,部分字段的位置信息可能未同步页面旋转参数,扁平化时会出现偏移。

  • 升级组件版本:
    iTextSharp v5.5存在表单扁平化的已知兼容性bug,建议升级至该分支的最新稳定版(如v5.5.13.3),修复了部分横向PDF、局部字段扁平化的异常问题。

内容的提问来源于stack exchange,提问作者Fady Huwaidy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 12:10:08