如何在C# PDF生成中添加自定义断字
在C# PDF生成中,自定义断字有助于修复狭窄列、发票、合同和多语言报告中的尴尬间距、词语溢出和劣质文本换行。 当PDF渲染器未应用正确的断字模式时,齐行文本可能会留下大间隙或在行间分布不均。
在IronPDF中,断字是在通过Chromium引擎的HTML到PDF渲染过程中处理的,而不是通过Word风格的文档对象模型。 CSS hyphens: auto 属性允许渲染器在合法的音节边界处断字,IronPDF 在生成PDF时应用此行为。 CustomHyphenation 属性在 ChromePdfRenderOptions 中控制所使用的断字模式。
模式文件使用TeX格式,可以从本地文件路径或远程URL加载。 这种方式使用户能够为不同语言和文档布局定义自定义断字规则,并在最终PDF中更好地控制单词断裂。
本指南解释了如何在C#中使用 CustomHyphenationDefinitions API,包括本地和远程模式加载、后备行为、限制、错误处理和缓存。
快速入门
-
使用 NuGet 包管理器安装 https://www.nuget.org/packages/IronPdf
PM > Install-Package IronPdf -
复制并运行这段代码。
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"); -
部署到您的生产环境中进行测试
通过免费试用立即在您的项目中开始使用IronPDF
最小化工作流程
- 安装IronPDF NuGet包
- 创建一个
ChromePdfRenderer实例 - 设置
RenderingOptions.CustomHyphenation为一个带有PatternSource路径或URL的新CustomHyphenationDefinitions - 在HTML内容的CSS中包含
hyphens: auto - 调用
RenderHtmlAsPdf并保存结果
自定义断字在PDF渲染中如何工作?
CustomHyphenationDefinitions 类定义了IronPDF在渲染过程中从哪里加载断字规则。 Chromium引擎读取这些模式,并在HTML元素上存在CSS hyphens: auto 规则时应用它们。
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属性优先,并遵循明确的优先链:
- CustomHyphenation—如果设置了有效的PatternSource,则使用自定义模式
- HyphenationLanguage—如果未配置自定义模式,则应用内置语言预设
- 无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")
输出
渲染的PDF显示了在音节边界上干净的单词分隔的齐行段落。 没有断字,同一段文本会产生大的词间间隙或溢出列。
对于Chromium兼容性,必须同时需要 hyphens: auto 和 -webkit-hyphens: auto CSS声明。 text-align: justify 规则使断字最为明显。 如果目标HTML元素上没有CSS声明,自定义模式将被加载但不会被应用。
https://github.com/hyphenation/tex-hyphen/blob/master/... 返回HTML页面包装,将导致模式验证失败。 使用 https://raw.githubusercontent.com/... 格式,或者点击GitHub上的"Raw"按钮以获取正确的URL。
远程资源约束是什么?
| 约束 | Value |
|---|---|
| 协议 | HTTP和HTTPS(推荐使用HTTPS) |
| 允许的内容类型 | text/plain, application/octet-stream |
| 最大响应大小 | 5 MB |
| 请求超时 | 10秒 |
| 安全 | 请求到私有/本地IP(10.x.x.x、192.168.x.x、localhost)被阻止,以防止SSRF攻击 |
| 拒绝的内容 | 二进制文件、包含空字节的文件、包含标签的文件 |
容器和云环境(Docker,Azure,AWS)必须具备到模式文件主机的HTTPS出站访问权限,以便远程加载成功。
如何从本地文件加载模式文件?
对于外部网络访问受限或偏好在构建时捆绑的环境,PatternSource也接受本地文件系统路径:
hyph-en-us.pat.txt 和 hyph-en-us.hyp.txt 并放置在代码引用的路径中。
using IronPdf;
var renderer = new ChromePdfRenderer();
// Load English hyphenation patterns from local files
renderer.RenderingOptions.CustomHyphenation = new CustomHyphenationDefinitions
{
PatternSource = @"C:\patterns\hyph-en-us.pat.txt",
ExceptionSource = @"C:\patterns\hyph-en-us.hyp.txt"
};
string html = @"
<html>
<head>
<style>
.invoice-container {
width: 220px;
text-align: justify;
hyphens: auto;
-webkit-hyphens: auto;
font-family: Georgia, serif;
font-size: 11px;
line-height: 1.5;
border: 1px solid #ddd;
padding: 12px;
}
h3 { font-size: 13px; margin-top: 0; }
.terms { color: #555; margin-top: 10px; font-size: 9px; }
</style>
</head>
<body>
<div class='invoice-container'>
<h3>Invoice #20260331</h3>
<p>无ndiscrimination acknowledgement: The undersigned
representative hereby confirms that all pharmaceutical
reimbursement documentation has been independently
verified and cross-referenced against the applicable
regulatory framework established by the appropriate
governmental oversight authority.</p>
<p class='terms'>无twithstanding any indemnification
provisions, the counterparty's disproportionate
liability shall not exceed the predetermined
recharacterization threshold established under the
intergovernmental cooperation agreement.</p>
</div>
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("local-hyphenation.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Load English hyphenation patterns from local files
renderer.RenderingOptions.CustomHyphenation = new CustomHyphenationDefinitions
{
PatternSource = @"C:\patterns\hyph-en-us.pat.txt",
ExceptionSource = @"C:\patterns\hyph-en-us.hyp.txt"
};
string html = @"
<html>
<head>
<style>
.invoice-container {
width: 220px;
text-align: justify;
hyphens: auto;
-webkit-hyphens: auto;
font-family: Georgia, serif;
font-size: 11px;
line-height: 1.5;
border: 1px solid #ddd;
padding: 12px;
}
h3 { font-size: 13px; margin-top: 0; }
.terms { color: #555; margin-top: 10px; font-size: 9px; }
</style>
</head>
<body>
<div class='invoice-container'>
<h3>Invoice #20260331</h3>
<p>无ndiscrimination acknowledgement: The undersigned
representative hereby confirms that all pharmaceutical
reimbursement documentation has been independently
verified and cross-referenced against the applicable
regulatory framework established by the appropriate
governmental oversight authority.</p>
<p class='terms'>无twithstanding any indemnification
provisions, the counterparty's disproportionate
liability shall not exceed the predetermined
recharacterization threshold established under the
intergovernmental cooperation agreement.</p>
</div>
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("local-hyphenation.pdf");
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Load English hyphenation patterns from local files
renderer.RenderingOptions.CustomHyphenation = New CustomHyphenationDefinitions With {
.PatternSource = "C:\patterns\hyph-en-us.pat.txt",
.ExceptionSource = "C:\patterns\hyph-en-us.hyp.txt"
}
Dim html As String = "
<html>
<head>
<style>
.invoice-container {
width: 220px;
text-align: justify;
hyphens: auto;
-webkit-hyphens: auto;
font-family: Georgia, serif;
font-size: 11px;
line-height: 1.5;
border: 1px solid #ddd;
padding: 12px;
}
h3 { font-size: 13px; margin-top: 0; }
.terms { color: #555; margin-top: 10px; font-size: 9px; }
</style>
</head>
<body>
<div class='invoice-container'>
<h3>Invoice #20260331</h3>
<p>无ndiscrimination acknowledgement: The undersigned
representative hereby confirms that all pharmaceutical
reimbursement documentation has been independently
verified and cross-referenced against the applicable
regulatory framework established by the appropriate
governmental oversight authority.</p>
<p class='terms'>无twithstanding any indemnification
provisions, the counterparty's disproportionate
liability shall not exceed the predetermined
recharacterization threshold established under the
intergovernmental cooperation agreement.</p>
</div>
</body>
</html>"
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("local-hyphenation.pdf")
输出
如下所示,长单词自动在音节边界处断开,否则会溢出或产生过多空格。 引擎仅在需要时连字符化——适合于一行的单词保持完整。
切换到另一种语言仅需要改变文件路径:
// Switch to French hyphenation — just change the file paths
renderer.RenderingOptions.CustomHyphenation = new CustomHyphenationDefinitions
{
PatternSource = @"C:\patterns\hyph-fr.pat.txt",
ExceptionSource = @"C:\patterns\hyph-fr.hyp.txt"
};
// Switch to French hyphenation — just change the file paths
renderer.RenderingOptions.CustomHyphenation = new CustomHyphenationDefinitions
{
PatternSource = @"C:\patterns\hyph-fr.pat.txt",
ExceptionSource = @"C:\patterns\hyph-fr.hyp.txt"
};
' Switch to French hyphenation — just change the file paths
renderer.RenderingOptions.CustomHyphenation = New CustomHyphenationDefinitions With {
.PatternSource = "C:\patterns\hyph-fr.pat.txt",
.ExceptionSource = "C:\patterns\hyph-fr.hyp.txt"
}
这使得CustomHyphenation对于内置PdfHyphenationLanguage 枚举不支持的语言特别有用,目前仅支持英语(美国)、英语(英国)和俄语。
本地文件约束是什么?
| 约束 | Value |
|---|---|
| 允许的扩展名 | .txt, .pat |
| 最大文件大小 | 5 MB |
| 编码 | UTF-8 |
| 内容规则 | 仅有效的连字符模式——无评论、元数据、标题、TeX指令或编码说明 |
| 拒绝的内容 | 二进制文件、包含空字节的文件、包含标签的文件 |
缓存如何影响批量渲染的性能?
自定义连字符模式在第一次加载后会缓存到内存中,以PatternSource和ExceptionSource值为键。 引用相同源路径或URL的后续渲染重新使用缓存模式,而无需重新下载或重新读取文件。
此行为对高容量PDF渲染工作流有两个实际影响:
性能:第一次渲染承担I/O成本(网络请求或磁盘读取)。 从那时起的每次渲染在模式加载方面都实际上是免费的。 对于使用相同连字符配置生成数百个PDF的批量作业,开销可忽略不计。
静默失败持久性:由于模式加载期间的错误不会抛出异常,并且渲染器在没有连字符化的情况下继续运行,因此第一个加载时出现的错误模式文件或网络故障将在整个批处理中静默地持续存在。 每次后续渲染也将缺乏连字符化,没有额外的错误信号。 在应用程序启动或部署期间验证模式文件并确认URL可访问性——而不是在渲染时。
缓存键标识:缓存键是PatternSource(如果设置了则是ExceptionSource)的确切字符串值。 指向同一URL或文件路径的两个渲染器实例共享相同的缓存模式。 更改URL——即使是同一文件的不同版本——强制重新加载。
在生产部署之前预验证文件内容。 模式文件必须仅包含有效的连字符文本。 存在评论、TeX指令、编码声明或任何非模式内容都会导致集成失败。 tex-hyphen仓库提供为几十种语言预制的干净模式文件。
推荐使用HTTPS作为远程模式源。 支持HTTP,但不提供文件内容的传输层保护。
下一步是什么?
ChromePdfRenderOptions 上的CustomHyphenation属性提供了对任何由TeX模式文件支持的语言的断字行为的直接控制——这超越了PdfHyphenationLanguage所提供的三个内置预设。 模式文件可以从远程URL或本地路径加载,首次使用后缓存到内存中,如果加载失败则回退到HyphenationLanguage设置。 错误被记录但从不抛出,因此模式验证应在部署期间而不是在渲染时进行。
有关相关的IronPDF渲染配置,请参见:
ChromePdfRenderOptionsAPI参考,包含所有可用的渲染选项PdfHyphenationLanguage枚举,用于内置的语言预设- HTML 到 PDF 渲染教程,用于完整的HTML渲染管道
- 渲染选项操作指南,用于其他ChromePdfRenderOptions配置
- IronPDF功能概述,为完整的PDF生成和操作能力
获得IronPDF的30天免费试用以在实际项目中测试自定义连字符,或查看生产部署的许可选项。

