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

iText 8生成段落与旧段落叠加问题技术求助

问题:PDF指定位置修改文本出现叠加,清理不彻底

需求为在PDF指定位置设置特定字体及字号的文本,因未找到StampAnnotation安装自定义字体的方式,故未采用该方案。当前问题为:创建并设置段落文本后需修改时,新文本与旧文本出现叠加(如“25шт”与“363936393639шт”叠加,且在Adobe Acrobat Pro中被识别为单个段落)。

当前使用代码

文本设置代码

var font = PdfFontFactory.CreateFont(@"C:\Windows\Fonts\GOST Common.ttf", "Identity-H");
_workingDocument.SetFont(font);

string utf8String = count + "шт.";
var writableText = new Paragraph(utf8String).SetItalic().SetBold();

switch (_format)
{
    case Formats.A4Book:
        x = 530;
        y = 175;
        ClearText(text, x, y); //尝试用PdfCleaner.AutoSweepCleanUp删除旧值
        AddImage(x, y); //添加图片覆盖未被清理的部分文本
        writableText.SetFontSize(20).SetFixedPosition(x - 300, y, 350).SetTextAlignment(TextAlignment.RIGHT)
            .SetHorizontalAlignment(HorizontalAlignment.RIGHT);
        _workingDocument.Add(writableText);
        break;
    case Formats.A3Album:
        ... //逻辑相同,仅x、y值不同
    case Formats.A3Book:
        ... //逻辑相同,仅x、y值不同
    default:
        ...
}

清理逻辑代码

int countTry = 0;
ICleanupStrategy cleanupStrategy =
            new RegexBasedCleanupStrategy(new Regex(@"(.*)[0-9]{1,}(.*)шт(.*)", RegexOptions.IgnoreCase))
                .SetRedactionColor(ColorConstants.WHITE);
while (countTry < 3)
{
     try
     {
            PdfCleaner.AutoSweepCleanUp(_document.GetFirstPage(), cleanupStrategy);
     }
     catch
     {
            //忽略异常
     }
     finally
     {
             countTry++;
     }
}

使用环境:iText 8.0.5、iText.pdf sweep 4.0.3、itext.bouncy-castle-adapter 8.0.5、.Net 8


优化解决方案

1. 精准定位清理区域,替换宽泛正则匹配

原正则匹配范围过大,易出现漏清或误匹配。改用坐标定位的矩形区域清理,确保覆盖目标文本:

// 计算要清理的矩形区域(根据字体大小调整高度,确保完全覆盖旧文本)
Rectangle cleanUpArea = new Rectangle(x - 300, y - 25, 350, 30);
ICleanupStrategy strategy = new PdfCleanUpStrategy();
// 指定要清理的页面和区域,用白色填充覆盖旧文本
strategy.AddCleanupLocation(new PdfCleanUpLocation(1, cleanUpArea, ColorConstants.WHITE));
// 执行清理操作
PdfCleaner.CleanUp(_document, strategy, new FileStream("temp_cleaned.pdf", FileMode.Create));

2. 直接使用PdfCanvas绘制文本,避免段落布局叠加

放弃Paragraph的布局逻辑,直接用画布精准绘制文本,确保位置完全对应清理区域:

// 清理完成后重新打开文档
using (var pdfDoc = new PdfDocument(new PdfReader("temp_cleaned.pdf"), new PdfWriter("final_output.pdf")))
{
    var page = pdfDoc.GetFirstPage();
    PdfCanvas canvas = new PdfCanvas(page);
    var font = PdfFontFactory.CreateFont(@"C:\Windows\Fonts\GOST Common.ttf", "Identity-H");
    
    // 设置字体、字号和颜色
    canvas.SetFontAndSize(font, 20);
    canvas.SetFillColor(ColorConstants.BLACK);
    // 按右侧对齐绘制文本,对应原位置
    canvas.ShowTextAligned(count + "шт.", x, y, TextAlignment.RIGHT);
}

3. 移除冗余的图片覆盖步骤

优化清理逻辑后,旧文本已被完全清除,无需再用图片覆盖,减少PDF冗余对象。


内容的提问来源于stack exchange,提问作者Qivorch Velix

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 18:22:46