HTML 中的自訂字體轉換為 PDF
為了確保需要時間載入的資源能夠正確渲染,必須使用waitFor類別指定渲染延遲。 這包括 JavaScript、字體和網頁資源等資產。
若要使用 Google Fonts 中的自訂字體渲染 HTML 內容,請配置渲染選項以使用waitFor屬性。 將等待類型設為RenderDelay ,並指定最大等待時間為 500 毫秒。
渲染 HTML 後,利用IronPDF 的 PDF 產生庫的功能匯出 PDF 文件。 您可以查看生成的 PDF 文件,確認自訂字體已完美載入和顯示。
// C# Example Code for Rendering HTML with custom font using IronPDF
using IronPdf;
class Program
{
static void Main()
{
// Step 1: Initialize the Renderer
var Renderer = new HtmlToPdf();
// Configure rendering options to wait for specific assets to load
Renderer.PrintOptions.WaitFor = WebBrowserEvent.RenderDelay;
Renderer.PrintOptions.RenderDelay = 500; // Maximum wait time set to 500 milliseconds
// Step 2: Define HTML with a custom Google Font link
string htmlContent = @"
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<link href='https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap' rel='stylesheet'>
<style>
body {
font-family: 'Roboto', sans-serif;
}
h1 {
font-weight: 700;
}
</style>
<title>Sample PDF</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph with a custom Google font.</p>
</body>
</html>";
// Step 3: Render the HTML to a PDF document
var pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent);
// Step 4: Export the PDF document to a file
pdfDocument.SaveAs("SampleWithFonts.pdf");
// Output completion message
Console.WriteLine("PDF document created successfully with custom Google font!");
}
}// C# Example Code for Rendering HTML with custom font using IronPDF
using IronPdf;
class Program
{
static void Main()
{
// Step 1: Initialize the Renderer
var Renderer = new HtmlToPdf();
// Configure rendering options to wait for specific assets to load
Renderer.PrintOptions.WaitFor = WebBrowserEvent.RenderDelay;
Renderer.PrintOptions.RenderDelay = 500; // Maximum wait time set to 500 milliseconds
// Step 2: Define HTML with a custom Google Font link
string htmlContent = @"
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<link href='https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap' rel='stylesheet'>
<style>
body {
font-family: 'Roboto', sans-serif;
}
h1 {
font-weight: 700;
}
</style>
<title>Sample PDF</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph with a custom Google font.</p>
</body>
</html>";
// Step 3: Render the HTML to a PDF document
var pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent);
// Step 4: Export the PDF document to a file
pdfDocument.SaveAs("SampleWithFonts.pdf");
// Output completion message
Console.WriteLine("PDF document created successfully with custom Google font!");
}
}$vbLabelText $csharpLabel




