如何在C#中新增自訂斷詞功能至PDF生成
在C# PDF生成中,自訂斷詞有助於修正窄欄、發票、合約和多語言報告中的尷尬間距、文字溢出和不良的文字換行。 當PDF渲染器沒有應用正確的斷詞模式時,齊行的文字可能會在行間留下很大的空隙或在行間不當地斷開。
在IronPDF中,斷詞是在通過Chromium引擎進行HTML到PDF渲染時處理的,而不是通過Word風格的文檔對象模型進行的。 CSS hyphens: auto屬性允許渲染器在有效音節邊界處斷開單詞,IronPDF在PDF生成期間應用了該行為。 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實例 - 將
CustomHyphenationDefinitions - 在HTML內容的CSS中包含
hyphens: auto - 呼叫
RenderHtmlAsPdf並保存結果
自訂斷詞在PDF渲染中如何運作?
CustomHyphenationDefinitions類定義了IronPDF在渲染過程中從哪裡加載斷詞規則。 Chromium引擎讀取這些模式並在HTML元素上存在CSS hyphens: auto規則時應用它們。
CustomHyphenationDefinitions類是什麼?
該類暴露了兩個屬性:
| 屬性 | 類型 | 必需 | 描述 |
|---|---|---|---|
PatternSource | string | 是 | 斷詞模式文件的路徑或URL(例如,hyph-en-us.pat.txt) |
ExceptionSource | string | 否 | 斷詞例外文件的路徑或URL(例如,hyph-en-us.hyp.txt) |
模式文件遵循由GitHub上的tex-hyphen項目維護的TeX斷詞格式。 每個語言在庫中都有兩個文件:https://raw.githubusercontent.com/開頭)—標準的GitHub頁面URL返回HTML而不是模式文本。
自訂斷詞如何覆蓋內建語言設定?
ChromePdfRenderOptions上提供了內建的英語(美國)、英語(英國)和俄語預設。 當兩者都設置時,CustomHyphenation屬性優先於該枚舉,遵循明確的優先鏈:
- CustomHyphenation — 如果設置了有效的PatternSource,則使用自定義模式
- HyphenationLanguage — 如果沒有配置自定義模式,則應用內建語言預設
- 無 — 如果未設置兩者,則不發生斷詞
自訂模式加載失敗時會發生什麼?
模式加載期間的錯誤將被記錄但不會拋出異常。渲染操作會繼續進行而不進行斷詞,而不是失敗。 如果也配置了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兼容,需要-webkit-hyphens: auto兩個CSS宣告。 text-align: justify規則使斷詞最顯眼。 如果目標HTML元素上沒有CSS宣告,則自訂模式會被加載但從不應用。
https://github.com/hyphenation/tex-hyphen/blob/master/...這樣的標準GitHub URL返回一個HTML頁面包裝,會導致模式驗證失敗。 使用https://raw.githubusercontent.com/...形式,或點擊GitHub上的"Raw"按鈕以獲得正確的URL。)}]
遠程源的約束條件是什麼?
| 約束 | 值 |
|---|---|
| 協議 | 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.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枚舉不支援的語言特別有用,目前僅支持英語(美國)、英語(英國)和俄語。
本地文件的約束條件是什麼?
| 約束 | 值 |
|---|---|
| 允許的擴展名 | .txt,.pat |
| 最大文件大小 | 5 MB |
| 編碼 | UTF-8 |
| 內容規則 | 僅限有效的斷詞模式—不允許註釋、元數據、標頭、TeX指令或編碼說明 |
| 被拒絕的內容 | 二進位文件、包含空字節的文件、包含標籤的文件 |
緩存如何影響批次渲染的效能?
自訂斷詞模式在第一次加載後緩存在記憶體中,鍵是PatternSource和ExceptionSource值。 後續參考相同源路徑或URL的渲染會重用緩存模式而不重新下載或重新讀取文件。
此行為對高容量PDF渲染工作流程有兩個實際影響:
效能:第一次渲染承擔I/O成本(網絡請求或磁盤讀取)。 從那時起的每次渲染在模式加載方面實際上是免費的。對於同一斷詞配置生成數百個PDF的批次任務,開銷可以忽略不計。
無聲失敗持續性:由於模式加載期間的錯誤不會拋出異常且渲染器在沒有斷詞的情況下繼續運行,初始加載上的壞模式文件或網絡故障將在整個批次中無聲持續。 每次後續渲染也將缺少斷詞,没有額外的錯誤信號。 在應用啟動或部署期間驗證模式文件並確認URL可訪問性—不是在渲染時。
緩存鍵身份:緩存鍵就是PatternSource(如果設置)的確切字符串值。 指向同一URL或文件路徑的兩個渲染器實例共享相同的緩存模式。 更改URL—即使是同一文件的不同版本—將強制重新加載。
在生產部署之前預先驗證文件內容。 模式文件必須僅包含有效的斷詞文本。 存在評論、TeX指令、編碼宣告或非模式內容會導致整合失敗。 tex-hyphen庫提供多種語言的預建乾淨模式文件。
推薦使用HTTPS來獲取遠程模式來源。 HTTP受支持但不提供對文件內容的傳輸層保護。
接下來該怎麼做?
ChromePdfRenderOptions上的CustomHyphenation屬性可直接控制任何受TeX模式文件支持的語言的單詞斷行行為—超越了通過PdfHyphenationLanguage提供的三個內建預設。 模式文件從遠程URL或本地路徑加載,首次使用後緩存在記憶體中,如果加載失敗則回退到HyphenationLanguage設置。 錯誤會被記錄但不會被拋出,因此模式驗證應該在部署時而不是在渲染時進行。
有關IronPDF渲染配置的相關信息,請參閱:
ChromePdfRenderOptionsAPI引用以獲取所有可用的渲染選項PdfHyphenationLanguage枚舉以獲取內建語言預設- HTML到PDF渲染教程以獲取完整的HTML渲染管道
- 渲染選項教程以獲取其他ChromePdfRenderOptions配置
- IronPDF功能總覽以獲取完整的PDF生成和操作能力集
獲取IronPDF的免費30天試用以在實際專案中測試自訂斷詞,或查看生產部署的授權選項。

