如何在 PDF 中設置字體
網頁字型是專為網站使用而設計的字型。 這些字體存放於網路伺服器上,並由網頁瀏覽器下載,以確保在網站上無論用戶的本地字體是否可用,都能保持文字呈現的一致性和視覺上的吸引力。 此外,圖標字體使用符號和圖形,常用於網頁設計中創建可縮放、可自定義的圖標,並通過 CSS 操作維持視覺上的一致性用戶介面。
CSS包括網頁字體,允許您在訪問您的網站時指定要下載的字體文件。 IronPDF支持從HTML加載和渲染字體到PDF。
如何在 PDF 中設置字體
- 下載 C# 庫 IronPDF 以設定 PDF 字體
- 利用 HTML 從外部來源導入或請求字體
- 延遲渲染過程以確保字體正確加載
- 如往常一樣將HTML渲染為PDF。
- 在 CSS 樣式中使用 @font-face 規則導入字體文件
開始使用 IronPDF
立即在您的專案中使用IronPDF,並享受免費試用。
使用網頁字體和圖示示例
IronPDF 支援網路字體 (例如 Google 字體和 Adobe 網頁字體 API)以及圖標字體,例如 Bootstrap 使用的字體FontAwesome.
字體在渲染時常需要一些延遲才能正確加載。 當字型未正確載入時,可能會導致頁面空白,沒有任何文字。 您可以使用 WaitFor.AllFontsLoaded
方法來等待字型載入,並為其指定最大等待時間。 預設的最大等待時間是500毫秒。
以下是如何使用的一個小例子網頁字體在您的專案中命名為Lobster。
:path=/static-assets/pdf/content-code-examples/how-to/webfonts-webicons-render-webfont.cs
using IronPdf;
// HTML contains webfont
var html = @"<link href=""https://fonts.googleapis.com/css?family=Lobster"" rel=""stylesheet"">
<p style=""font-family: 'Lobster', serif; font-size:30px;"" > Hello Google Fonts</p>";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Wait for font to load
renderer.RenderingOptions.WaitFor.AllFontsLoaded(2000);
// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
// Export the PDF
pdf.SaveAs("font-test.pdf");
Imports IronPdf
' HTML contains webfont
Private html = "<link href=""https://fonts.googleapis.com/css?family=Lobster"" rel=""stylesheet"">
<p style=""font-family: 'Lobster', serif; font-size:30px;"" > Hello Google Fonts</p>"
Private renderer As New ChromePdfRenderer()
' Wait for font to load
renderer.RenderingOptions.WaitFor.AllFontsLoaded(2000)
' Render HTML to PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
' Export the PDF
pdf.SaveAs("font-test.pdf")
探索更多的WaitFor選項,例如字體、JavaScript、HTML元素和網路閒置等選項。IronPDF WaitFor 類別文檔.'
導入字型檔案範例
要使用現有的字體文件,請應用@font-faceCSS 樣式中的規則。 它也能在使用@font-face規則和嵌入base64編碼的woff文件的組合時工作。 在以下示例中,我將使用像素化无衬线字体.
:path=/static-assets/pdf/content-code-examples/how-to/webfonts-webicons-custom-font.cs
using IronPdf;
// Import custom font
string html = @"<!DOCTYPE html>
<html>
<head>
<style>
@font-face {font-family: 'Pixelify';
src: url('fonts\PixelifySans-VariableFont_wght.ttf');
}
p {
font-family: 'Pixelify';
font-size: 70px;
}
</style>
</head>
<body>
<p>Custom font</p>
</body>
</html>";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
// Export the PDF
pdf.SaveAs("customFont.pdf");
Imports IronPdf
' Import custom font
Private html As String = "<!DOCTYPE html>
<html>
<head>
<style>
@font-face {font-family: 'Pixelify';
src: url('fonts\PixelifySans-VariableFont_wght.ttf');
}
p {
font-family: 'Pixelify';
font-size: 70px;
}
</style>
</head>
<body>
<p>Custom font</p>
</body>
</html>"
Private renderer As New ChromePdfRenderer()
' Render HTML to PDF
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
' Export the PDF
pdf.SaveAs("customFont.pdf")
Azure PDF 的限制
這Azure代管平台不支援在其較低共享網路應用程式層級中的伺服器加載SVG字體。 然而,Azure 的 VPS 和 Web Role 並不是以相同方式進行沙盒化,且支持網絡字體渲染。