如何在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生成期間應用了該行為。 ChromePdfRenderOptions中控制使用哪種斷詞模式。

模式文件使用TeX格式並可以從本地文件路徑或遠程URL加載。 這使得可以為不同語言和文檔佈局定義自訂的斷詞規則,在最終PDF中更好地控制單詞斷行。

本指南解釋了如何在C#中使用CustomHyphenationDefinitions API,包括本地和遠程模式加載、回退行為、限制、錯誤處理和緩存。


NuGet 用 NuGet 安裝

PM >  Install-Package IronPdf

NuGet 查看 https://www.nuget.org/packages/IronPdf 以快速安裝。超過 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. CustomHyphenationDefinitions
  4. 在HTML內容的CSS中包含hyphens: auto
  5. 呼叫RenderHtmlAsPdf並保存結果

自訂斷詞在PDF渲染中如何運作?

CustomHyphenationDefinitions類定義了IronPDF在渲染過程中從哪裡加載斷詞規則。 Chromium引擎讀取這些模式並在HTML元素上存在CSS hyphens: auto規則時應用它們。

CustomHyphenationDefinitions類是什麼?

該類暴露了兩個屬性:

表1: CustomHyphenationDefinitions屬性
屬性類型必需描述
PatternSourcestring斷詞模式文件的路徑或URL(例如,hyph-en-us.pat.txt
ExceptionSourcestring斷詞例外文件的路徑或URL(例如,hyph-en-us.hyp.txt

模式文件遵循由GitHub上的tex-hyphen項目維護的TeX斷詞格式。 每個語言在庫中都有兩個文件:https://raw.githubusercontent.com/開頭)—標準的GitHub頁面URL返回HTML而不是模式文本。

自訂斷詞如何覆蓋內建語言設定?

ChromePdfRenderOptions上提供了內建的英語(美國)、英語(英國)和俄語預設。 當兩者都設置時,CustomHyphenation屬性優先於該枚舉,遵循明確的優先鏈:

  1. CustomHyphenation — 如果設置了有效的PatternSource,則使用自定義模式
  2. HyphenationLanguage — 如果沒有配置自定義模式,則應用內建語言預設
  3. — 如果未設置兩者,則不發生斷詞

自訂模式加載失敗時會發生什麼?

模式加載期間的錯誤將被記錄但不會拋出異常。渲染操作會繼續進行而不進行斷詞,而不是失敗。 如果也配置了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兼容,需要-webkit-hyphens: auto兩個CSS宣告。 text-align: justify規則使斷詞最顯眼。 如果目標HTML元素上沒有CSS宣告,則自訂模式會被加載但從不應用。

請注意URL必須指向原始文本內容。 像https://github.com/hyphenation/tex-hyphen/blob/master/...這樣的標準GitHub URL返回一個HTML頁面包裝,會導致模式驗證失敗。 使用https://raw.githubusercontent.com/...形式,或點擊GitHub上的"Raw"按鈕以獲得正確的URL。)}]

遠程源的約束條件是什麼?

表2: 遠程URL約束
約束
協議HTTP和HTTPS(推薦HTTPS)
允許的內容類型text/plainapplication/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 小時在線上。
聊天
電子郵件
打電話給我