在生产环境中测试,无水印。
随时随地满足您的需求。
获得30天的全功能产品。
几分钟内就能启动并运行。
在您的产品试用期间,全面访问我们的支持工程团队。
将HTML转换为PDF是许多软件应用中的常见需求,例如生成报告、发票或将网页保存为PDF。 在本文中,我们将探讨三个用于 C# 中 HTML 到 PDF 转换的流行开源库,审视它们的优缺点,并讨论为什么 IronPDF 在许多情况下是更好的选择。
从Pixabay添加上传
或拖放图像到此处
添加图片替代文本
PuppeteerSharp 是 Puppeteer 的一个 .NET 包装器,Puppeteer 是一个无头的 Chromium 浏览器。 它使开发人员能够利用Chromium渲染引擎将HTML文档转换为PDF。
PuppeteerSharp 提供对渲染过程的精确控制。 这里有一个例子:
using PuppeteerSharp;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Download Chromium
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
// Launch Browser
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))
{
// Open a new page
var page = await browser.NewPageAsync();
// Set HTML content
await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>");
// Generate PDF
await page.PdfAsync("output.pdf");
Console.WriteLine("PDF Generated Successfully!");
}
}
}
using PuppeteerSharp;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Download Chromium
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
// Launch Browser
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))
{
// Open a new page
var page = await browser.NewPageAsync();
// Set HTML content
await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>");
// Generate PDF
await page.PdfAsync("output.pdf");
Console.WriteLine("PDF Generated Successfully!");
}
}
}
Imports PuppeteerSharp
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
' Download Chromium
Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultChromiumRevision)
' Launch Browser
Using browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
' Open a new page
Dim page = Await browser.NewPageAsync()
' Set HTML content
Await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>")
' Generate PDF
Await page.PdfAsync("output.pdf")
Console.WriteLine("PDF Generated Successfully!")
End Using
End Function
End Class
下载Chromium:PuppeteerSharp会自动下载所需的Chromium版本以确保兼容性。
启动浏览器: 使用 Puppeteer.LaunchAsync() 启动一个无头版的 Chromium 实例。
设定 HTML 内容:使用 page.SetContentAsync() 将所需的 HTML 加载到浏览器页面中。
生成 PDF:使用 page.PdfAsync() 方法生成已渲染内容的 PDF。
结果是一个高质量的 PDF(output.pdf),可以准确复制 HTML 结构和设计。
从Pixabay添加上传
或拖放图像到此处
添加图片替代文本
PdfSharp 是一个强大的开源库,用于在 C# 中创建和操作 PDF 文件。 虽然它不直接支持HTML渲染,但它在为开发人员提供工具,以编程方式生成和编辑PDF文档方面表现出色。
PDF 创建:PdfSharp 允许开发人员通过定义页面大小、添加文本、形状、图像等,从头生成新的 PDF 文件。
现有 PDF 的操作:您可以修改现有的 PDF 文档,例如合并、拆分或提取内容。
绘图功能:PdfSharp 提供强大的图形功能,使用 XGraphics 类在 PDF 文件中添加自定义设计。
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
// Example HTML content
string htmlContent = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>";
// Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlContent);
// Create a new PDF document
PdfDocument pdfDocument = new PdfDocument();
pdfDocument.Info.Title = "HTML to PDF Example";
// Add a new page to the document
PdfPage page = pdfDocument.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont titleFont = new XFont("Arial", 20, XFontStyle.Bold);
XFont textFont = new XFont("Arial", 12, XFontStyle.Regular);
// Draw the parsed HTML content
int yPosition = 50; // Starting Y position
foreach (var node in htmlDoc.DocumentNode.SelectNodes("//h1
//p"))
{
if (node.Name == "h1")
{
gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 30; // Adjust spacing
}
else if (node.Name == "p")
{
gfx.DrawString(node.InnerText, textFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 20; // Adjust spacing
}
}
// Save the PDF document
string outputFilePath = "HtmlToPdf.pdf";
pdfDocument.Save(outputFilePath);
System.Console.WriteLine($"PDF file created: {outputFilePath}");
}
}
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
// Example HTML content
string htmlContent = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>";
// Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlContent);
// Create a new PDF document
PdfDocument pdfDocument = new PdfDocument();
pdfDocument.Info.Title = "HTML to PDF Example";
// Add a new page to the document
PdfPage page = pdfDocument.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont titleFont = new XFont("Arial", 20, XFontStyle.Bold);
XFont textFont = new XFont("Arial", 12, XFontStyle.Regular);
// Draw the parsed HTML content
int yPosition = 50; // Starting Y position
foreach (var node in htmlDoc.DocumentNode.SelectNodes("//h1
//p"))
{
if (node.Name == "h1")
{
gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 30; // Adjust spacing
}
else if (node.Name == "p")
{
gfx.DrawString(node.InnerText, textFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 20; // Adjust spacing
}
}
// Save the PDF document
string outputFilePath = "HtmlToPdf.pdf";
pdfDocument.Save(outputFilePath);
System.Console.WriteLine($"PDF file created: {outputFilePath}");
}
}
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Imports HtmlAgilityPack
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Example HTML content
Dim htmlContent As String = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>"
' Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
Dim htmlDoc = New HtmlDocument()
htmlDoc.LoadHtml(htmlContent)
' Create a new PDF document
Dim pdfDocument As New PdfDocument()
pdfDocument.Info.Title = "HTML to PDF Example"
' Add a new page to the document
Dim page As PdfPage = pdfDocument.AddPage()
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
Dim titleFont As New XFont("Arial", 20, XFontStyle.Bold)
Dim textFont As New XFont("Arial", 12, XFontStyle.Regular)
' Draw the parsed HTML content
Dim yPosition As Integer = 50 ' Starting Y position
'INSTANT VB TODO TASK: The following line uses invalid syntax:
' foreach(var node in htmlDoc.DocumentNode.SelectNodes("//h1 { if (node.Name == "h1") { gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft); yPosition += 30; } else if (node.Name == "p") { gfx.DrawString(node.InnerText, textFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft); yPosition += 20; } } string outputFilePath = "HtmlToPdf.pdf"; pdfDocument.Save(outputFilePath); System.Console.WriteLine(string.Format("PDF file created: {0}", outputFilePath)); } }
HTML 解析:该示例使用 HtmlAgilityPack(一个用于解析和操作 HTML 的开源库)从
标签中提取文本内容。
绘制内容:PdfSharp 的 XGraphics 类用于将解析的 HTML 内容呈现为 PDF 页面的文本。
从Pixabay添加上传
或拖放图像到此处
添加图片替代文本
Pdfium.NET 是基于开源 PDFium 项目的综合库,专为在 .NET 应用程序中查看、编辑和操作 PDF 文件而设计。 它为开发人员提供了强大的工具来创建、编辑和提取PDF的内容,使其适用于多种使用场景。 这基本上是一个免费的HTML到PDF转换库。
PDF创建和编辑:
文本和图像提取:
PDF查看器控件:
兼容性:
高级功能:
using Pdfium.Net.SDK;
using System;
class Program
{
static void Main(string[] args)
{
// Initialize Pdfium.NET SDK
PdfCommon.Initialize();
// Create a new PDF document
PdfDocument pdfDocument = PdfDocument.CreateNew();
// Add a page to the document
var page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842); // A4 size in points (8.27 x 11.69 inches)
// Add HTML content (example: parsed manually)
var htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>";
// Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
var font = PdfFont.CreateFont(pdfDocument, "Arial");
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!");
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.");
// Save the document
string outputFilePath = "HtmlToPdfExample.pdf";
pdfDocument.Save(outputFilePath, SaveFlags.Default);
Console.WriteLine($"PDF created successfully: {outputFilePath}");
}
}
using Pdfium.Net.SDK;
using System;
class Program
{
static void Main(string[] args)
{
// Initialize Pdfium.NET SDK
PdfCommon.Initialize();
// Create a new PDF document
PdfDocument pdfDocument = PdfDocument.CreateNew();
// Add a page to the document
var page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842); // A4 size in points (8.27 x 11.69 inches)
// Add HTML content (example: parsed manually)
var htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>";
// Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
var font = PdfFont.CreateFont(pdfDocument, "Arial");
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!");
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.");
// Save the document
string outputFilePath = "HtmlToPdfExample.pdf";
pdfDocument.Save(outputFilePath, SaveFlags.Default);
Console.WriteLine($"PDF created successfully: {outputFilePath}");
}
}
Imports Pdfium.Net.SDK
Imports System
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Initialize Pdfium.NET SDK
PdfCommon.Initialize()
' Create a new PDF document
Dim pdfDocument As PdfDocument = PdfDocument.CreateNew()
' Add a page to the document
Dim page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842) ' A4 size in points (8.27 x 11.69 inches)
' Add HTML content (example: parsed manually)
Dim htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>"
' Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
Dim font = PdfFont.CreateFont(pdfDocument, "Arial")
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!")
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.")
' Save the document
Dim outputFilePath As String = "HtmlToPdfExample.pdf"
pdfDocument.Save(outputFilePath, SaveFlags.Default)
Console.WriteLine($"PDF created successfully: {outputFilePath}")
End Sub
End Class
SDK 初始化:PdfCommon.Initialize() 方法用于初始化 Pdfium.NET 功能。
创建 PDF:使用 PdfDocument.CreateNew() 创建一个新的 PDF 文档。
添加页面:页面将以指定尺寸(例如A4尺寸)插入到PDF中。
渲染HTML内容:由于Pdfium.NET SDK不原生支持HTML渲染,您需要手动解析并将HTML元素渲染为文本、形状或图像。
从Pixabay添加上传
或拖放图像到此处
添加图片替代文本
IronPDF 是一个专业级库,专为 .NET 开发人员设计,可轻松将 HTML 内容转换为高质量的 PDF。 IronPDF以其可靠性、先进功能和易用性而闻名,在提供精确渲染和强大功能的同时简化了开发过程。 以下是IronPDF作为一个出色解决方案的原因:
直接将HTML转换为PDF: 使用IronPDF直接将包含CSS和JavaScript的HTML内容创建成完整格式的PDF文档。 只需几行代码,开发人员即可从网页、原始HTML字符串或本地HTML文件生成PDF。
现代渲染能力:支持最新的网络标准,IronPDF确保复杂布局、样式和交互元素的精确渲染,以将HTML页面转换为PDF。
高级PDF功能:IronPDF 提供广泛的自定义选项,例如添加页眉、页脚、水印、注释和书签。 它还支持合并、拆分和编辑现有的PDF。 拆分PDF文档,
性能和可扩展性: IronPDF针对小规模应用和企业环境进行了优化,无论项目规模大小,都能提供快速可靠的性能。
IronPDF因其功能组合、开发者支持和性能在众多解决方案中脱颖而出。 与通常需要广泛配置或外部依赖的开源替代方案不同,IronPDF 是一个自包含的解决方案,可以在不牺牲功能的情况下简化开发。 无论是用于生成发票、报告,还是存档网页内容,IronPDF都为开发人员提供了所需的工具,以快速高效地实现专业级成果。
IronPDF 是一个实用的选择,适合那些重视其 HTML 转 PDF 工作流的可靠性、可扩展性和易用性的开发人员。
class Program
{
static void Main()
{
// Specify license key
License.LicenseKey = "Yoour Key";
// Create a new HtmlToPdf object
var Renderer = new ChromePdfRenderer();
// Define the HTML string/ HTML code to be converted, can use html document
string htmlContent = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>";
// Convert pdf simple HTML string to a PDF document
var document = Renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf"); // path to pdf file generated
}
}
class Program
{
static void Main()
{
// Specify license key
License.LicenseKey = "Yoour Key";
// Create a new HtmlToPdf object
var Renderer = new ChromePdfRenderer();
// Define the HTML string/ HTML code to be converted, can use html document
string htmlContent = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>";
// Convert pdf simple HTML string to a PDF document
var document = Renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf"); // path to pdf file generated
}
}
Friend Class Program
Shared Sub Main()
' Specify license key
License.LicenseKey = "Yoour Key"
' Create a new HtmlToPdf object
Dim Renderer = New ChromePdfRenderer()
' Define the HTML string/ HTML code to be converted, can use html document
Dim htmlContent As String = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>"
' Convert pdf simple HTML string to a PDF document
Dim document = Renderer.RenderHtmlAsPdf(htmlContent)
' Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf") ' path to pdf file generated
End Sub
End Class
程序通过设置IronPDF 许可证密钥开始,这样做是为了解锁库的全部功能。
一个ChromePdfRenderer实例被初始化。 该组件负责将HTML内容转换为PDF文档,充当原始HTML与最终输出之间的桥梁。
创建了一个字符串变量htmlContent,用于存储将转换为PDF的HTML结构。 在此示例中,它包含一个简单的标题。
在 ChromePdfRenderer 实例上调用 RenderHtmlAsPdf() 方法,将 HTML 字符串作为输入传递。 此功能处理内容并将其转换为PDF文档。
最后,生成的 PDF 使用 SaveAs() 方法保存为名为 "html2Pdf.pdf" 的文件,并存储在磁盘上以便日后访问。
从Pixabay添加上传
或拖放图像到此处
添加图片替代文本
IronPDF 需要有效的许可证密钥才能实现全部功能。 您可以从官方网站获取试用许可证。在使用IronPDF库之前,请按如下设置许可证密钥:
IronPdf.License.LicenseKey = "your key";
IronPdf.License.LicenseKey = "your key";
IronPdf.License.LicenseKey = "your key"
这确保了库的操作没有限制。
PuppeteerSharp 是一个优秀的选择,特别适合需要精确将 HTML 渲染为 PDF 的开发人员,尤其是在处理复杂网页时。 然而,对于需要高级PDF特性、性能优化和便捷整合的应用程序,专业工具如IronPDF通常是更好的选择。
PdfSharp 是一个很好的选择,用于轻量级的程序化 PDF 创建和操作,特别适合具有简单需求的项目。 然而,如果您的应用程序需要将HTML转换为PDF或使用高级PDF功能,IronPDF 提供了一个更高效且功能丰富的解决方案。
虽然 Pdfium.NET SDK 是一个用于 PDF 操作的强大工具,但IronPDF 提供了对直接 HTML 到 PDF 转换的本机支持,包括渲染现代 HTML、CSS 和 JavaScript。 IronPDF通过内置方法如HtmlToPdf.RenderHtmlAsPdf()简化工作流程,使开发者的工作更快速高效。
无论是用于生成发票、报告,还是存档网页内容,IronPDF都为开发人员提供了所需的工具,以快速高效地实现专业级成果。
IronPDF 是一个实用的选择,适合重视可靠性、可扩展性和易用性的开发人员在其HTML到PDF的工作流程中使用。