How to Convert HTML String to PDF in C
IronPDF 使用 Chrome 浏览器渲染引擎,用 C# 将 HTML 字符串转换为 PDF 文档,支持所有 HTML5、CSS3 和 JavaScript 内容,只需一行代码即可完成基本转换。 该库为 创建 PDF 提供了强大的功能,同时保持了完美的渲染保真度。
IronPDF允许开发者在.NET Core和.NET Framework的C#、F#和VB.NET中轻松创建PDF文档。 IronPDF 支持将任何 HTML 字符串渲染为 PDF,渲染过程使用功能齐全的谷歌 Chromium 引擎版本。这确保了 HTML 内容在现代网络浏览器中的显示效果,使其成为从动态 HTML 内容生成报告、发票和文档的理想选择。
快速入门:几秒钟内将 HTML 字符串转换为 PDF
使用 IronPDF 将 HTML 字符串转换为 PDF 文件。 本指南演示了如何用最少的代码在 C# 中将 HTML 字符串转换为 PDF 文档。 非常适合需要将 PDF 渲染功能集成到其项目中的开发人员。
最小工作流程(5 个步骤)
- 从 NuGet 下载 IronPDF C# 库。
- 实例化 PDF 渲染器并传递 HTML 字符串
- 为 PDF 中的外部资产配置 BasePath
- 配置 RenderingOptions 以微调输出 PDF
- 保存并下载生成的 PDF
如何将简单的 HTML 字符串转换为 PDF?
以下是一个示例,展示了 IronPDF 如何使用 RenderHtmlAsPdf 方法将 HTML 字符串渲染为 PDF。 参数是要渲染为PDF的HTML字符串。 此方法属于 ChromePdfRenderer 类,该类为您的 PDF 生成需求提供了对渲染选项的全面控制。
:path=/static-assets/pdf/content-code-examples/how-to/html-string-to-pdf.cs
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from a HTML string using C#
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
// Export to a file or Stream
pdf.SaveAs("output.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer = New ChromePdfRenderer()
' Create a PDF from a HTML string using C#
Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
' Export to a file or Stream
pdf.SaveAs("output.pdf")
RenderHtmlAsPdf 方法返回一个 PdfDocument 对象,该对象存储 PDF 信息并提供用于操作 PDF 的方法,包括合并 PDF、添加水印以及设置安全选项。
using 代码块中。 ChromePdfRenderer 支持多线程,可仅实例化一次并在不同请求中重复使用,从而提升性能。}}
当从外部来源获取 HTML 字符串且需要禁用本地磁盘访问或跨源请求时,请在渲染前将 IronPdf.Installation.EnableWebSecurity 设置为 true。 这是一个静态全局设置,而非渲染器上的实例属性。
// Enable web security before rendering untrusted HTML
IronPdf.Installation.EnableWebSecurity = true;
// Enable web security before rendering untrusted HTML
IronPdf.Installation.EnableWebSecurity = true;
' Enable web security before rendering untrusted HTML
IronPdf.Installation.EnableWebSecurity = True
对于包含 CSS 样式的复杂 HTML 内容,请使用 Base URLs & Asset Encoding 功能通过内联样式或引用外部样式表来增强 HTML 字符串:
// Example with inline CSS
var styledHtml = @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; border-bottom: 2px solid #0066cc; }
p { line-height: 1.6; }
</style>
</head>
<body>
<h1>Professional Report</h1>
<p>This PDF was generated from HTML with custom styling.</p>
</body>
</html>";
using var styledPdf = renderer.RenderHtmlAsPdf(styledHtml);
styledPdf.SaveAs("styled-output.pdf");
// Example with inline CSS
var styledHtml = @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; border-bottom: 2px solid #0066cc; }
p { line-height: 1.6; }
</style>
</head>
<body>
<h1>Professional Report</h1>
<p>This PDF was generated from HTML with custom styling.</p>
</body>
</html>";
using var styledPdf = renderer.RenderHtmlAsPdf(styledHtml);
styledPdf.SaveAs("styled-output.pdf");
Dim styledHtml As String = "
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; border-bottom: 2px solid #0066cc; }
p { line-height: 1.6; }
</style>
</head>
<body>
<h1>Professional Report</h1>
<p>This PDF was generated from HTML with custom styling.</p>
</body>
</html>"
Using styledPdf = renderer.RenderHtmlAsPdf(styledHtml)
styledPdf.SaveAs("styled-output.pdf")
End Using
生成的 PDF 看起来像什么?
这是代码生成的文件:
生成的 PDF 将保持 HTML 的准确格式和样式,因此非常适合 生成 PDF 报告或将网页内容转换为可打印的文档。
在将 HTML 转换为 PDF 时如何包含外部资产?
本例显示 IronPDF 从可选的 BasePath 加载外部图像资产。 设置BaseUrlOrPath属性提供了超链接、图像、CSS和JavaScript文件的相对文件路径或URL上下文。 这在处理 PDF 中的图片或需要引用外部资源时尤为重要。
:path=/static-assets/pdf/content-code-examples/how-to/html-string-to-pdf-2.cs
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Advanced Example with HTML Assets
// Load external html assets: Images, CSS and JavaScript.
// An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer = New ChromePdfRenderer()
' Advanced Example with HTML Assets
' Load external html assets: Images, CSS and JavaScript.
' An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
Private myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\site\assets\")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
对于涉及复杂布局或动态内容的高级场景,请利用 IronPDF 对 JavaScript 渲染的支持:
// Example with JavaScript-generated content
var jsHtml = @"
<html>
<head>
<script>
window.onload = function() {
document.getElementById('dynamic').innerHTML =
'Generated on: ' + new Date().toLocaleString();
};
</script>
</head>
<body>
<h1>Dynamic Content Example</h1>
<div id='dynamic'></div>
</body>
</html>";
// Configure rendering to wait for JavaScript execution
renderer.RenderingOptions.WaitFor.RenderDelay(500); // milliseconds
using var dynamicPdf = renderer.RenderHtmlAsPdf(jsHtml, @"C:\site\");
dynamicPdf.SaveAs("dynamic-content.pdf");
// Example with JavaScript-generated content
var jsHtml = @"
<html>
<head>
<script>
window.onload = function() {
document.getElementById('dynamic').innerHTML =
'Generated on: ' + new Date().toLocaleString();
};
</script>
</head>
<body>
<h1>Dynamic Content Example</h1>
<div id='dynamic'></div>
</body>
</html>";
// Configure rendering to wait for JavaScript execution
renderer.RenderingOptions.WaitFor.RenderDelay(500); // milliseconds
using var dynamicPdf = renderer.RenderHtmlAsPdf(jsHtml, @"C:\site\");
dynamicPdf.SaveAs("dynamic-content.pdf");
Imports System
' Example with JavaScript-generated content
Dim jsHtml As String = "
<html>
<head>
<script>
window.onload = function() {
document.getElementById('dynamic').innerHTML =
'Generated on: ' + new Date().toLocaleString();
};
</script>
</head>
<body>
<h1>Dynamic Content Example</h1>
<div id='dynamic'></div>
</body>
</html>"
' Configure rendering to wait for JavaScript execution
renderer.RenderingOptions.WaitFor.RenderDelay(500) ' milliseconds
Using dynamicPdf = renderer.RenderHtmlAsPdf(jsHtml, "C:\site\")
dynamicPdf.SaveAs("dynamic-content.pdf")
End Using
在处理外部资产时,您可能需要处理身份验证或特殊标头。 IronPDF 通过 HTTP Request Header 功能提供支持,允许您在获取资源时包含授权令牌或自定义标头。
为什么设置 BasePath 对于外部资源很重要?
这是代码生成的文件:
正确设置 BasePath 可确保正确解析 HTML 中的所有相对引用。 没有它,IronPDF 就无法定位图片、样式表或脚本等外部资源。这一点在以下情况下尤为重要
1.转换引用本地文件系统资源的 HTML 2.使用相对 URL 的内容管理系统 3.将现有网页内容转换为 PDF 格式 4.创建使用共享资产的模板
对于基于网络的资源,请使用完整的 URL 作为基本路径:
// Using a web URL as base path
var webBasedPdf = renderer.RenderHtmlAsPdf(
"<link rel='stylesheet' href='/styles/main.css'><h1>Web Content</h1>",
"https://mywebsite.com"
);
// Using a web URL as base path
var webBasedPdf = renderer.RenderHtmlAsPdf(
"<link rel='stylesheet' href='/styles/main.css'><h1>Web Content</h1>",
"https://mywebsite.com"
);
' Using a web URL as base path
Dim webBasedPdf = renderer.RenderHtmlAsPdf(
"<link rel='stylesheet' href='/styles/main.css'><h1>Web Content</h1>",
"https://mywebsite.com"
)
如需对 PDF 生成过程进行更多控制,请浏览 IronPDF 有关 自定义页边距、页面方向 和 PDF压缩 的大量文档,以便针对各种使用情况优化您的输出文件。
常见问题解答
如何用 C# 将简单的 HTML 字符串转换为 PDF?
您可以使用 IronPDF 的 ChromePdfRenderer 类中的 RenderHtmlAsPdf 方法将 HTML 字符串转换为 PDF。只需实例化渲染器,将 HTML 字符串传递给该方法,然后保存生成的 PdfDocument 对象即可。IronPDF 使用 Chrome 浏览器渲染引擎,以确保完美的保真度。
HTML 到 PDF 的转换使用什么渲染引擎?
IronPDF 使用功能齐全的 Google Chromium 引擎版本将 HTML 渲染为 PDF。这可确保您的 HTML 内容(包括 HTML5、CSS3 和 JavaScript)在现代网络浏览器中的显示效果完全一致。
我能否将带有 CSS 样式的 HTML 转换为 PDF?
是的,IronPDF 支持将带有 CSS 样式的 HTML 转换为 PDF。您可以直接在 HTML 字符串中使用内联样式,或使用基础 URL 和资产编码功能引用外部样式表,以确保样式内容的正确呈现。
将 HTML 转换为 PDF 的最快方法是什么?
最快捷的方法是使用 IronPDF 的静态方法:IronPdf.ChromePdfRenderer.StaticRenderHtmlAsPdf("Your HTML").SaveAs("output.pdf").这一行代码就能转换 HTML 字符串并将其保存为 PDF 文件。
转换 HTML 字符串时如何处理外部资产?
IronPDF 允许您为 PDF 中的外部资产配置 BasePath。这可确保在转换过程中正确加载 HTML 中引用的图片、样式表和其他资源。
从 HTML 转换为 PDF 时,能否自定义 PDF 输出?
是的,IronPDF 提供了广泛的 RenderingOptions(渲染选项),可对 PDF 输出进行微调。您可以通过 ChromePdfRenderer 类控制页面大小、页边距、页眉、页脚以及生成的 PDF 的许多其他方面。
转换后生成的 PDF 有哪些用途?
IronPDF 的 PdfDocument 对象提供了大量 PDF 操作方法,包括合并 PDF、添加水印、设置安全选项等。转换后的 PDF 可保存到磁盘、流式传输或根据需要进一步处理。
从外部资源转换 HTML 时如何处理安全性问题?
从外部资源转换 HTML 时,IronPDF 允许您将 ChromePdfRenderer 上的 EnableWebSecurity 属性设置为 true。这将禁止本地磁盘访问和跨源请求,从而增强安全性。

