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

iText转换HTML为PDF时CSS column-count多栏属性不生效如何解决?

CSS column-count属性在iText HTML转PDF时不生效解决方案

生效前提

iText 7的Html2pdf模块从2.0.0版本开始支持CSS多列布局相关属性,包含column-count、column-gap、column-rule等,低于该版本的依赖包无法支持该特性,请先将项目中iText.Html2pdf及配套的iText7核心包升级到2.0.0及以上版本,避免版本冲突。

HTML样式调整

不要直接给<body>根标签配置多列属性,iText对根元素的多列属性解析存在兼容问题,建议新增一层外层容器包裹所有正文内容,将多列属性配置在该容器上,参考写法如下:

<style>
/* 不要给该样式添加仅screen媒体生效的限制,要适配PRINT媒体 */
.content-wrapper {
  column-count: 2;
  column-gap: 20px;
  /* 可选配置:列之间的分割线 */
  column-rule: 1px solid #eee;
  width: 100%;
}
</style>
<body>
  <div class="content-wrapper">
    <!-- 所有需要双栏展示的内容都放在该容器内 -->
  </div>
</body>

转换代码调整

升级依赖和调整HTML样式后如果依然不生效,可以修改转换代码,显式启用标准CSS解析规则,修改后的代码如下:

public static byte[] ConvertHtmlToPDF(string sHtmlContent)
{
    byte[] oPdfFile = null;
    try
    {
        if (string.IsNullOrEmpty(sHtmlContent))
            return null;
        string FONTS = HostingEnvironment.ApplicationPhysicalPath + @"Content\CustomFonts\Inter_Web\itext";
        var oPageSize = PageSize.A6;
        var fontProvider = new iText.Html2pdf.Resolver.Font.DefaultFontProvider();
        fontProvider.AddDirectory(FONTS);
        ConverterProperties oConverterProperties = new ConverterProperties();
        oConverterProperties.SetFontProvider(fontProvider);
        // 显式启用默认CSS应用工厂,保证标准CSS属性被正常解析
        oConverterProperties.SetCssApplierFactory(new DefaultCssApplierFactory());
        var oMediaDeviceDesc = new iText.StyledXmlParser.Css.Media.MediaDeviceDescription(iText.StyledXmlParser.Css.Media.MediaType.PRINT, oPageSize.GetWidth(), oPageSize.GetHeight());
        oConverterProperties.SetMediaDeviceDescription(oMediaDeviceDesc);
        using (MemoryStream oDocumentStream = new MemoryStream())
        {
            using (PdfWriter oDocumentWriter = new PdfWriter(oDocumentStream).SetSmartMode(true))
            {
                PdfDocument pdfDocument = new PdfDocument(oDocumentWriter);
                pdfDocument.SetDefaultPageSize(oPageSize);
                HtmlConverter.ConvertToPdf(sHtmlContent, pdfDocument, oConverterProperties);
            }
            oPdfFile = oDocumentStream.ToArray();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return oPdfFile;
}

验证方法

可以先用极简的双栏测试HTML验证配置是否生效,排除原有HTML内容里的样式冲突问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:39:03