C# PDF库比较:IronPDF vs iText 7, PDFSharp, Aspose, Syncfusion, QuestPDF等
对于正在评估 C# PDF 库的工程经理而言,IronPDF 通过缩短开发时间并提供全面的功能,能带来最佳的投资回报。 相比之下,PDFSharp 等开源选项更适合满足基础的编程需求,且初始成本较低。
在现代 .NET 应用程序中处理 PDF 文档的重要性日益凸显。 无论是生成发票、转换报告,还是将表单集成到 Web 应用程序中,您都需要可靠的 C# PDF 库。 面对众多选择,哪款 PDF 库最适合您的项目?
本文将 IronPDF 与 iText、PDFSharp、Aspose、Syncfusion、QuestPDF 等热门选项进行了对比分析。 您将了解每款 .NET PDF 库如何处理 PDF 生成、HTML 转 PDF、编辑及其他关键功能。 本对比涵盖许可、性能和易用性等方面,以助您做出正确决策。
为什么需要 C# PDF 库?
在探讨具体产品之前,请先思考为何需要用于处理 PDF 文件的 C# 库:
-
支持 CSS 和 JavaScript 的 HTML 转 PDF 功能。
- 确保在 Windows、Linux 和 Docker 环境中的布局保持一致。
您的 PDF 库应易于使用、代码量少且能提供高质量的渲染效果。 关于云部署,请查阅 Azure 部署指南和 AWS Lambda 集成指南。
对于您的团队而言,哪些 PDF 库功能最为重要?
| 库 | HTML 到 PDF | JS 支持 | 编辑 PDF | 许可 | 最佳使用场景 |
|---|---|---|---|---|---|
| IronPDF | 是 | 完整 | Yes | 商业 | 具有动态内容的 Web 应用程序 |
| iText 7 | 是 | 有限的 | Yes | 商业 | Enterprise 合规与静态 HTML |
PDFSharp / MigraDoc |
否 | 不适用 | Partial | 开源 | 通过编程方式创建 PDF 及自定义版式 |
| Aspose.PDF | 是 | 部分 | Yes | 商业 | 企业自动化和多格式转换 |
| Syncfusion PDF | 是 | 部分 | Yes | 商业 | 报告与仪表盘 |
| QuestPDF | 否 | 不适用 | Yes | 开源 | 结构化程序化 PDF |
wkhtmltopdf (DinkToPdf) |
是 | 有限的 | 否 | 开源 | 静态 HTML 转 PDF |
下表简要概述了各库的核心优势,可帮助您根据 HTML/JS 支持、编辑功能及许可协议选择合适的工具。 以下各节将探讨每个库如何处理 HTML 转 PDF 或常规 PDF 创建等基本任务。
什么是 IronPDF,何时应该使用它?
IronPDF 是一款现代化的商用 .NET PDF 库,旨在让 PDF 相关工作既简单又高效。与需要手动绘制或使用低级 API 的库不同,IronPDF 专注于实际应用场景:HTML 转 PDF、PDF 编辑以及使用极少代码生成报告。 该实现为您处理了复杂性,特别是在内容以 HTML 形式存在的 Web 应用程序中。 IronPDF 可在 Windows、.NET Framework、.NET Core 以及 Docker 等容器化平台上运行,使其在本地和云端部署中均具有广泛的适用性。
您的团队为何应选择 IronPDF?
- 将HTML 转换为 PDF ,并完全支持CSS和JavaScript 。
IronPDF如何处理复杂的网页内容?
为了演示 IronPDF 如何处理包含复杂 CSS 或 JavaScript 的HTML 内容,请参考以下URL 转换示例:
using IronPdf;
class Program
{
static void Main()
{
// Initialize the Chrome PDF renderer
var renderer = new ChromePdfRenderer();
// Configure rendering options for optimal output
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.JavaScript(3000); // Wait 3 seconds for JS execution
// Set page size and margins
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 10; // millimeters
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.MarginLeft = 10;
renderer.RenderingOptions.MarginRight = 10;
// Convert URL to PDF
var pdf = renderer.RenderUrlAsPdf("___PROTECTED_URL_170___");
// Save the PDF document
pdf.SaveAs("output.pdf");
// Optional: Add metadata
pdf.MetaData.Title = "Wikipedia Main Page";
pdf.MetaData.Author = "IronPDF Example";
pdf.MetaData.Subject = "URL to PDF Conversion";
}
}
using IronPdf;
class Program
{
static void Main()
{
// Initialize the Chrome PDF renderer
var renderer = new ChromePdfRenderer();
// Configure rendering options for optimal output
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.JavaScript(3000); // Wait 3 seconds for JS execution
// Set page size and margins
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 10; // millimeters
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.MarginLeft = 10;
renderer.RenderingOptions.MarginRight = 10;
// Convert URL to PDF
var pdf = renderer.RenderUrlAsPdf("___PROTECTED_URL_170___");
// Save the PDF document
pdf.SaveAs("output.pdf");
// Optional: Add metadata
pdf.MetaData.Title = "Wikipedia Main Page";
pdf.MetaData.Author = "IronPDF Example";
pdf.MetaData.Subject = "URL to PDF Conversion";
}
}
Imports IronPdf
Class Program
Shared Sub Main()
' Initialize the Chrome PDF renderer
Dim renderer = New ChromePdfRenderer()
' Configure rendering options for optimal output
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
renderer.RenderingOptions.EnableJavaScript = True
renderer.RenderingOptions.WaitFor.JavaScript(3000) ' Wait 3 seconds for JS execution
' Set page size and margins
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
renderer.RenderingOptions.MarginTop = 10 ' millimeters
renderer.RenderingOptions.MarginBottom = 10
renderer.RenderingOptions.MarginLeft = 10
renderer.RenderingOptions.MarginRight = 10
' Convert URL to PDF
Dim pdf = renderer.RenderUrlAsPdf("___PROTECTED_URL_170___")
' Save the PDF document
pdf.SaveAs("output.pdf")
' Optional: Add metadata
pdf.MetaData.Title = "Wikipedia Main Page"
pdf.MetaData.Author = "IronPDF Example"
pdf.MetaData.Subject = "URL to PDF Conversion"
End Sub
End Class
您可以期待获得哪些结果?
维基百科首页截图,显示了主要布局,包括关于摄影师费利切·贝亚托的专题文章、时事新闻版块(包括雅伊尔·博尔索纳罗的判决)以及"历史上的今天"历史事件版块。
IronPDF 只需编写极少的代码,即可生成高保真 PDF,渲染复杂的 CSS 布局和动态 JavaScript 内容。 该库的Chrome 渲染引擎可确保像素级完美输出,与现代浏览器完美匹配。 您的应用程序可以立即使用此功能来处理cookie 、 HTTP 标头或身份验证。
结论: IronPDF 是易于使用、高性能 PDF 生成工具的首选,它具有出色的 HTML/CSS/JS 渲染功能和专业的支持。 观看演示视频,了解其实际应用效果。
PDF库如何处理Bootstrap和现代CSS框架?
在使用Bootstrap 和现代 CSS 框架的应用程序中选择 C# PDF 库时,框架兼容性决定了您的设计是否能够准确转换或需要修改。 这种方法为使用响应式设计模式的团队带来了明显的益处。
为什么基于 Chromium 的渲染对 Bootstrap 很重要?
IronPDF 的 Chromium 引擎充分支持: Bootstrap 5:完整的 Flexbox 布局、CSS Grid、实用类、所有组件 Bootstrap 4:完整的卡片系统、导航、弹性实用程序、响应式设计
- Tailwind CSS:所有实用类都支持浏览器精确渲染。 -基础:完整的网格系统和组件支持 -现代CSS3: Flexbox、CSS Grid、自定义属性、动画、过渡效果
实际验证:IronPDF 能够以像素级的精度渲染Bootstrap 主页和官方示例。 该库为您管理复杂性,包括Google Fonts 、 SVG 图形和自定义字体。
Bootstrap有哪些局限性?
iText 7:对 flexbox 的支持有限(v7.1.15 版本新增),不支持 CSS Grid,存在 Bootstrap 3 的限制,需要使用变通方法才能使用现代组件。
PDFSharp 和 MigraDoc:不支持原生 HTML 渲染——仅支持手动创建 PDF,不支持 Bootstrap。
Aspose.PDF:自定义引擎,约 90% 支持 CSS3,部分支持 flexbox,需要对 Bootstrap 组件进行大量测试。
Syncfusion PDF:基于 WebKit 的引擎,没有 flexbox/CSS Grid,最高支持 Bootstrap 3,存在安全问题(上次更新于 2016 年)。
QuestPDF:提供流畅的 API 以进行手动布局——不支持 HTML/CSS 渲染和 Bootstrap。
开发影响:非 Chromium 库需要并行"PDF 安全"布局,这会显著增加开发时间并降低设计一致性。
什么是 iText 7?何时应该使用它?
iText 7是一个可靠的企业级 C# PDF 库,用于生成、编辑和保护 PDF 文件。 该实现方案可处理金融、法律和企业应用中的PDF/A 、数字签名、编辑和合规性要求高的工作流程。 虽然 iText 7 可以处理 HTML 到 PDF 的转换,但它本身并不执行 JavaScript,因此需要对动态内容进行预处理。 7.1.15 版本增加了有限的 flexbox 支持,但许多 CSS3 功能仍然不受支持。 请查看我们的iText 与 IronPDF对比评测。
iText 7 有哪些特性使其适合企业应用?
iText 7 如何将 URL 转换为 PDF?
using iText.Html2pdf;
using System.Net.Http;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var url = "___PROTECTED_URL_171___";
// Create HTTP client with browser-like settings
using var client = new HttpClient();
// Add user agent to avoid 403 Forbidden responses
client.DefaultRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
"(KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36");
// Add timeout for reliability
client.Timeout = TimeSpan.FromSeconds(30);
// Fetch HTML content
string htmlContent = await client.GetStringAsync(url);
// Configure conversion properties
var converterProperties = new ConverterProperties();
converterProperties.SetBaseUri(url); // Important for resolving relative URLs
// Create PDF from HTML
using var fileStream = new FileStream("itext7-output.pdf", FileMode.Create);
HtmlConverter.ConvertToPdf(htmlContent, fileStream, converterProperties);
Console.WriteLine("PDF created successfully!");
}
}
using iText.Html2pdf;
using System.Net.Http;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var url = "___PROTECTED_URL_171___";
// Create HTTP client with browser-like settings
using var client = new HttpClient();
// Add user agent to avoid 403 Forbidden responses
client.DefaultRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
"(KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36");
// Add timeout for reliability
client.Timeout = TimeSpan.FromSeconds(30);
// Fetch HTML content
string htmlContent = await client.GetStringAsync(url);
// Configure conversion properties
var converterProperties = new ConverterProperties();
converterProperties.SetBaseUri(url); // Important for resolving relative URLs
// Create PDF from HTML
using var fileStream = new FileStream("itext7-output.pdf", FileMode.Create);
HtmlConverter.ConvertToPdf(htmlContent, fileStream, converterProperties);
Console.WriteLine("PDF created successfully!");
}
}
Imports iText.Html2pdf
Imports System.Net.Http
Imports System.IO
Imports System.Threading.Tasks
Module Program
Async Function Main() As Task
Dim url As String = "___PROTECTED_URL_171___"
' Create HTTP client with browser-like settings
Using client As New HttpClient()
' Add user agent to avoid 403 Forbidden responses
client.DefaultRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " &
"(KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36")
' Add timeout for reliability
client.Timeout = TimeSpan.FromSeconds(30)
' Fetch HTML content
Dim htmlContent As String = Await client.GetStringAsync(url)
' Configure conversion properties
Dim converterProperties As New ConverterProperties()
converterProperties.SetBaseUri(url) ' Important for resolving relative URLs
' Create PDF from HTML
Using fileStream As New FileStream("itext7-output.pdf", FileMode.Create)
HtmlConverter.ConvertToPdf(htmlContent, fileStream, converterProperties)
End Using
Console.WriteLine("PDF created successfully!")
End Using
End Function
End Module
iText 7 的 HTML 渲染有哪些局限性?
维基百科侧边栏导航的屏幕截图,显示了复杂的嵌套菜单、链接和表单元素,这些都体现了 PDF 转换工具面临的挑战。
这段代码获取 HTML 内容并将其转换为 PDF。 结果保留了页面布局、文本、图像和 CSS 样式,但动态 JavaScript 内容将无法渲染。 对于 JavaScript 代码较多的页面,可以考虑使用 IronPDF 的JavaScript 渲染功能或实现自定义渲染延迟。
结论: iText 7 在企业级 PDF 生成和编辑方面表现出色,具有强大的合规性支持和静态 HTML 到 PDF 的转换功能。 对于 JavaScript 或高级 CSS,请考虑使用 IronPDF 或 wkhtmltopdf。
什么是 PDFSharp 和 MigraDoc?何时应该使用它们?
PDFSharp和 MigraDoc 是用于程序化创建 PDF 的免费开源 C# PDF 库。 PDFSharp 处理底层 PDF 生成,而 MigraDoc 提供用于表格、段落和多页文档的高级布局 API。 这些库不提供 HTML 到 PDF 的转换,因此当您需要在代码中完全控制文档结构时,它们是理想的选择。 有关程序化绘图,请参阅有关绘制线条和矩形以及绘制文本和位图的指南。
为什么选择 PDFSharp 生成简单的 PDF 文件?
-
免费和开源(MIT 许可证)。
-
通过编程方式创建包含文本、图像和表格的 PDF 文件。
-
支持多页面布局,
MigraDoc。 -
轻巧且易于集成。
-
完全控制绘图和定位。
- 适用于.NET Framework和.NET Core 。
如何使用 PDFSharp 以编程方式创建 PDF?
using PdfSharp.Drawing;
using PdfSharp.Fonts;
using PdfSharp.Pdf;
using static System.Net.Mime.MediaTypeNames;
class Program
{
static void Main()
{
// Configure font resolver for cross-platform compatibility
GlobalFontSettings.UseWindowsFontsUnderWindows = true;
// Create a new PDF document
var document = new PdfDocument();
document.Info.Title = "PDFSharp Example";
document.Info.Author = "Your Team";
document.Info.Subject = "Demonstrating PDFSharp capabilities";
// Add a page to the document
var page = document.AddPage();
page.Size = PdfSharp.PageSize.A4;
page.Orientation = PdfSharp.PageOrientation.Portrait;
// Create graphics object for drawing
var gfx = XGraphics.FromPdfPage(page);
// Draw text at specific coordinates
var font = new XFont("Verdana", 20, XFontStyleEx.Regular);
gfx.DrawString("Hello from PDFSharp!", font, XBrushes.Black,
new XPoint(50, 100));
// Add more content - a rectangle
var pen = new XPen(XColors.Navy, 2);
gfx.DrawRectangle(pen, XBrushes.LightBlue, 50, 150, 200, 100);
// Add text inside rectangle
var smallFont = new XFont("Arial", 12, XFontStyleEx.Regular);
gfx.DrawString("Custom drawing example", smallFont, XBrushes.DarkBlue,
new XPoint(60, 200));
// Save the document
document.Save("pdfsharp-example.pdf");
Console.WriteLine("PDF created with PDFSharp!");
}
}
using PdfSharp.Drawing;
using PdfSharp.Fonts;
using PdfSharp.Pdf;
using static System.Net.Mime.MediaTypeNames;
class Program
{
static void Main()
{
// Configure font resolver for cross-platform compatibility
GlobalFontSettings.UseWindowsFontsUnderWindows = true;
// Create a new PDF document
var document = new PdfDocument();
document.Info.Title = "PDFSharp Example";
document.Info.Author = "Your Team";
document.Info.Subject = "Demonstrating PDFSharp capabilities";
// Add a page to the document
var page = document.AddPage();
page.Size = PdfSharp.PageSize.A4;
page.Orientation = PdfSharp.PageOrientation.Portrait;
// Create graphics object for drawing
var gfx = XGraphics.FromPdfPage(page);
// Draw text at specific coordinates
var font = new XFont("Verdana", 20, XFontStyleEx.Regular);
gfx.DrawString("Hello from PDFSharp!", font, XBrushes.Black,
new XPoint(50, 100));
// Add more content - a rectangle
var pen = new XPen(XColors.Navy, 2);
gfx.DrawRectangle(pen, XBrushes.LightBlue, 50, 150, 200, 100);
// Add text inside rectangle
var smallFont = new XFont("Arial", 12, XFontStyleEx.Regular);
gfx.DrawString("Custom drawing example", smallFont, XBrushes.DarkBlue,
new XPoint(60, 200));
// Save the document
document.Save("pdfsharp-example.pdf");
Console.WriteLine("PDF created with PDFSharp!");
}
}
Imports PdfSharp.Drawing
Imports PdfSharp.Fonts
Imports PdfSharp.Pdf
Imports System.Net.Mime.MediaTypeNames
Module Program
Sub Main()
' Configure font resolver for cross-platform compatibility
GlobalFontSettings.UseWindowsFontsUnderWindows = True
' Create a new PDF document
Dim document As New PdfDocument()
document.Info.Title = "PDFSharp Example"
document.Info.Author = "Your Team"
document.Info.Subject = "Demonstrating PDFSharp capabilities"
' Add a page to the document
Dim page = document.AddPage()
page.Size = PdfSharp.PageSize.A4
page.Orientation = PdfSharp.PageOrientation.Portrait
' Create graphics object for drawing
Dim gfx = XGraphics.FromPdfPage(page)
' Draw text at specific coordinates
Dim font As New XFont("Verdana", 20, XFontStyleEx.Regular)
gfx.DrawString("Hello from PDFSharp!", font, XBrushes.Black, New XPoint(50, 100))
' Add more content - a rectangle
Dim pen As New XPen(XColors.Navy, 2)
gfx.DrawRectangle(pen, XBrushes.LightBlue, 50, 150, 200, 100)
' Add text inside rectangle
Dim smallFont As New XFont("Arial", 12, XFontStyleEx.Regular)
gfx.DrawString("Custom drawing example", smallFont, XBrushes.DarkBlue, New XPoint(60, 200))
' Save the document
document.Save("pdfsharp-example.pdf")
Console.WriteLine("PDF created with PDFSharp!")
End Sub
End Module
PDFSharp何时才是最佳选择?
! PDF 查看器显示一个简单的文档,其中包含"来自 PDFSharp 的问候!"文本,演示了 PDFSharp 库的基本 PDF 生成功能。
这段代码通过编程方式生成 PDF 文件,手动添加文本并处理布局。 该实现为没有 HTML 输入的自定义文档(如发票、表单或证书)提供了明显的优势。 如需了解具有更多功能的类似程序化控制,请参阅创建新的 PDF 。
结论: PDFSharp 和 MigraDoc 非常适合基本的 PDF 创建——免费且易于集成,但缺乏 HTML 转换和高级编辑功能。 对于 HTML 工作流程,请考虑使用 IronPDF 的 HTML 转 PDF 功能。## 什么是 Aspose.PDF 以及何时应该使用它?
Aspose.PDF是一个商业性的 .NET PDF 库,提供用于创建、编辑、转换和保护 PDF 的完整工具。 与轻量级库不同,Aspose.PDF 专注于企业应用程序,支持包括Word 、Excel、 HTML和XML在内的文件转换。 您的应用程序可以立即使用此功能在大规模应用程序中实现文档自动化、报告生成和高级 PDF 操作。 请查看我们的Aspose 与 IronPDF对比评测。
Aspose.PDF 提供哪些企业级功能?
*支持异步的高性能生成。
- 支持.NET Framework 、 .NET Core和 .NET 6+。
Aspose.PDF 如何处理 URL 到 PDF 的转换?
using Aspose.Pdf;
using System;
using System.IO;
using System.Net;
class Program
{
static void Main()
{
string url = "___PROTECTED_URL_172___";
// Optional: provide credentials for protected resources
NetworkCredential credentials = null;
// Example for authenticated resources:
// credentials = new NetworkCredential("username", "password");
// Configure HTML load options
var options = new HtmlLoadOptions(url)
{
// Enable external resources loading
ExternalResourcesCredentials = credentials,
// Set page info
PageInfo = new PageInfo
{
Width = PageSize.A4.Width,
Height = PageSize.A4.Height,
Margin = new MarginInfo(20, 20, 20, 20) // left, bottom, right, top
},
// Enable JavaScript execution (limited support)
IsEmbedFonts = true,
IsRenderToSinglePage = false
};
try
{
// Fetch HTML content as stream and load into Document
using (var document = new Document(GetContentFromUrlAsStream(url, credentials), options))
{
// Add metadata
document.Info.Title = "Wikipedia Main Page";
document.Info.Author = "Aspose.PDF Example";
document.Info.Subject = "URL to PDF Conversion";
document.Info.Keywords = "PDF, Aspose, Wikipedia";
// Improve the PDF
document.OptimizeResources();
// Save PDF with specific save options
var saveOptions = new PdfSaveOptions
{
DefaultFontName = "Arial", // Fallback font
EmbedStandardFonts = true
};
document.Save("aspose-output.pdf", saveOptions);
}
Console.WriteLine("PDF successfully created!");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
private static Stream GetContentFromUrlAsStream(string url, ICredentials credentials = null)
{
using var handler = new System.Net.Http.HttpClientHandler { Credentials = credentials };
using var httpClient = new System.Net.Http.HttpClient(handler);
// Set a browser-like User-Agent to avoid 403 errors
httpClient.DefaultRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
"(KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36");
// Set timeout
httpClient.Timeout = TimeSpan.FromSeconds(30);
return httpClient.GetStreamAsync(url).GetAwaiter().GetResult();
}
}
using Aspose.Pdf;
using System;
using System.IO;
using System.Net;
class Program
{
static void Main()
{
string url = "___PROTECTED_URL_172___";
// Optional: provide credentials for protected resources
NetworkCredential credentials = null;
// Example for authenticated resources:
// credentials = new NetworkCredential("username", "password");
// Configure HTML load options
var options = new HtmlLoadOptions(url)
{
// Enable external resources loading
ExternalResourcesCredentials = credentials,
// Set page info
PageInfo = new PageInfo
{
Width = PageSize.A4.Width,
Height = PageSize.A4.Height,
Margin = new MarginInfo(20, 20, 20, 20) // left, bottom, right, top
},
// Enable JavaScript execution (limited support)
IsEmbedFonts = true,
IsRenderToSinglePage = false
};
try
{
// Fetch HTML content as stream and load into Document
using (var document = new Document(GetContentFromUrlAsStream(url, credentials), options))
{
// Add metadata
document.Info.Title = "Wikipedia Main Page";
document.Info.Author = "Aspose.PDF Example";
document.Info.Subject = "URL to PDF Conversion";
document.Info.Keywords = "PDF, Aspose, Wikipedia";
// Improve the PDF
document.OptimizeResources();
// Save PDF with specific save options
var saveOptions = new PdfSaveOptions
{
DefaultFontName = "Arial", // Fallback font
EmbedStandardFonts = true
};
document.Save("aspose-output.pdf", saveOptions);
}
Console.WriteLine("PDF successfully created!");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
private static Stream GetContentFromUrlAsStream(string url, ICredentials credentials = null)
{
using var handler = new System.Net.Http.HttpClientHandler { Credentials = credentials };
using var httpClient = new System.Net.Http.HttpClient(handler);
// Set a browser-like User-Agent to avoid 403 errors
httpClient.DefaultRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
"(KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36");
// Set timeout
httpClient.Timeout = TimeSpan.FromSeconds(30);
return httpClient.GetStreamAsync(url).GetAwaiter().GetResult();
}
}
Imports Aspose.Pdf
Imports System
Imports System.IO
Imports System.Net
Imports System.Net.Http
Class Program
Shared Sub Main()
Dim url As String = "___PROTECTED_URL_172___"
' Optional: provide credentials for protected resources
Dim credentials As NetworkCredential = Nothing
' Example for authenticated resources:
' credentials = New NetworkCredential("username", "password")
' Configure HTML load options
Dim options As New HtmlLoadOptions(url) With {
.ExternalResourcesCredentials = credentials,
.PageInfo = New PageInfo With {
.Width = PageSize.A4.Width,
.Height = PageSize.A4.Height,
.Margin = New MarginInfo(20, 20, 20, 20) ' left, bottom, right, top
},
.IsEmbedFonts = True,
.IsRenderToSinglePage = False
}
Try
' Fetch HTML content as stream and load into Document
Using document As New Document(GetContentFromUrlAsStream(url, credentials), options)
' Add metadata
document.Info.Title = "Wikipedia Main Page"
document.Info.Author = "Aspose.PDF Example"
document.Info.Subject = "URL to PDF Conversion"
document.Info.Keywords = "PDF, Aspose, Wikipedia"
' Improve the PDF
document.OptimizeResources()
' Save PDF with specific save options
Dim saveOptions As New PdfSaveOptions With {
.DefaultFontName = "Arial", ' Fallback font
.EmbedStandardFonts = True
}
document.Save("aspose-output.pdf", saveOptions)
End Using
Console.WriteLine("PDF successfully created!")
Catch ex As Exception
Console.WriteLine($"Error: {ex.Message}")
End Try
End Sub
Private Shared Function GetContentFromUrlAsStream(url As String, Optional credentials As ICredentials = Nothing) As Stream
Using handler As New HttpClientHandler With {.Credentials = credentials}
Using httpClient As New HttpClient(handler)
' Set a browser-like User-Agent to avoid 403 errors
httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " &
"(KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36")
' Set timeout
httpClient.Timeout = TimeSpan.FromSeconds(30)
Return httpClient.GetStreamAsync(url).GetAwaiter().GetResult()
End Using
End Using
End Function
End Class
这是维基百科首页的截图,显示了主要布局,包括关于交易所广场20号的专题文章、"新闻动态"、"你知道吗"和"历史上的今天"等历史事件。
此代码使用类似浏览器的用户代理获取 HTML 内容以防止 403 错误,将 HTML 直接流式传输到 Aspose.PDF 文档中(HtmlLoadOptions),然后保存为 PDF。 结果保留了页面布局、文本、图像和 CSS 样式,并支持基本的 HTTP 身份验证。 动态 JavaScript 内容将无法执行。 为了获得更好的 JavaScript 支持,请探索IronPDF 的 JavaScript 渲染功能。
结论: Aspose.PDF在需要高级功能、多格式转换和强大安全性的企业应用程序中表现出色。 虽然对于小型项目来说,它具有商业性和潜在复杂性,但对于大型文档工作流程而言,它是无与伦比的。
什么是 Syncfusion PDF?何时应该使用它?
Syncfusion PDF是 Syncfusion 套件的一部分,为 Web 和桌面应用程序提供功能丰富的 .NET PDF 库。 该库可以帮你处理生成、编辑和转换 PDF 的复杂性,包括 HTML 到 PDF 的转换,同时还能与其他 Syncfusion 组件无缝集成,用于生成报告和仪表板。 使用 Syncfusion 组件的团队可以受益于紧密集成。 请参阅我们的Syncfusion 与 IronPDF对比评测。
为什么选择 Syncfusion 作为集成解决方案?
-
将HTML 转换为支持 CSS 和图像的PDF。
-
为网页和桌面应用程序生成动态报表。
- 改进.NET Core 、 .NET Framework和ASP.NET Core 。
Syncfusion 如何将 URL 转换为 PDF?
using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
class Program
{
static void Main()
{
// Initialize the HTML to PDF converter
HtmlToPdfConverter converter = new HtmlToPdfConverter();
// Configure WebKit settings for better rendering
WebKitConverterSettings settings = new WebKitConverterSettings();
// Set WebKit path (required for deployment)
settings.WebKitPath = @"C:\QtBinariesPath";
// Configure page settings
settings.PdfPageSize = PdfPageSize.A4;
settings.Orientation = PdfPageOrientation.Portrait;
settings.Margin = new PdfMargins() { All = 20 };
// Enable JavaScript execution
settings.EnableJavaScript = true;
settings.JavaScriptDelay = 3000; // Wait 3 seconds for JS
// Set viewport size for responsive design
settings.ViewPortSize = new System.Drawing.Size(1024, 0);
// Add custom headers if needed
settings.HttpRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
converter.ConverterSettings = settings;
// Convert URL to PDF
PdfDocument document = converter.Convert("___PROTECTED_URL_173___");
// Add document info
document.DocumentInformation.Title = "Wikipedia Main Page";
document.DocumentInformation.Author = "Syncfusion Example";
document.DocumentInformation.Subject = "URL to PDF Conversion";
// Save the PDF
document.Save("syncfusion-output.pdf");
document.Close(true); // true = dispose resources
Console.WriteLine("PDF created successfully!");
}
}
using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
class Program
{
static void Main()
{
// Initialize the HTML to PDF converter
HtmlToPdfConverter converter = new HtmlToPdfConverter();
// Configure WebKit settings for better rendering
WebKitConverterSettings settings = new WebKitConverterSettings();
// Set WebKit path (required for deployment)
settings.WebKitPath = @"C:\QtBinariesPath";
// Configure page settings
settings.PdfPageSize = PdfPageSize.A4;
settings.Orientation = PdfPageOrientation.Portrait;
settings.Margin = new PdfMargins() { All = 20 };
// Enable JavaScript execution
settings.EnableJavaScript = true;
settings.JavaScriptDelay = 3000; // Wait 3 seconds for JS
// Set viewport size for responsive design
settings.ViewPortSize = new System.Drawing.Size(1024, 0);
// Add custom headers if needed
settings.HttpRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
converter.ConverterSettings = settings;
// Convert URL to PDF
PdfDocument document = converter.Convert("___PROTECTED_URL_173___");
// Add document info
document.DocumentInformation.Title = "Wikipedia Main Page";
document.DocumentInformation.Author = "Syncfusion Example";
document.DocumentInformation.Subject = "URL to PDF Conversion";
// Save the PDF
document.Save("syncfusion-output.pdf");
document.Close(true); // true = dispose resources
Console.WriteLine("PDF created successfully!");
}
}
Imports Syncfusion.HtmlConverter
Imports Syncfusion.Pdf
Imports System.Drawing
Class Program
Shared Sub Main()
' Initialize the HTML to PDF converter
Dim converter As New HtmlToPdfConverter()
' Configure WebKit settings for better rendering
Dim settings As New WebKitConverterSettings()
' Set WebKit path (required for deployment)
settings.WebKitPath = "C:\QtBinariesPath"
' Configure page settings
settings.PdfPageSize = PdfPageSize.A4
settings.Orientation = PdfPageOrientation.Portrait
settings.Margin = New PdfMargins() With {.All = 20}
' Enable JavaScript execution
settings.EnableJavaScript = True
settings.JavaScriptDelay = 3000 ' Wait 3 seconds for JS
' Set viewport size for responsive design
settings.ViewPortSize = New Size(1024, 0)
' Add custom headers if needed
settings.HttpRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
converter.ConverterSettings = settings
' Convert URL to PDF
Dim document As PdfDocument = converter.Convert("___PROTECTED_URL_173___")
' Add document info
document.DocumentInformation.Title = "Wikipedia Main Page"
document.DocumentInformation.Author = "Syncfusion Example"
document.DocumentInformation.Subject = "URL to PDF Conversion"
' Save the PDF
document.Save("syncfusion-output.pdf")
document.Close(True) ' true = dispose resources
Console.WriteLine("PDF created successfully!")
End Sub
End Class
Syncfusion的报告功能有哪些优势?
! PDF 查看器正在显示维基百科内容,但页面上却覆盖着 Syncfusion 试用版的醒目红色斜角水印。
此示例将 URL 转换为 PDF,保留布局、图像和格式。 Syncfusion PDF 在需要可靠地将 HTML 渲染成 PDF 的报告场景中表现出色。 该库支持专业文档的页眉和页脚、页码和书签。
结论: Syncfusion PDF 非常适合使用 Syncfusion 组件、需要专业 HTML 转 PDF 渲染或希望生成具有广泛功能的企业级 PDF 的团队。 如需了解其他选择,请查看我们的详细对比。
什么是 QuestPDF?何时应该使用它?
QuestPDF是一个开源的 C# 库,专注于使用声明式 API 以编程方式生成 PDF。 与 HTML 转 PDF 转换器不同,QuestPDF 完全使用代码构建 PDF,从而可以精确控制布局、文本、图像和表格。 您的应用程序可以立即使用此功能自动生成报告、发票和动态生成的结构化文档。 请查看我们的QuestPDF与IronPDF对比评测。
为什么选择 QuestPDF 进行程序化控制?
-
用于以编程方式创建 PDF 的声明式 API。
-
完全控制布局、表格、图像和格式。
- 非常适合动态报表生成和自动化工作流程。
如何使用 QuestPDF 的 Fluent API 构建 PDF?
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using QuestPDF.Previewer;
class Program
{
static void Main()
{
// Configure license (Community, Professional, or Enterprise)
QuestPDF.Settings.License = LicenseType.Community;
// Create document with fluent API
Document.Create(container =>
{
container.Page(page =>
{
// Page settings
page.Size(PageSizes.A4);
page.Margin(2, Unit.Centimetre);
page.PageColor(Colors.White);
page.DefaultTextStyle(x => x.FontSize(12).FontFamily(Fonts.Arial));
// Header section
page.Header()
.Height(100)
.Background(Colors.Grey.Lighten3)
.AlignCenter()
.AlignMiddle()
.Text("QuestPDF Example Document")
.FontSize(20)
.Bold()
.FontColor(Colors.Blue.Darken2);
// Content section
page.Content()
.PaddingVertical(1, Unit.Centimetre)
.Column(column =>
{
column.Spacing(20);
// Add title
column.Item().Text("Hello from QuestPDF!")
.FontSize(16)
.SemiBold()
.FontColor(Colors.Blue.Medium);
// Add paragraph
column.Item().Text(text =>
{
text.Span("This is an example of programmatic PDF generation using ");
text.Span("QuestPDF").Bold();
text.Span(". You have complete control over layout and styling.");
});
// Add table
column.Item().Table(table =>
{
table.ColumnsDefinition(columns =>
{
columns.RelativeColumn();
columns.RelativeColumn();
});
// Table header
table.Header(header =>
{
header.Cell().Background(Colors.Grey.Medium)
.Padding(5).Text("Feature").Bold();
header.Cell().Background(Colors.Grey.Medium)
.Padding(5).Text("Description").Bold();
});
// Table rows
table.Cell().Border(1).Padding(5).Text("Fluent API");
table.Cell().Border(1).Padding(5)
.Text("Build documents using method chaining");
table.Cell().Border(1).Padding(5).Text("Layout Control");
table.Cell().Border(1).Padding(5)
.Text("Precise control over element positioning");
});
});
// Footer section
page.Footer()
.Height(50)
.AlignCenter()
.Text(text =>
{
text.Span("Page ");
text.CurrentPageNumber();
text.Span(" of ");
text.TotalPages();
});
});
})
.GeneratePdf("questpdf-output.pdf");
Console.WriteLine("PDF created with QuestPDF!");
}
}
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using QuestPDF.Previewer;
class Program
{
static void Main()
{
// Configure license (Community, Professional, or Enterprise)
QuestPDF.Settings.License = LicenseType.Community;
// Create document with fluent API
Document.Create(container =>
{
container.Page(page =>
{
// Page settings
page.Size(PageSizes.A4);
page.Margin(2, Unit.Centimetre);
page.PageColor(Colors.White);
page.DefaultTextStyle(x => x.FontSize(12).FontFamily(Fonts.Arial));
// Header section
page.Header()
.Height(100)
.Background(Colors.Grey.Lighten3)
.AlignCenter()
.AlignMiddle()
.Text("QuestPDF Example Document")
.FontSize(20)
.Bold()
.FontColor(Colors.Blue.Darken2);
// Content section
page.Content()
.PaddingVertical(1, Unit.Centimetre)
.Column(column =>
{
column.Spacing(20);
// Add title
column.Item().Text("Hello from QuestPDF!")
.FontSize(16)
.SemiBold()
.FontColor(Colors.Blue.Medium);
// Add paragraph
column.Item().Text(text =>
{
text.Span("This is an example of programmatic PDF generation using ");
text.Span("QuestPDF").Bold();
text.Span(". You have complete control over layout and styling.");
});
// Add table
column.Item().Table(table =>
{
table.ColumnsDefinition(columns =>
{
columns.RelativeColumn();
columns.RelativeColumn();
});
// Table header
table.Header(header =>
{
header.Cell().Background(Colors.Grey.Medium)
.Padding(5).Text("Feature").Bold();
header.Cell().Background(Colors.Grey.Medium)
.Padding(5).Text("Description").Bold();
});
// Table rows
table.Cell().Border(1).Padding(5).Text("Fluent API");
table.Cell().Border(1).Padding(5)
.Text("Build documents using method chaining");
table.Cell().Border(1).Padding(5).Text("Layout Control");
table.Cell().Border(1).Padding(5)
.Text("Precise control over element positioning");
});
});
// Footer section
page.Footer()
.Height(50)
.AlignCenter()
.Text(text =>
{
text.Span("Page ");
text.CurrentPageNumber();
text.Span(" of ");
text.TotalPages();
});
});
})
.GeneratePdf("questpdf-output.pdf");
Console.WriteLine("PDF created with QuestPDF!");
}
}
Imports QuestPDF.Fluent
Imports QuestPDF.Helpers
Imports QuestPDF.Infrastructure
Imports QuestPDF.Previewer
Module Program
Sub Main()
' Configure license (Community, Professional, or Enterprise)
QuestPDF.Settings.License = LicenseType.Community
' Create document with fluent API
Document.Create(Sub(container)
container.Page(Sub(page)
' Page settings
page.Size(PageSizes.A4)
page.Margin(2, Unit.Centimetre)
page.PageColor(Colors.White)
page.DefaultTextStyle(Function(x) x.FontSize(12).FontFamily(Fonts.Arial))
' Header section
page.Header() _
.Height(100) _
.Background(Colors.Grey.Lighten3) _
.AlignCenter() _
.AlignMiddle() _
.Text("QuestPDF Example Document") _
.FontSize(20) _
.Bold() _
.FontColor(Colors.Blue.Darken2)
' Content section
page.Content() _
.PaddingVertical(1, Unit.Centimetre) _
.Column(Sub(column)
column.Spacing(20)
' Add title
column.Item().Text("Hello from QuestPDF!") _
.FontSize(16) _
.SemiBold() _
.FontColor(Colors.Blue.Medium)
' Add paragraph
column.Item().Text(Sub(text)
text.Span("This is an example of programmatic PDF generation using ")
text.Span("QuestPDF").Bold()
text.Span(". You have complete control over layout and styling.")
End Sub)
' Add table
column.Item().Table(Sub(table)
table.ColumnsDefinition(Sub(columns)
columns.RelativeColumn()
columns.RelativeColumn()
End Sub)
' Table header
table.Header(Sub(header)
header.Cell().Background(Colors.Grey.Medium) _
.Padding(5).Text("Feature").Bold()
header.Cell().Background(Colors.Grey.Medium) _
.Padding(5).Text("Description").Bold()
End Sub)
' Table rows
table.Cell().Border(1).Padding(5).Text("Fluent API")
table.Cell().Border(1).Padding(5) _
.Text("Build documents using method chaining")
table.Cell().Border(1).Padding(5).Text("Layout Control")
table.Cell().Border(1).Padding(5) _
.Text("Precise control over element positioning")
End Sub)
End Sub)
' Footer section
page.Footer() _
.Height(50) _
.AlignCenter() _
.Text(Sub(text)
text.Span("Page ")
text.CurrentPageNumber()
text.Span(" of ")
text.TotalPages()
End Sub)
End Sub)
End Sub) _
.GeneratePdf("questpdf-output.pdf")
Console.WriteLine("PDF created with QuestPDF!")
End Sub
End Module
QuestPDF 何时能发挥最佳效果?
! PDF 查看器显示由 QuestPDF 生成的文档,文档中白色页面上显示"来自 QuestPDF 的问候!"字样,缩放比例为 100%。
这演示了如何通过程序创建 PDF,无需输入 HTML 即可完全控制内容和布局。 QuestPDF 擅长创建需要精确定位的发票、表格和结构化报告。 对于需要类似控制功能并支持 HTML 的团队,请探索IronPDF 的程序化功能。
结论: QuestPDF 非常适合需要对 PDF 内容进行完全程序化控制的开发人员。 虽然缺乏 HTML 转换功能,但它在生成结构化、动态生成的 PDF 文件方面表现出色,可用于报告和自动化。
应该选择哪个 C# PDF 库?
选择合适的 C# PDF 库取决于您的项目需求和内容类型。 对于包含复杂 CSS 或 JavaScript 的动态 Web 内容, IronPDF提供最可靠的解决方案,具备高保真渲染和简洁的 API。对于需要符合 PDF/A 标准、支持数字签名或多格式转换的企业环境,iText 7 和 Aspose.PDF 提供丰富的功能、安全性和支持。
对于喜欢以编程方式控制文档布局和内容的开发人员来说,像 PDFSharp/MigraDoc 和 QuestPDF 这样的开源库非常出色,非常适合生成结构化报告、发票或票据,而无需 HTML。 Syncfusion PDF 为报表和仪表板提供了功能丰富的环境,而 wkhtmltopdf 则擅长将静态网页转换为具有高 CSS 保真度的 PDF。
如何评估企业准备情况?
评估企业准备情况时,请考虑以下因素:
支持与服务级别协议:IronPDF 提供24/5 全天候技术支持,并保证响应时间。 iText 7 和 Aspose 等商业库提供企业支持包。 开源方案依赖于社区支持。 如需帮助,请参阅工程支持指南和支持最佳实践。
安全与合规性:IronPDF 支持PDF/A 、 PDF/UA 、加密和数字签名。 图书馆定期接受安全审计,并符合 SOC 2 标准。 对于企业签名,请参阅HSM 集成。
性能与可扩展性:IronPDF 的Chrome 引擎能够高效地处理异步操作和多线程。 对于高容量场景,可考虑性能优化策略和并行处理。
总拥有成本:虽然开源选项没有许可费,但要考虑开发人员的时间、维护和支持成本。 IronPDF 的许可包含更新和支持,从而降低了长期成本。 探索适用于进行中项目的扩展功能。## 为什么今天就应该试用 IronPDF?
您准备好简化 .NET 应用程序中的 PDF 生成、编辑和 HTML 到 PDF 的转换了吗? 凭借其用户友好的 API、高质量的渲染效果和专业的支持,您可以快速上手并立即看到效果。 浏览我们的完整文档、代码示例和API 参考,以加快开发速度。 查看我们的更新日志,了解最新更新和重大改进的里程碑。
立即开始免费试用,了解为什么 IronPDF 是构建现代 .NET PDF 应用程序的开发人员的首选。 对于准备部署的团队,请探索我们的许可选项,这些选项定价透明,可在Windows 、 Linux 、 Docker 、 macOS以及Azure和AWS等云平台上灵活部署。 了解更多关于Ironword 文档和Ironsecuredoc 文档的 PDF 安全功能信息。
[{i:(iText, PDFSharp, Aspose, Syncfusion, and QuestPDF are registered trademarks of their respective owners. 本网站与 iText, PDFSharp, Aspose, Syncfusion, 或 QuestPDF 无关,也未得到它们的支持或资助。 所有产品名称、徽标和品牌均为各自所有者的财产。 比较仅供参考,反映撰写时公开可用的信息。)}]
常见问题解答
用于生成发票的最佳 C# PDF 库是什么?
IronPDF 因其强大的功能和在 .NET 应用程序中的易集成性而广受欢迎,用于生成发票。
IronPDF 和 iText 在 PDF 生成方面如何比较?
IronPDF 提供了更简单的 API 和全面的文档,使之比 iText 更容易被开发者集成和使用。
我能使用 IronPDF 将报告转换为 PDF 吗?
是的,IronPDF 非常适合于有效地将各种类型的报告转换为 PDF 格式。
IronPDF 是否与现代 .NET 应用程序兼容?
IronPDF 完全兼容现代 .NET 应用程序,为开发者提供无缝集成。
与 PDFSharp 相比,使用 IronPDF 有哪些优势?
与 PDFSharp 相比,IronPDF 提供了更高级的功能和对现代 .NET 环境的更好支持。
IronPDF 是否支持在 web 应用程序中集成表单?
是的,IronPDF 支持 web 应用程序中的表单集成,提供工具以处理表单数据和 PDF 交互。
哪个 C# PDF 库对初学者最好?
IronPDF 用户友好,并提供丰富的文档,是 C# 初学者的最佳选择。
IronPDF 的定价与其他 PDF 库相比如何?
IronPDF 提供具有竞争力的定价和多种许可选项,通常相比其他优质 PDF 库更具价值。
IronPDF 能否处理大规模的 PDF 处理任务?
是的,IronPDF 设计用于高效处理大规模的 PDF 处理任务,适合企业级项目。
IronPDF 用户有什么支持选项可用?
IronPDF 提供全方位的支持,包括文档、教程和响应性的客户服务来帮助用户。


