如何在C# PDF生成中添加自定义断字

This article was translated from English: Does it need improvement?
Translated
View the article in English

在C# PDF生成中,自定义断字有助于修复狭窄列、发票、合同和多语言报告中的尴尬间距、词语溢出和劣质文本换行。 当PDF渲染器未应用正确的断字模式时,齐行文本可能会留下大间隙或在行间分布不均。

在IronPDF中,断字是在通过Chromium引擎的HTML到PDF渲染过程中处理的,而不是通过Word风格的文档对象模型。 CSS hyphens: auto 属性允许渲染器在合法的音节边界处断字,IronPDF 在生成PDF时应用此行为。 CustomHyphenation 属性在 ChromePdfRenderOptions 中控制所使用的断字模式。

模式文件使用TeX格式,可以从本地文件路径或远程URL加载。 这种方式使用户能够为不同语言和文档布局定义自定义断字规则,并在最终PDF中更好地控制单词断裂。

本指南解释了如何在C#中使用 CustomHyphenationDefinitions API,包括本地和远程模式加载、后备行为、限制、错误处理和缓存。


NuGet 使用 NuGet 安装

PM >  Install-Package IronPdf

IronPDF 上查看 NuGet 快速安装。超过 1000 万次下载,它正以 C# 改变 PDF 开发。 您也可以下载 DLLWindows 安装程序

快速入门

  1. 使用 NuGet 包管理器安装 https://www.nuget.org/packages/IronPdf

    PM > Install-Package IronPdf
  2. 复制并运行这段代码。

    using IronPdf;
    
    // Create renderer and assign custom hyphenation patterns from a remote URL
    var renderer = new ChromePdfRenderer();
    renderer.RenderingOptions.CustomHyphenation = new CustomHyphenationDefinitions
    {
        PatternSource = "https://raw.githubusercontent.com/hyphenation/tex-hyphen/master/hyph-utf8/tex/generic/hyph-utf8/patterns/txt/hyph-en-us.pat.txt",
        ExceptionSource = "https://raw.githubusercontent.com/hyphenation/tex-hyphen/master/hyph-utf8/tex/generic/hyph-utf8/patterns/txt/hyph-en-us.hyp.txt"
    };
    
    // Render HTML with CSS hyphens:auto to trigger word breaking
    var pdf = renderer.RenderHtmlAsPdf("<div style='text-align:justify; hyphens:auto; width:120px;'>Supercalifragilisticexpialidocious</div>");
    pdf.SaveAs("hyphenated.pdf");
  3. 部署到您的生产环境中进行测试

    通过免费试用立即在您的项目中开始使用IronPDF

    arrow pointer

最小化工作流程

  1. 安装IronPDF NuGet包
  2. 创建一个 ChromePdfRenderer 实例
  3. 设置 RenderingOptions.CustomHyphenation 为一个带有 PatternSource 路径或URL的新 CustomHyphenationDefinitions
  4. 在HTML内容的CSS中包含 hyphens: auto
  5. 调用 RenderHtmlAsPdf 并保存结果

自定义断字在PDF渲染中如何工作?

CustomHyphenationDefinitions 类定义了IronPDF在渲染过程中从哪里加载断字规则。 Chromium引擎读取这些模式,并在HTML元素上存在CSS hyphens: auto 规则时应用它们。

CustomHyphenationDefinitions类是什么?

类公开了两个属性:

