如何在C#進行PDF生成中新增自訂斷字
C# PDF生成中的自訂斷字有助於修正狹窄欄位、發票、合約和多語言報告中的不當間距、字詞溢出和文字換行不良。 當PDF渲染器未應用正確的斷字模式時,齊行文字可能會留下大空隙或跨行斷字不佳。
在IronPDF中,斷字是在透過Chromium引擎進行HTML-to-PDF渲染時處理的,而不是透過類似Word的文件物件模型。 CSS hyphens: auto 屬性允許渲染器在有效音節分界處進行單詞斷字,IronPDF在PDF生成時應用該行為。 在CustomHyphenation屬性控制使用哪些斷字模式。
模式檔使用TeX格式,可以從本地檔案路徑或遠端URL載入。 這讓可能為不同語言和文件版面定義自訂斷字規則,對最終PDF中的單詞分界有更多掌握。
本指南說明如何在C#中使用CustomHyphenationDefinitions API,包括本地及遠端模式載入、備援行為、限制、錯誤處理和快取。
-
1Install IronPDF with NuGet Package Manager
-
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");C# -
3部署以在您的實時環境中測試
今天就開始在您的專案中使用IronPDF,透過免費試用
最低限度的工作流程
- 安裝IronPDF NuGet套件
- 建立
renderer實例 - 將
CustomHyphenationDefinitions - 在HTML內容的CSS中包含
hyphens - 呼叫
renderer.RenderHtmlAsPdf()並儲存結果
自訂斷字在PDF渲染中如何運作?
CustomHyphenationDefinitions類別定義IronPDF在渲染過程中從哪裡載入斷字規則。 Chromium引擎在HTML元素上出現CSS hyphens 規則時,會讀取這些模式並應用它們。
什麼是CustomHyphenationDefinitions類別?
該類別公開兩個屬性:
| 屬性 | 型別 | 必須 | 描述 |
|---|---|---|---|
PatternSource | string | 是 | 斷字模式檔的路徑或URL(例如,hyph-en-us.pat.txt) |
ExceptionSource | string | 否 | 斷字例外檔的路徑或URL(例如,hyph-en-us.hyp.txt) |
模式檔遵循由GitHub上的tex-hyphen專案維護的TeX斷字格式。 每種語言在儲存庫中有兩個檔案:hyph-{lang}.pat.txt 用於模式規則,hyph-{lang}.hyp.txt 用於例外清單。引用GitHub託管的檔案時,要求使用原始內容URL(以https://raw.githubusercontent.com/ 開頭)- 標準的GitHub頁面URL返回的是HTML,而不是模式文字。
自訂斷字如何覆蓋內建語言設定?
HyphenationLanguage提供內建的美式英文、英式英文和俄文預設。 當兩者同時設置時,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");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顯示了音節邊界處具有乾淨單詞分隔的齊行段落。 在沒有斷字的情況下,這個相同的文字將產生較大的詞間間隙或溢出欄位。
需要兩者hyphenate-limit-chars的CSS聲明,才能相容於Chromium。 hyphens規則使斷字最為可見。 如果目標HTML元素上不存在CSS聲明,自訂模式載入但從不應用。
https://github.com/hyphenation/tex-hyphen/blob/master/... 這樣的標準GitHub URL返回的是HTML頁面包裝,這將導致模式驗證失敗。 使用https://raw.githubusercontent.com/...形式,或在GitHub上點擊"原始"按鈕以獲得正確的URL。遠端來源的限制條件是什麼?
| 限制條件 | 值 |
|---|---|
| 協定 | HTTP及HTTPS(推薦HTTPS) |
| 允許的內容型別 | text/plain, application/octet-stream |
| 最大響應大小 | 5 MB |
| 請求超時 | 10秒 |
| 安全性 | 阻止對私有/本地IP(10.x.x.x, 192.168.x.x, localhost)的請求,以防止SSRF攻擊 |
| 拒絕的內容 | 二進位檔案、含有空字元的檔案、包含<script>標籤的檔案 |
容器和雲端環境(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>Nondiscrimination 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'>Notwithstanding 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>Nondiscrimination 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'>Notwithstanding 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 With {
.PatternSource = "C:\patterns\hyph-fr.pat.txt",
.ExceptionSource = "C:\patterns\hyph-fr.hyp.txt"
}這讓PdfHyphenationLanguage枚舉未覆蓋的語言而言特別有用。
本地檔案的限制條件是什麼?
| 限制條件 | 值 |
|---|---|
| 允許的擴展名 | .txt, .pat |
| 最大檔案大小 | 5 MB |
| 編碼 | UTF-8 |
| 內容規則 | 僅有效的斷字模式 — 沒有註解、元資料、標頭、TeX指令或編碼注解 |
| 拒絕的內容 | 二進位檔案、含有空字元的檔案、包含<script>標籤的檔案 |
快取在批次渲染中如何影響效能?
自訂斷字模式在首次載入後被快取至記憶體中,以ExceptionSource值為鍵。 後續引用相同來源路徑或URL的渲染重新使用快取的模式,而不重新下載或重讀檔案。
此行為對高容量PDF渲染工作流程有兩個實際影響:
效能: 第一次渲染承擔I/O成本(網路請求或磁碟讀取)。 之後的每次渲染從斷字模式載入的角度來看都是實際免費的。對於生成數百份具有相同斷字配置PDF的批次作業來說,開銷可忽略。
靜默失敗持續性: 因為在模式載入期間的錯誤不會拋出異常,並且渲染器無斷字地繼續,所以第一次載入時的壞模式檔或網路故障會全程靜默持續。 每次後續渲染也會缺少斷字,無其他錯誤信號。 在應用程式啟動或部署期間驗證模式檔並確認URL可存取性 - 而非在渲染時。
快取鍵識別: 快取鍵是ExceptionSource)的準確字串值。 指向相同URL或檔案路徑的兩個渲染器實例共用相同的快取模式。 即使是同一檔案的不同版本,變更URL也會強制重新載入。
在生產環境部署前預先驗證檔案內容。 模式檔必須僅包含有效的斷字文字。 註解、TeX指令、編碼宣告或任何非模式內容的存在會導致整合失敗。 tex-hyphen儲存庫提供了數十種語言的預構建乾淨模式檔。
建議對遠端模式來源使用HTTPS。 HTTP雖可支援,但不提供檔案內容的傳輸層保護。
下一步是什麼?
ChromePdfRenderOptions上給予對由TeX模式檔支援的任何語言的單詞分裂行為的直接控制 — 擴展了PdfHyphenationLanguage提供的三個內建預設以外的功能。 模式檔載入自遠端URL或本地路徑,在首次使用後快取至記憶體,並在載入失敗時退回至HyphenationLanguage設定。 錯誤被記錄但從不拋出,因此在部署而不是渲染時應該進行模式驗證。
有關IronPDF渲染配置的相關資訊,請參見:
ChromePdfRenderOptionsAPI文獻提供所有可用的渲染選項PdfHyphenationLanguage枚舉提供內建語言預設- HTML到PDF渲染教程展示完整的HTML渲染管線
- 渲染選項說明提供其他ChromePdfRenderOptions配置
- IronPDF功能概覽展示完整的PDF生成和操作能力
獲取IronPDF的30天免費試用來測試在實際專案中的自訂斷字,或查看授權選項以供生產部署。
ChromePdfRendererPatternSourceCustomHyphenationDefinitionsstringhyphens: auto``RenderHtmlAsPdfCustomHyphenationDefinitionshyphens: autoHyphenationLanguageChromePdfRenderOptionshyph-en-us.pat.txt-webkit-hyphens: auto``text-align: justifyPdfHyphenationLanguageChromePdfRenderOptions
常見問題
如何使用C#在PDF生成中實施自定義連字?
您可以透過從URL或本地文件載入TeX連字模式來使用IronPDF在PDF生成中實施自定義連字,使您能在C#中生成PDF時控制單詞斷行。
什麼是TeX連字模式,及它們如何在IronPDF中使用?
TeX連字模式是一組在合適的連字點分詞的規則。IronPDF允許您載入這些模式來管理生成的PDF中文詞的連字方式。
我可以在IronPDF中從URL載入連字模式嗎?
是的,IronPDF支持直接從URL載入連字模式,從而為您的C# PDF專案提供動態和靈活的單詞斷行配置。
是否可以使用IronPDF的本地文件載入連字模式?
完全可以,IronPDF允許您從本地文件載入自定義連字模式,以便您精確控制PDF中的單詞連字。
使用IronPDF的自定義連字時有什麼限制?
在使用IronPDF的自定義連字時,您需要確保模式格式正確,並與預定的語言和文件佈局需求對齊。
為什麼我需要在我的PDF文件中使用自定義連字?
自定義連字有助於改善PDF文件的可讀性,並確保在處理複雜語言特定的單詞斷行時的格式一貫性。
IronPDF是否提供用於實施自定義連字的程式碼範例?
是的,IronPDF提供程式碼範例以幫助您在C#專案中實施自定義連字,使您更容易整合此功能至您的PDF生成流程中。
自定義連字如何改善PDF生成?
自定義連字通過允許對單詞斷行的精確控制來改善PDF生成,從而增強不同語言和格式下文件的外觀和可讀性。

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。