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# 庫:
-
將HTML轉換為支援CSS和JavaScript的PDF 。
- 確保在Windows 、 Linux和Docker上佈局一致。
您的 PDF 庫應該易於使用,只需最少的程式碼,並提供高品質的渲染效果。 對於雲端部署,請查閱Azure 部署和AWS Lambda 整合指南。
您的團隊最重視PDF庫的哪些功能?
| 圖書館 | HTML至PDF | JS 支援 | 編輯PDF | 執照 | 最佳用例 |
|---|---|---|---|---|---|
| IronPDF | 是的 | 全文 | Yes | 商業 | 具有動態內容的 Web 應用程式 |
| iText 7 | 是的 | 限額 | Yes | 商業 | 企業合規性與靜態 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 檢視器顯示一個簡單的文檔,其中包含"Hello from 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 安全功能資訊。
常見問題解答
生成發票的最佳 C# PDF 庫是什麼?
IronPDF 因其強大的功能和易於在 .NET 應用程序中整合而成為生成發票的熱門選擇。
IronPDF 與 iText 在 PDF 生成方面的比較如何?
IronPDF 提供更簡單的 API 和詳盡的文件,使得開發人員能夠更輕鬆地進行整合和使用,與 iText 相比。
我可以使用 IronPDF 將報告轉換為 PDF 嗎?
可以,IronPDF 非常適合有效地將各種類型的報告轉換為 PDF 格式。
IronPDF 與現代 .NET 應用程序兼容嗎?
IronPDF 完全兼容現代 .NET 應用程序,為開發人員提供無縫整合。
使用 IronPDF 相較於 PDFSharp 的優勢是什麼?
IronPDF 提供比 PDFSharp 更先進的功能和對現代 .NET 環境的更好支持。
IronPDF 是否支持在 Web 應用程序中整合表單?
是的,IronPDF 支持在 Web 應用程序中整合表單,提供處理表單數據和 PDF 交互的工具。
哪個 PDF 庫最適合 C# 初學者?
IronPDF 使用方便並提供豐富的文擋,使其成為 C# 初學者的絕佳選擇。
IronPDF 的定價與其他 PDF 庫相比如何?
IronPDF 提供具競爭力的定價和多種授權選項,通常比其他高端 PDF 庫提供更好的價值。
IronPDF 是否能處理大規模的 PDF 處理任務?
是的,IronPDF 設計用於高效處理大規模的 PDF 處理任務,適合企業級項目。
IronPDF 用戶有哪些支持選項?
IronPDF 提供全面的支持,包括文件、教程和響應快速的客戶服務以協助用戶。