表1:CustomHyphenationDefinitions属性
属性翻译类型必需的说明
PatternSource字符串断字模式文件的路径或URL(例如,hyph-en-us.pat.txt
ExceptionSource字符串断字例外文件的路径或URL(例如,hyph-en-us.hyp.txt

模式文件遵循tex-hyphen项目在GitHub上的页面维护的TeX断字格式。 每种语言在仓库中有两个文件:hyph-{lang}.pat.txt 为模式规则,hyph-{lang}.hyp.txt 为例外列表。当引用托管在GitHub上的文件时,需要原始内容URL(以 https://raw.githubusercontent.com/ 开头)——标准的GitHub页面URL返回HTML,而不是模式文本。

自定义断字如何覆盖内置语言设置?

HyphenationLanguage 枚举在 ChromePdfRenderOptions 上提供了英语(美国)、英语(英国)和俄语的内置预设。 当CustomHyphenation属性和这个枚举都被设置时,CustomHyphenation属性优先,并遵循明确的优先链:

  1. CustomHyphenation—如果设置了有效的PatternSource,则使用自定义模式
  2. HyphenationLanguage—如果未配置自定义模式,则应用内置语言预设
  3. 无ne—如果两者都未设置,则不进行断字

自定义模式加载失败会发生什么?

模式加载期间的错误会被记录,但不会抛出异常。 渲染操作将继续但没有断字而不是失败。 如果还配置了HyphenationLanguage值,渲染器将回退到该内置预设。

这种静默失败行为是为生产环境的故意设计选择。 网络超时获取远程模式文件、无效文件路径、DNS解析失败或格式错误的模式内容不会导致渲染管道崩溃。PDF仍会生成,只是缺少断字分隔符。

权衡在于可见性。 首次加载时的坏模式文件或无法访问的URL会对以后每次使用这些相同源值的渲染产生静默影响(因为缓存也会存储失败状态)。 建议在应用程序启动或CI/CD部署检查期间验证模式文件并确认对远程URL的网络访问,而不是在渲染时。


如何从远程URL加载模式文件?

将PatternSource指向远程URL是应用自定义断字的最快方法,而无需将文件捆绑到项目中。 以下示例加载美国 从tex-hyphen存储库加载英文模式,并呈现一个齐行文本块:

using IronPdf;

var renderer = new ChromePdfRenderer();

// Load custom patterns from a remote TeX hyphenation repository
renderer.RenderingOptions.CustomHyphenation = new CustomHyphenationDefinitions
{
    PatternSource = "https://raw.githubusercontent.com/hyphenation/tex-hyphen/master/hyph-utf8/tex/generic/hyph-utf8/patterns/txt/hyph-en-us.pat.txt",
    ExceptionSource = "https://raw.githubusercontent.com/hyphenation/tex-hyphen/master/hyph-utf8/tex/generic/hyph-utf8/patterns/txt/hyph-en-us.hyp.txt"
};

string html = @"
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; }
        .narrow-column {
            width: 150px;
            text-align: justify;
            hyphens: auto;
            -webkit-hyphens: auto;
            border: 1px solid #ccc;
            padding: 10px;
        }
    </style>
</head>
<body>
    <div class='narrow-column'>
        The extraordinarily sophisticated implementation demonstrates
        how hyphenation significantly improves the typographical quality
        of justified text in constrained column widths.
    </div>
</body>
</html>";

var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("remote-hyphenation.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

// Load custom patterns from a remote TeX hyphenation repository
renderer.RenderingOptions.CustomHyphenation = new CustomHyphenationDefinitions
{
    PatternSource = "https://raw.githubusercontent.com/hyphenation/tex-hyphen/master/hyph-utf8/tex/generic/hyph-utf8/patterns/txt/hyph-en-us.pat.txt",
    ExceptionSource = "https://raw.githubusercontent.com/hyphenation/tex-hyphen/master/hyph-utf8/tex/generic/hyph-utf8/patterns/txt/hyph-en-us.hyp.txt"
};

string html = @"
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; }
        .narrow-column {
            width: 150px;
            text-align: justify;
            hyphens: auto;
            -webkit-hyphens: auto;
            border: 1px solid #ccc;
            padding: 10px;
        }
    </style>
</head>
<body>
    <div class='narrow-column'>
        The extraordinarily sophisticated implementation demonstrates
        how hyphenation significantly improves the typographical quality
        of justified text in constrained column widths.
    </div>
</body>
</html>";

var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("remote-hyphenation.pdf");
Imports IronPdf

Dim renderer As New ChromePdfRenderer()

' Load custom patterns from a remote TeX hyphenation repository
renderer.RenderingOptions.CustomHyphenation = New CustomHyphenationDefinitions With {
    .PatternSource = "https://raw.githubusercontent.com/hyphenation/tex-hyphen/master/hyph-utf8/tex/generic/hyph-utf8/patterns/txt/hyph-en-us.pat.txt",
    .ExceptionSource = "https://raw.githubusercontent.com/hyphenation/tex-hyphen/master/hyph-utf8/tex/generic/hyph-utf8/patterns/txt/hyph-en-us.hyp.txt"
}

Dim html As String = "
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; }
        .narrow-column {
            width: 150px;
            text-align: justify;
            hyphens: auto;
            -webkit-hyphens: auto;
            border: 1px solid #ccc;
            padding: 10px;
        }
    </style>
</head>
<body>
    <div class='narrow-column'>
        The extraordinarily sophisticated implementation demonstrates
        how hyphenation significantly improves the typographical quality
        of justified text in constrained column widths.
    </div>
</body>
</html>"

Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("remote-hyphenation.pdf")
$vbLabelText   $csharpLabel

输出

渲染的PDF显示了在音节边界上干净的单词分隔的齐行段落。 没有断字,同一段文本会产生大的词间间隙或溢出列。

对于Chromium兼容性,必须同时需要 hyphens: auto-webkit-hyphens: auto CSS声明。 text-align: justify 规则使断字最为明显。 如果目标HTML元素上没有CSS声明,自定义模式将被加载但不会被应用。

请注意URL必须指向原始文本内容。 标准GitHub URL如 https://github.com/hyphenation/tex-hyphen/blob/master/... 返回HTML页面包装,将导致模式验证失败。 使用 https://raw.githubusercontent.com/... 格式,或者点击GitHub上的"Raw"按钮以获取正确的URL。

远程资源约束是什么?

表2:远程URL约束
约束Value
协议HTTP和HTTPS(推荐使用HTTPS)
允许的内容类型text/plain, application/octet-stream
最大响应大小5 MB
请求超时10秒
安全请求到私有/本地IP(10.x.x.x192.168.x.xlocalhost)被阻止,以防止SSRF攻击
拒绝的内容二进制文件、包含空字节的文件、包含
Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package IronPdf
运行示例看着你的HTML代码变成PDF文件。

钢铁支援团队

我们每周 5 天,每天 24 小时在线。
聊天
电子邮件
打电话给我