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

如何使用iText7在PDF中纵向连续添加图片并自动分页

解决iText7在C#中连续添加图片并自动分页的问题

问题根源

原代码中图片未限制尺寸,当图片原生尺寸超过页面可用空间时,iText7会将整张图片单独放在新页面;你尝试的Div代码存在两个问题:一是误用了Java风格的小写add()方法(C#中iText7的方法为大写Add()),二是同样未限制图片尺寸导致溢出。

解决方案核心

通过限制图片宽度适配页面可用空间,让iText7的布局引擎能计算剩余空间,自动处理分页逻辑。

方法一:直接循环添加适配后的图片

foreach (string imagePath in images)
{
    var img = new iText.Layout.Element.Image(ImageDataFactory.Create(imagePath))
        .SetTextAlignment(TextAlignment.CENTER)
        // 设置图片宽度为页面可用宽度的100%,高度自动按比例缩放
        .SetWidth(UnitValue.CreatePercentValue(100))
        // 可选:设置图片底部间距,提升可读性
        .SetMarginBottom(10);
    document.Add(img);
}

方法二:使用Div容器统一管理图片

Div imageContainer = new Div();
// 让Div占满页面可用宽度
imageContainer.SetWidth(UnitValue.CreatePercentValue(100));

foreach (string imagePath in images)
{
    var img = new iText.Layout.Element.Image(ImageDataFactory.Create(imagePath))
        .SetTextAlignment(TextAlignment.CENTER)
        .SetWidth(UnitValue.CreatePercentValue(100))
        .SetMarginBottom(10);
    // C#中iText7方法为大写Add(),避免Java语法混淆
    imageContainer.Add(img);
}

document.Add(imageContainer);

补充说明

  • 如果单张图片缩放后仍超过单页高度,iText7会自动将该图片放到新页面完整显示,后续图片接着排列。
  • 若需要允许图片跨页拆分(不推荐,影响美观),可给图片添加.SetSplitCharacters(new ImageSplitCharacters())配置。

内容的提问来源于stack exchange,提问作者danijeljw-RPC

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:37:26