SpirePDF C# HTML到PDF教程和庫比較
將HTML轉換為PDF是許多.NET應用程式的重要需求,從生成發票和報告到建立文件和電子書。 在選擇IronPDF或Spire.PDF進行HTML到PDF轉換時,了解它們的優勢、限制和實際性能是至關重要的。 這份全面的比較檢視了這兩個庫的功能,幫助您做出有根據的PDF生成需求決策。
IronPDF和Spire.PDF在HTML到PDF轉換方面的關鍵差異是什麼?
IronPDF是一個用途廣泛的.NET PDF庫,設計用於處理許多與PDF相關的任務,包括轉換PDF文件、PDF編輯、PDF建立、閱讀PDF文件等。 它因易於整合到現有.NET應用程式中、高性能以及支持現代Web標準如HTML5、CSS3和JavaScript而聞名。 IronPDF的基於Chrome的渲染引擎確保了從HTML內容生成像素完美的PDF。
Spire.PDF for .NET是另一個強大的.NET PDF庫,提供了全面的PDF建立和操作功能。 它支持各種PDF功能,如文字和圖片提取、PDF表單填寫和數位簽名。 雖然功能全面,但其HTML到PDF轉換功能存在特定限制,開發者需考慮。
| 類別 | 特徵/方面 | IronPDF | Spire.PDF | 主要優勢 |
|---|---|---|---|---|
| 核心架構 | 設計理念 | 簡單優先,直觀的API | 多類方法,手動設置 | IronPDF:更快的開發 |
| API複雜性 | 簡單的方法如 RenderHtmlAsPdf() |
需要多執行緒方法 | IronPDF:更簡單的API | |
| 學習曲線 | 低 | 中到高 | IronPDF:更快的採用 | |
| 平台支持 | 跨平台 | 原生支援,無需額外的套件 | 限制對Linux/macOS的支持 | IronPDF:真正的跨平台 |
| .NET版本 | .NET 8, 7, 6, 5, Core 3.1+, Framework 4.6.2+ | .NET Core 2.0+, Framework 2.0+ | 兩者:廣泛的框架支持 | |
| 操作系統 | Windows, Linux, macOS, Docker原生 | 主要針對Windows | IronPDF:更廣泛的OS支持 | |
| HTML到PDF | 渲染引擎 | 完整的Chrome V8引擎 | 自定義HTML解析器 | IronPDF:高瀏覽器一致性 |
| CSS3/HTML5 支持 | 完全支持 | 有限(僅基本CSS) | IronPDF:現代Web標準 | |
| JavaScript 執行 | 全面的 JavaScript 支持 | 有限的 JavaScript 支持 | IronPDF:動態內容準備 | |
| Web字體 | Google字體、系統字體 | 有限的字體支持 | IronPDF:排版靈活性 | |
| 渲染速度 | 由於Chrome的開銷,對於簡單HTML略慢 | 對於簡單/靜態HTML更快 | Spire:對基礎HTML的開銷較低 | |
| Security & Encryption | 加密級別 | AES-256,自定義處理器 | AES-256標準 | 兩者:行業標準 |
| API簡單性 | 單一SecuritySettings類 |
多種安全方法 | IronPDF:統一的方法 | |
| 內容操作 | 編輯方法 | 真實內容移除,一行API | 手動矩形覆蓋 | IronPDF:合規準備 |
| 浮水印 | 基於HTML/CSS,完整樣式 | 基於文字,具有旋轉功能 | IronPDF:豐富的水印 | |
| 文件轉換 | DOCX到PDF | 內建DocxToPdfRenderer |
需要Spire.Doc庫 | IronPDF:無額外費用 |
| 性能指標 | 記憶體使用量 | 更高(Chrome引擎開銷) | 更低(更簡單的渲染引擎) | Spire:較低的記憶體佔用 |
| 執行緒支持 | 原生async/await優化 | 需要STA執行緒 | IronPDF:現代異步模式 | |
| 開發體驗 | 程式碼範例 | 100多個即用樣例 | 基本範例 | IronPDF:豐富的資源 |
| 錯誤資訊 | 描述性,可行的 | 技術資訊 | IronPDF:更好的除錯 | |
| Licensing & Pricing | 入門級 | Lite:$999(1位開發者,1個專案) | 開發者:$999/年(1開發者) | IronPDF:永久授權 |
| 團隊授權 | Plus:$1,499(3開發者,3項目) | 站點企業:$4,599/年 | IronPDF:更高的團隊價值 | |
| Suite選項 | Iron Suite:$2,998(10個產品) | 無套件選項 | IronPDF:卓越的價值 | |
| 支持 | 包含支持 | 是的,工程支援24/5 | 僅限論壇(付費支持額外) | IronPDF:包含支持 |
| 支持渠道 | 電子郵件、聊天、電話、螢幕共享 | 論壇、電子郵件(付費階段) | IronPDF:更多渠道 | |
| 最佳適用 | 使用案例 | 現代Web應用程式,複雜的HTML/CSS | 簡單的文件,基本佈局 | 依上下文而異 |
欲了解更多關於IronPDF的詳細資訊,請存取ironpdf.com。
庫之間的跨平台相容性如何?
IronPDF
IronPDF以其廣泛的跨平台相容性而著稱。 它支持.NET框架內的多種環境,確保在不同平台上的無縫運行。 以下是IronPDF的平臺相容性摘要:
-
.NET 版本:
- 完全用C#, VB.NET和F#編寫和支持
- .NET Core(8, 7, 6, 5 和 3.1+)
- .NET Standard(2.0+)
- .NET Framework(4.6.2+)
- 應用環境: IronPDF在各種應用環境中運行,如Windows、Linux、Mac、Docker、Azure和AWS。
- IDEs: 適用於IDEs,如Microsoft Visual Studio和JetBrains Rider & ReSharper
- 操作系統和處理器: 支持許多不同的OS和處理器,包括Windows、Mac、Linux、x64、x86、ARM
欲了解IronPDF相容性的更多細節,請存取IronPDF功能頁面。
Spire.PDF
Spire.PDF在.NET環境內完全支持,但它在Windows操作系統內工作,而不像IronPDF擁有對Linux和macOS的原生支持。 當在macOS或Linux上部署時,Spire.PDF需要每個平臺的不同插件,這可能會增加部署情境的複雜性。
-
.NET 支持:
- .NET Framework 2.0+
- .NET Core 2.0+
- 用C#編寫,支持VB.NET
- 應用環境: Spire.PDF在各種應用環境中運行,如Windows和ASP.NET應用程式中。 它還可以支持Windows Forms。
哪個庫提供更好的HTML到PDF轉換功能?
IronPDF特性
- PDF轉換: IronPDF可以將HTML轉換為PDF。 憑藉對現代Web標準的全面支援,您可以確信IronPDF將持續地從您的HTML內容中返回像素完美的PDF。 IronPDF還可以將檔文件從其他格式轉換為PDF,如DOCX、圖片、RTF等。
- PDF生成: 使用IronPDF,您可以從URL、ASPX文件或HTML字串生成PDF。
- 安全特性: 使用IronPDF,您可以確保任何敏感PDF文件的安全,這要歸功於其安全特性。 使用IronPDF加密您的PDF文件,設置密碼並設置PDF文件的權限。
- PDF編輯功能: 使用IronPDF,您可以輕鬆處理現有的PDF文件,對其進行編輯,並閱讀PDF文件。 IronPDF提供編輯功能,如新增頁眉和頁腳,在PDF頁面上加蓋文字和圖片,向PDF新增自定義水印,與PDF表單一起使用,以及拆分或合併PDF文件。
- 整合: 無縫整合到ASP.NET和MVC應用程式中。
- PDF版本支持: 可以支持PDF版本1.2-1.7
要查看IronPDF功能的完整列表,請存取IronPDF功能。
Spire.PDF功能
- PDF建立: 從頭建立PDF或現有文件。
- 文字和圖片提取: 使用Spire.PDF提取PDF頁面和內容。
- PDF表單處理: 填寫和管理PDF表單。
- PDF轉換: 將PDF轉換為其他格式,如HTML、RTF和圖片。
- 頁面操作: 在PDF中插入、刪除和重新排序頁面。
- 有限的HTML支持: HTML到PDF引擎對現代CSS 和JavaScript的支持有限。 預設轉換路徑在CSS頁面斷開屬性和外部CSS檔識別上存在限制,JavaScript執行支持有限。 可選的ChromeHtmlConverter插件可提供更好的渲染。
Bootstrap和現代CSS框架渲染
現代Web開發嚴重依賴於像Bootstrap這樣的CSS框架,以便快速的UI開發和響應式設計。 PDF生成庫必須準確轉換這些框架,以保持專業製品質量和設計的一致性。
IronPDF:完整的Bootstrap和Tailwind支持
IronPDF的Chromium引擎提供了對所有現代CSS框架的完整支持:
- Bootstrap 5: 完整彈性框和CSS網格支持,具有所有響應組件
- Bootstrap 4: 完整的卡片佈局、導航系統和實用類
- Tailwind CSS: 所有實用優先類和響應式修飾語
- Foundation: 完整的網格和組件系統
- 現代CSS3: 彈性框、網格、自定義屬性、動畫和變換
以真實例子為證:Bootstrap首頁和Bootstrap範本以像素完美準確的轉換。
程式碼範例:團隊成員卡片使用Bootstrap
using IronPdf;
var renderer = new ChromePdfRenderer();
string bootstrapTeam = @"
<!DOCTYPE html>
<html>
<head>
<link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
</head>
<body>
<div class='container my-5'>
<h1 class='text-center mb-5'>Our Team</h1>
<div class='row row-cols-1 row-cols-md-3 g-4'>
<div class='col'>
<div class='card h-100 shadow-sm text-center'>
<div class='card-body d-flex flex-column'>
<img src='https://via.placeholder.com/150' class='rounded-circle mx-auto mb-3' alt='Team member' style='width: 150px; height: 150px; object-fit: cover;'>
<h5 class='card-title'>Jennifer Martinez</h5>
<p class='text-muted mb-3'>Chief Technology Officer</p>
<p class='card-text flex-grow-1'>Leading our technical vision and innovation strategy with over 15 years of experience in software architecture.</p>
<div class='d-flex justify-content-center gap-2 mt-auto'>
<a href='#' class='btn btn-sm btn-outline-primary'>LinkedIn</a>
<a href='#' class='btn btn-sm btn-outline-secondary'>Email</a>
</div>
</div>
</div>
</div>
<div class='col'>
<div class='card h-100 shadow-sm text-center'>
<div class='card-body d-flex flex-column'>
<img src='https://via.placeholder.com/150' class='rounded-circle mx-auto mb-3' alt='Team member' style='width: 150px; height: 150px; object-fit: cover;'>
<h5 class='card-title'>David Chen</h5>
<p class='text-muted mb-3'>Head of Engineering</p>
<p class='card-text flex-grow-1'>Managing our engineering teams and ensuring product quality through rigorous testing and code review processes.</p>
<div class='d-flex justify-content-center gap-2 mt-auto'>
<a href='#' class='btn btn-sm btn-outline-primary'>LinkedIn</a>
<a href='#' class='btn btn-sm btn-outline-secondary'>Email</a>
</div>
</div>
</div>
</div>
<div class='col'>
<div class='card h-100 shadow-sm text-center'>
<div class='card-body d-flex flex-column'>
<img src='https://via.placeholder.com/150' class='rounded-circle mx-auto mb-3' alt='Team member' style='width: 150px; height: 150px; object-fit: cover;'>
<h5 class='card-title'>Sarah Johnson</h5>
<p class='text-muted mb-3'>Product Manager</p>
<p class='card-text flex-grow-1'>Driving product strategy and customer satisfaction through data-driven decisions and user research.</p>
<div class='d-flex justify-content-center gap-2 mt-auto'>
<a href='#' class='btn btn-sm btn-outline-primary'>LinkedIn</a>
<a href='#' class='btn btn-sm btn-outline-secondary'>Email</a>
</div>
</div>
</div>
</div>
</div>
<div class='text-center mt-5'>
<h3>Join Our Team</h3>
<p class='text-muted mb-3'>We're always looking for talented individuals to join our growing team.</p>
<a href='#' class='btn btn-primary btn-lg'>View Open Positions</a>
</div>
</div>
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(bootstrapTeam);
pdf.SaveAs("team-members.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
string bootstrapTeam = @"
<!DOCTYPE html>
<html>
<head>
<link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
</head>
<body>
<div class='container my-5'>
<h1 class='text-center mb-5'>Our Team</h1>
<div class='row row-cols-1 row-cols-md-3 g-4'>
<div class='col'>
<div class='card h-100 shadow-sm text-center'>
<div class='card-body d-flex flex-column'>
<img src='https://via.placeholder.com/150' class='rounded-circle mx-auto mb-3' alt='Team member' style='width: 150px; height: 150px; object-fit: cover;'>
<h5 class='card-title'>Jennifer Martinez</h5>
<p class='text-muted mb-3'>Chief Technology Officer</p>
<p class='card-text flex-grow-1'>Leading our technical vision and innovation strategy with over 15 years of experience in software architecture.</p>
<div class='d-flex justify-content-center gap-2 mt-auto'>
<a href='#' class='btn btn-sm btn-outline-primary'>LinkedIn</a>
<a href='#' class='btn btn-sm btn-outline-secondary'>Email</a>
</div>
</div>
</div>
</div>
<div class='col'>
<div class='card h-100 shadow-sm text-center'>
<div class='card-body d-flex flex-column'>
<img src='https://via.placeholder.com/150' class='rounded-circle mx-auto mb-3' alt='Team member' style='width: 150px; height: 150px; object-fit: cover;'>
<h5 class='card-title'>David Chen</h5>
<p class='text-muted mb-3'>Head of Engineering</p>
<p class='card-text flex-grow-1'>Managing our engineering teams and ensuring product quality through rigorous testing and code review processes.</p>
<div class='d-flex justify-content-center gap-2 mt-auto'>
<a href='#' class='btn btn-sm btn-outline-primary'>LinkedIn</a>
<a href='#' class='btn btn-sm btn-outline-secondary'>Email</a>
</div>
</div>
</div>
</div>
<div class='col'>
<div class='card h-100 shadow-sm text-center'>
<div class='card-body d-flex flex-column'>
<img src='https://via.placeholder.com/150' class='rounded-circle mx-auto mb-3' alt='Team member' style='width: 150px; height: 150px; object-fit: cover;'>
<h5 class='card-title'>Sarah Johnson</h5>
<p class='text-muted mb-3'>Product Manager</p>
<p class='card-text flex-grow-1'>Driving product strategy and customer satisfaction through data-driven decisions and user research.</p>
<div class='d-flex justify-content-center gap-2 mt-auto'>
<a href='#' class='btn btn-sm btn-outline-primary'>LinkedIn</a>
<a href='#' class='btn btn-sm btn-outline-secondary'>Email</a>
</div>
</div>
</div>
</div>
</div>
<div class='text-center mt-5'>
<h3>Join Our Team</h3>
<p class='text-muted mb-3'>We're always looking for talented individuals to join our growing team.</p>
<a href='#' class='btn btn-primary btn-lg'>View Open Positions</a>
</div>
</div>
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(bootstrapTeam);
pdf.SaveAs("team-members.pdf");
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
Dim bootstrapTeam As String = "
<!DOCTYPE html>
<html>
<head>
<link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
</head>
<body>
<div class='container my-5'>
<h1 class='text-center mb-5'>Our Team</h1>
<div class='row row-cols-1 row-cols-md-3 g-4'>
<div class='col'>
<div class='card h-100 shadow-sm text-center'>
<div class='card-body d-flex flex-column'>
<img src='https://via.placeholder.com/150' class='rounded-circle mx-auto mb-3' alt='Team member' style='width: 150px; height: 150px; object-fit: cover;'>
<h5 class='card-title'>Jennifer Martinez</h5>
<p class='text-muted mb-3'>Chief Technology Officer</p>
<p class='card-text flex-grow-1'>Leading our technical vision and innovation strategy with over 15 years of experience in software architecture.</p>
<div class='d-flex justify-content-center gap-2 mt-auto'>
<a href='#' class='btn btn-sm btn-outline-primary'>LinkedIn</a>
<a href='#' class='btn btn-sm btn-outline-secondary'>Email</a>
</div>
</div>
</div>
</div>
<div class='col'>
<div class='card h-100 shadow-sm text-center'>
<div class='card-body d-flex flex-column'>
<img src='https://via.placeholder.com/150' class='rounded-circle mx-auto mb-3' alt='Team member' style='width: 150px; height: 150px; object-fit: cover;'>
<h5 class='card-title'>David Chen</h5>
<p class='text-muted mb-3'>Head of Engineering</p>
<p class='card-text flex-grow-1'>Managing our engineering teams and ensuring product quality through rigorous testing and code review processes.</p>
<div class='d-flex justify-content-center gap-2 mt-auto'>
<a href='#' class='btn btn-sm btn-outline-primary'>LinkedIn</a>
<a href='#' class='btn btn-sm btn-outline-secondary'>Email</a>
</div>
</div>
</div>
</div>
<div class='col'>
<div class='card h-100 shadow-sm text-center'>
<div class='card-body d-flex flex-column'>
<img src='https://via.placeholder.com/150' class='rounded-circle mx-auto mb-3' alt='Team member' style='width: 150px; height: 150px; object-fit: cover;'>
<h5 class='card-title'>Sarah Johnson</h5>
<p class='text-muted mb-3'>Product Manager</p>
<p class='card-text flex-grow-1'>Driving product strategy and customer satisfaction through data-driven decisions and user research.</p>
<div class='d-flex justify-content-center gap-2 mt-auto'>
<a href='#' class='btn btn-sm btn-outline-primary'>LinkedIn</a>
<a href='#' class='btn btn-sm btn-outline-secondary'>Email</a>
</div>
</div>
</div>
</div>
</div>
<div class='text-center mt-5'>
<h3>Join Our Team</h3>
<p class='text-muted mb-3'>We're always looking for talented individuals to join our growing team.</p>
<a href='#' class='btn btn-primary btn-lg'>View Open Positions</a>
</div>
</div>
</body>
</html>"
Dim pdf = renderer.RenderHtmlAsPdf(bootstrapTeam)
pdf.SaveAs("team-members.pdf")
輸出: 一個專業的團隊頁面,具有Bootstrap的卡片網格、彈性框對齊、響應式圖像和按鈕組件——均在PDF中準確渲染。
Spire.PDF:有限的HTML和現代框架支持
正如其文件所述,Spire.PDF的HTML到PDF引擎對現代CSS框架具有顯著的限制:
- 有限的CSS支持: 僅基礎CSS; 對CSS3功能的綜合支持有限
- 有限的彈性框支持: Bootstrap 4/5嚴重依賴於彈性框,但支持有限,影響佈局準確性
- 有限的CSS網格支持: 使用CSS網格的現代佈局系統可能無法正確渲染
- JavaScript限制: 與現代瀏覽器相比,JavaScript執行有限
- Bootstrap 3最可靠: 舊有的基於表格的Bootstrap版本比Bootstrap 4/5更可靠
- 複雜佈局可能需要變通方法: 現代響應式設計可能需要重大的調整
開發者報告的Spire.PDF HTML轉換問題:
- Bootstrap的導航欄渲染時佈局問題
- 與彈性框不對齊的卡片組件
- 在PDF輸出中忽略響應式網格斷點
- 現代CSS功能需要手動CSS重寫或後備
開發影響: 使用Bootstrap 4+或現代CSS框架的應用需面對Spire.PDF的重大挑戰。 開發團隊必須:
- 專門為PDF生成維護單獨的簡化CSS(雙重維護)
- 降級到Bootstrap 3或完全放棄框架(限制現代功能)
- 大量測試並手動修复每個組件(耗時且不穩定)
對於需要現代CSS框架支持的專案,Spire.PDF的HTML渲染限制使其不適合,除非輔以重大的額外開發努力和持續的維護負擔。
要查看Bootstrap相容性資訊的詳細資訊,請參見Bootstrap & Flexbox CSS指南。
常見的PDF任務程式碼範例如何比較?
為了演示IronPDF和Spire.PDF for .NET的功能,我們將通過程式碼範例比較其多個關鍵PDF功能的實現,給您一個這些功能如何幫助您的PDF專案的概念。
將HTML轉換為PDF
IronPDF範例:
using IronPdf;
// Disable local disk access or cross-origin requests
Installation.EnableWebSecurity = true;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from an HTML string using C#
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
pdf.SaveAs("output.pdf");
// 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");
using IronPdf;
// Disable local disk access or cross-origin requests
Installation.EnableWebSecurity = true;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from an HTML string using C#
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
pdf.SaveAs("output.pdf");
// 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
' Disable local disk access or cross-origin requests
Installation.EnableWebSecurity = True
' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()
' Create a PDF from an HTML string using C#
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
pdf.SaveAs("output.pdf")
' 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
Dim myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\site\assets\")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
IronPDF中的ChromePdfRenderer類利用完整的Chrome瀏覽器引擎來渲染HTML內容。 這意味著CSS3動畫、JavaScript執行和現代Web字體都會像在Chrome中一樣準確渲染。 RenderHtmlAsPdf()方法接受HTML字串和可選的基路徑以載入外部資產,使其在轉換簡單和複雜HTML文件時都很直接。 渲染器支持高級渲染選項,包括自定義紙張尺寸、字邊距和JavaScript延遲設置。
Spire.PDF範例:
using Spire.Pdf;
using Spire.Pdf.HtmlConverter;
using System.IO;
using System.Threading;
using System.Drawing;
namespace ConvertHtmlStringToPdfWithoutPlugin
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument object
PdfDocument doc = new PdfDocument();
// Create a PdfPageSettings object
PdfPageSettings setting = new PdfPageSettings();
// Set page size and margins through the object
setting.Size = new SizeF(1000, 1000);
setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);
// Create a PdfHtmlLayoutFormat object
PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
// Set IsWaiting property to true
htmlLayoutFormat.IsWaiting = true;
// Read HTML string from a .html file
string htmlString = File.ReadAllText(@"C:\Users\Administrator\Desktop\Document\Html\Sample.html");
// Load HTML from HTML string using LoadFromHTML method
Thread thread = new Thread(() =>
{ doc.LoadFromHTML(htmlString, true, setting, htmlLayoutFormat); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
// Save to a PDF file
doc.SaveToFile("HtmlStringToPdf.pdf");
}
}
}
using Spire.Pdf;
using Spire.Pdf.HtmlConverter;
using System.IO;
using System.Threading;
using System.Drawing;
namespace ConvertHtmlStringToPdfWithoutPlugin
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument object
PdfDocument doc = new PdfDocument();
// Create a PdfPageSettings object
PdfPageSettings setting = new PdfPageSettings();
// Set page size and margins through the object
setting.Size = new SizeF(1000, 1000);
setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);
// Create a PdfHtmlLayoutFormat object
PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
// Set IsWaiting property to true
htmlLayoutFormat.IsWaiting = true;
// Read HTML string from a .html file
string htmlString = File.ReadAllText(@"C:\Users\Administrator\Desktop\Document\Html\Sample.html");
// Load HTML from HTML string using LoadFromHTML method
Thread thread = new Thread(() =>
{ doc.LoadFromHTML(htmlString, true, setting, htmlLayoutFormat); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
// Save to a PDF file
doc.SaveToFile("HtmlStringToPdf.pdf");
}
}
}
Imports Spire.Pdf
Imports Spire.Pdf.HtmlConverter
Imports System.IO
Imports System.Threading
Imports System.Drawing
Namespace ConvertHtmlStringToPdfWithoutPlugin
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Create a PdfDocument object
Dim doc As New PdfDocument()
' Create a PdfPageSettings object
Dim setting As New PdfPageSettings()
' Set page size and margins through the object
setting.Size = New SizeF(1000, 1000)
setting.Margins = New Spire.Pdf.Graphics.PdfMargins(20)
' Create a PdfHtmlLayoutFormat object
Dim htmlLayoutFormat As New PdfHtmlLayoutFormat()
' Set IsWaiting property to true
htmlLayoutFormat.IsWaiting = True
' Read HTML string from a .html file
Dim htmlString As String = File.ReadAllText("C:\Users\Administrator\Desktop\Document\Html\Sample.html")
' Load HTML from HTML string using LoadFromHTML method
Dim thread As New Thread(Sub()
doc.LoadFromHTML(htmlString, True, setting, htmlLayoutFormat)
End Sub)
thread.SetApartmentState(ApartmentState.STA)
thread.Start()
thread.Join()
' Save to a PDF file
doc.SaveToFile("HtmlStringToPdf.pdf")
End Sub
End Class
End Namespace
Spire.PDF的HTML到PDF轉換需要建立多個物件,包括PdfHtmlLayoutFormat。 轉換必須在單執行緒公寓(STA)執行緒中執行,增加了實現的複雜性。 使用者報告說"Spire生成的PDF文件只是一個圖像。 一些css甚至不正確,例如忽略粗體字樣",表示CSS渲染保真度的限制。
IronPDF利用Chrome的渲染引擎進行高保真HTML到PDF轉換,通過其對現代Web標準的支持,確保網頁內容的準確表示。 Spire.PDF也提供強大的HTML到PDF轉換,但可能無法匹配IronPDF的渲染精度,並採用更長且手動的方法。
如何加密PDF文件?
IronPDF範例:
using IronPdf;
using System;
// Open an Encrypted File, alternatively create a new PDF from HTML
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");
// Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = DateTime.Now;
// Edit file security settings
pdf.SecuritySettings.RemovePasswordsAndEncryption();
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key");
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
// Change or set the document encryption password
pdf.Password = "my-password";
pdf.SaveAs("secured.pdf");
using IronPdf;
using System;
// Open an Encrypted File, alternatively create a new PDF from HTML
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");
// Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = DateTime.Now;
// Edit file security settings
pdf.SecuritySettings.RemovePasswordsAndEncryption();
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key");
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
// Change or set the document encryption password
pdf.Password = "my-password";
pdf.SaveAs("secured.pdf");
Imports IronPdf
Imports System
' Open an Encrypted File, alternatively create a new PDF from HTML
Private pdf = PdfDocument.FromFile("encrypted.pdf", "password")
' Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = DateTime.Now
' Edit file security settings
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key")
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights
' Change or set the document encryption password
pdf.Password = "my-password"
pdf.SaveAs("secured.pdf")
IronPDF的SecuritySettings類提供了廣泛的API以管理PDF安全性。 您可以控制布林屬性中的個別權限,設置不同級別的列印權限,並將密碼的管理與其他安全設置分開。 API設計遵循.NET的慣例,具有強型別的枚舉如PdfPrintSecurity。 在文件中了解更多關於PDF許可和密碼的資訊。
Spire.PDF範例:
using Spire.Pdf;
using Spire.Pdf.Security;
// Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
// Load a sample PDF file
pdf.LoadFromFile(@"E:\Files\sample.pdf");
// Encrypt the PDF file with a password
pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit);
// Save the result file
pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF);
using Spire.Pdf;
using Spire.Pdf.Security;
// Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
// Load a sample PDF file
pdf.LoadFromFile(@"E:\Files\sample.pdf");
// Encrypt the PDF file with a password
pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit);
// Save the result file
pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF);
Imports Spire.Pdf
Imports Spire.Pdf.Security
' Create a PdfDocument object
Private pdf As New PdfDocument()
' Load a sample PDF file
pdf.LoadFromFile("E:\Files\sample.pdf")
' Encrypt the PDF file with a password
pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print Or PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit)
' Save the result file
pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF)
Spire.PDF的加密方法使用Security.Encrypt()方法和權限的按位標誌。 雖然更加緊湊,但這種方法需要理解按位操作,並提供比IronPDF的個別許可屬性更少的細粒度控制。
兩者均提供易用的方法來加密PDF文件並設置加密PDF文件的可讀性。 IronPDF提供了一種簡單的方法,同時仍然允許您完全控制PDF的安全設置。 Spire.PDF採用稍微短的過程但仍然包括設置許可的其他選項。
哪些方法可用於編輯PDF內容?
IronPDF範例:
using IronPdf;
// Load the PDF document
PdfDocument pdf = PdfDocument.FromFile("novel.pdf");
// Redact 'are' phrase from all pages
pdf.RedactTextOnAllPages("are");
// Save the redacted document
pdf.SaveAs("redacted.pdf");
using IronPdf;
// Load the PDF document
PdfDocument pdf = PdfDocument.FromFile("novel.pdf");
// Redact 'are' phrase from all pages
pdf.RedactTextOnAllPages("are");
// Save the redacted document
pdf.SaveAs("redacted.pdf");
Imports IronPdf
' Load the PDF document
Private pdf As PdfDocument = PdfDocument.FromFile("novel.pdf")
' Redact 'are' phrase from all pages
pdf.RedactTextOnAllPages("are")
' Save the redacted document
pdf.SaveAs("redacted.pdf")
IronPDF提供了專門編輯API,進行真正的內容移除,而不僅僅是視覺遮蔽。 RedactTextOnAllPages()方法搜索並永久刪除指定文字,以確保符合資料保護規定。 其他方法允許在特定頁面或區域上進行編輯。
Spire.PDF編輯範例通過矩形覆蓋:
儘管Spire.PDF沒有專門的編輯工具,內容仍然可以通過手動過程編輯,如下所示:
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
// Specify the input PDF file path
string inputPdfFilePath = "path/to/your/input.pdf";
// Specify the output redacted PDF file path
string outputPdfFilePath = "path/to/your/redacted_output.pdf";
// Create a new PdfDocument object
PdfDocument pdfDocument = new PdfDocument();
// Load the existing PDF document
pdfDocument.LoadFromFile(inputPdfFilePath);
// Redact content on each page
foreach (PdfPageBase page in pdfDocument.Pages)
{
// Define the area to redact (e.g., coordinates and size of the rectangle)
RectangleF redactArea = new RectangleF(100, 100, 200, 50); // Example coordinates and size
// Apply redaction
page.Canvas.DrawRectangle(new PdfSolidBrush(Color.Black), redactArea);
}
// Save the redacted PDF document
pdfDocument.SaveToFile(outputPdfFilePath);
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
// Specify the input PDF file path
string inputPdfFilePath = "path/to/your/input.pdf";
// Specify the output redacted PDF file path
string outputPdfFilePath = "path/to/your/redacted_output.pdf";
// Create a new PdfDocument object
PdfDocument pdfDocument = new PdfDocument();
// Load the existing PDF document
pdfDocument.LoadFromFile(inputPdfFilePath);
// Redact content on each page
foreach (PdfPageBase page in pdfDocument.Pages)
{
// Define the area to redact (e.g., coordinates and size of the rectangle)
RectangleF redactArea = new RectangleF(100, 100, 200, 50); // Example coordinates and size
// Apply redaction
page.Canvas.DrawRectangle(new PdfSolidBrush(Color.Black), redactArea);
}
// Save the redacted PDF document
pdfDocument.SaveToFile(outputPdfFilePath);
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing
' Specify the input PDF file path
Private inputPdfFilePath As String = "path/to/your/input.pdf"
' Specify the output redacted PDF file path
Private outputPdfFilePath As String = "path/to/your/redacted_output.pdf"
' Create a new PdfDocument object
Private pdfDocument As New PdfDocument()
' Load the existing PDF document
pdfDocument.LoadFromFile(inputPdfFilePath)
' Redact content on each page
For Each page As PdfPageBase In pdfDocument.Pages
' Define the area to redact (e.g., coordinates and size of the rectangle)
Dim redactArea As New RectangleF(100, 100, 200, 50) ' Example coordinates and size
' Apply redaction
page.Canvas.DrawRectangle(New PdfSolidBrush(Color.Black), redactArea)
Next page
' Save the redacted PDF document
pdfDocument.SaveToFile(outputPdfFilePath)
這種手動方法需要精確計算每個編輯區域的坐標,並且僅提供視覺遮罩,而不是實際內容刪除。 基礎文字可能仍然可以通過PDF編輯工具提取。
IronPDF用其強大而簡單的編輯工具簡化了編輯。 由於缺乏內建的編輯工具,Spire.PDF需要更多的手動操作來進行編輯,導致可能較低效的工作流。
如何對PDF文件進行簽名?
IronPDF範例:
using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;
// Instantiate the renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>foo</h1>");
// Create X509Certificate2 object with X509KeyStorageFlags set to Exportable
X509Certificate2 cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);
// Create PdfSignature with certificate
var sig = new PdfSignature(cert);
// Sign PDF document
pdf.Sign(sig);
pdf.SaveAs("signed.pdf");
using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;
// Instantiate the renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>foo</h1>");
// Create X509Certificate2 object with X509KeyStorageFlags set to Exportable
X509Certificate2 cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);
// Create PdfSignature with certificate
var sig = new PdfSignature(cert);
// Sign PDF document
pdf.Sign(sig);
pdf.SaveAs("signed.pdf");
Imports IronPdf
Imports IronPdf.Signing
Imports System.Security.Cryptography.X509Certificates
' Instantiate the renderer
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>foo</h1>")
' Create X509Certificate2 object with X509KeyStorageFlags set to Exportable
Private cert As New X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable)
' Create PdfSignature with certificate
Private sig = New PdfSignature(cert)
' Sign PDF document
pdf.Sign(sig)
pdf.SaveAs("signed.pdf")
IronPDF的數位簽名實現遵循.NET證書處理模式。 PdfSignature類接受標準X509Certificate2物件,並在內部處理PDF簽名的複雜性。 您也可以新增視覺簽名顯現並配置簽名字段。
Spire.PDF範例:
using Spire.Pdf;
using Spire.Pdf.Security;
using System.Drawing;
// Create a PdfDocument object
PdfDocument doc = new PdfDocument();
// Load a sample PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
// Load the certificate
PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");
// Create a PdfSignature object and specify its position and size
PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
RectangleF rectangleF = new RectangleF(doc.Pages[0].ActualSize.Width - 260 - 54 , 200, 260, 110);
signature.Bounds = rectangleF;
signature.Certificated = true;
// Set the graphics mode to ImageAndSignDetail
signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;
// Set various details about the signature
signature.NameLabel = "Signer:";
signature.Name = "Gary";
signature.ContactInfoLabel = "Phone:";
signature.ContactInfo = "0123456";
signature.DateLabel = "Date:";
signature.Date = DateTime.Now;
signature.LocationInfoLabel = "Location:";
signature.LocationInfo = "USA";
signature.ReasonLabel = "Reason:";
signature.Reason = "I am the author";
signature.DistinguishedNameLabel = "DN:";
signature.DistinguishedName = signature.Certificate.IssuerName.Name;
// Set the signature image source
signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\handwrittingSignature.png");
// Set the signature font
signature.SignDetailsFont = new PdfTrueTypeFont(new Font("Arial Unicode MS", 12f, FontStyle.Regular));
// Set the document permission to forbid changes but allow form fill
signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;
// Save to file
doc.SaveToFile("VisiableSignature.pdf");
using Spire.Pdf;
using Spire.Pdf.Security;
using System.Drawing;
// Create a PdfDocument object
PdfDocument doc = new PdfDocument();
// Load a sample PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
// Load the certificate
PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");
// Create a PdfSignature object and specify its position and size
PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
RectangleF rectangleF = new RectangleF(doc.Pages[0].ActualSize.Width - 260 - 54 , 200, 260, 110);
signature.Bounds = rectangleF;
signature.Certificated = true;
// Set the graphics mode to ImageAndSignDetail
signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;
// Set various details about the signature
signature.NameLabel = "Signer:";
signature.Name = "Gary";
signature.ContactInfoLabel = "Phone:";
signature.ContactInfo = "0123456";
signature.DateLabel = "Date:";
signature.Date = DateTime.Now;
signature.LocationInfoLabel = "Location:";
signature.LocationInfo = "USA";
signature.ReasonLabel = "Reason:";
signature.Reason = "I am the author";
signature.DistinguishedNameLabel = "DN:";
signature.DistinguishedName = signature.Certificate.IssuerName.Name;
// Set the signature image source
signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\handwrittingSignature.png");
// Set the signature font
signature.SignDetailsFont = new PdfTrueTypeFont(new Font("Arial Unicode MS", 12f, FontStyle.Regular));
// Set the document permission to forbid changes but allow form fill
signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;
// Save to file
doc.SaveToFile("VisiableSignature.pdf");
Imports Spire.Pdf
Imports Spire.Pdf.Security
Imports System.Drawing
' Create a PdfDocument object
Private doc As New PdfDocument()
' Load a sample PDF file
doc.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf")
' Load the certificate
Dim cert As New PdfCertificate("C:\Users\Administrator\Desktop\MyCertificate.pfx", "e-iceblue")
' Create a PdfSignature object and specify its position and size
Dim signature As New PdfSignature(doc, doc.Pages(doc.Pages.Count - 1), cert, "MySignature")
Dim rectangleF As New RectangleF(doc.Pages(0).ActualSize.Width - 260 - 54, 200, 260, 110)
signature.Bounds = rectangleF
signature.Certificated = True
' Set the graphics mode to ImageAndSignDetail
signature.GraphicsMode = GraphicMode.SignImageAndSignDetail
' Set various details about the signature
signature.NameLabel = "Signer:"
signature.Name = "Gary"
signature.ContactInfoLabel = "Phone:"
signature.ContactInfo = "0123456"
signature.DateLabel = "Date:"
signature.Date = DateTime.Now
signature.LocationInfoLabel = "Location:"
signature.LocationInfo = "USA"
signature.ReasonLabel = "Reason:"
signature.Reason = "I am the author"
signature.DistinguishedNameLabel = "DN:"
signature.DistinguishedName = signature.Certificate.IssuerName.Name
' Set the signature image source
signature.SignImageSource = PdfImage.FromFile("C:\Users\Administrator\Desktop\handwrittingSignature.png")
' Set the signature font
signature.SignDetailsFont = New PdfTrueTypeFont(New Font("Arial Unicode MS", 12F, FontStyle.Regular))
' Set the document permission to forbid changes but allow form fill
signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges Or PdfCertificationFlags.AllowFormFill
' Save to file
doc.SaveToFile("VisiableSignature.pdf")
Spire.PDF提供對簽名顯現的全面控制,但需要更多程式碼。 您必須手動設置每個標籤,精確定位簽名位置,並單獨配置視覺元素。
從驗證PDF文件到簡單簽署新專案,數位簽章可以用於各種設定。 IronPDF在新增數位簽名上提供了簡單的方法,允許自動化簽名過程。 Spire.PDF也支持PDF的數位簽名; 然而,這個過程可能更需要手動,並需要更多努力來實現。
有哪些方法可以為PDF加水印?
IronPDF範例:
using IronPdf;
// Stamps a Watermark onto a new or existing PDF
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs(@"C:\Path\To\Watermarked.pdf");
using IronPdf;
// Stamps a Watermark onto a new or existing PDF
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs(@"C:\Path\To\Watermarked.pdf");
Imports IronPdf
' Stamps a Watermark onto a new or existing PDF
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center)
pdf.SaveAs("C:\Path\To\Watermarked.pdf")
IronPDF的水印功能接受HTML內容,允許您使用CSS進行樣式設計。 ApplyWatermark()方法提供旋轉角度和對齊的參數,使得將水印精確定位變得容易。 了解更多關於自定義水印和高級樣式選項。
Spire.PDF範例:
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
// Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
// Load a sample PDF document
pdf.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");
// Create a PdfTrueTypeFont object
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 50f), true);
// Set the watermark text
string text = "CONFIDENTIAL";
// Measure the text size
SizeF textSize = font.MeasureString(text);
// Calculate the values of two offset variables,
// which will be used to calculate the translation amount of the coordinate system
float offset1 = (float)(textSize.Width * System.Math.Sqrt(2) / 4);
float offset2 = (float)(textSize.Height * System.Math.Sqrt(2) / 4);
// Traverse all the pages in the document
foreach (PdfPageBase page in pdf.Pages)
{
// Set the page transparency
page.Canvas.SetTransparency(0.8f);
// Translate the coordinate system by specified coordinates
page.Canvas.TranslateTransform(page.Canvas.Size.Width / 2 - offset1 - offset2, page.Canvas.Size.Height / 2 + offset1 - offset2);
// Rotate the coordinate system 45 degrees counterclockwise
page.Canvas.RotateTransform(-45);
// Draw watermark text on the page
page.Canvas.DrawString(text, font, PdfBrushes.DarkGray, 0, 0);
}
// Save the changes to another file
pdf.SaveToFile("TextWatermark.pdf");
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
// Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
// Load a sample PDF document
pdf.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");
// Create a PdfTrueTypeFont object
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 50f), true);
// Set the watermark text
string text = "CONFIDENTIAL";
// Measure the text size
SizeF textSize = font.MeasureString(text);
// Calculate the values of two offset variables,
// which will be used to calculate the translation amount of the coordinate system
float offset1 = (float)(textSize.Width * System.Math.Sqrt(2) / 4);
float offset2 = (float)(textSize.Height * System.Math.Sqrt(2) / 4);
// Traverse all the pages in the document
foreach (PdfPageBase page in pdf.Pages)
{
// Set the page transparency
page.Canvas.SetTransparency(0.8f);
// Translate the coordinate system by specified coordinates
page.Canvas.TranslateTransform(page.Canvas.Size.Width / 2 - offset1 - offset2, page.Canvas.Size.Height / 2 + offset1 - offset2);
// Rotate the coordinate system 45 degrees counterclockwise
page.Canvas.RotateTransform(-45);
// Draw watermark text on the page
page.Canvas.DrawString(text, font, PdfBrushes.DarkGray, 0, 0);
}
// Save the changes to another file
pdf.SaveToFile("TextWatermark.pdf");
Imports System
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing
' Create a PdfDocument object
Private pdf As New PdfDocument()
' Load a sample PDF document
pdf.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf")
' Create a PdfTrueTypeFont object
Dim font As New PdfTrueTypeFont(New Font("Arial", 50F), True)
' Set the watermark text
Dim text As String = "CONFIDENTIAL"
' Measure the text size
Dim textSize As SizeF = font.MeasureString(text)
' Calculate the values of two offset variables,
' which will be used to calculate the translation amount of the coordinate system
Dim offset1 As Single = CSng(textSize.Width * Math.Sqrt(2) / 4)
Dim offset2 As Single = CSng(textSize.Height * Math.Sqrt(2) / 4)
' Traverse all the pages in the document
For Each page As PdfPageBase In pdf.Pages
' Set the page transparency
page.Canvas.SetTransparency(0.8F)
' Translate the coordinate system by specified coordinates
page.Canvas.TranslateTransform(page.Canvas.Size.Width \ 2 - offset1 - offset2, page.Canvas.Size.Height \ 2 + offset1 - offset2)
' Rotate the coordinate system 45 degrees counterclockwise
page.Canvas.RotateTransform(-45)
' Draw watermark text on the page
page.Canvas.DrawString(text, font, PdfBrushes.DarkGray, 0, 0)
Next page
' Save the changes to another file
pdf.SaveToFile("TextWatermark.pdf")
Spire.PDF的水印需要通過坐標系統變換手動計算定位和旋轉。 儘管提供了精細的控制,它需要對圖形編程概念的理解。
IronPDF提供了一種簡單的方法來新增文字水印,同時完全控制水印的位置和設計。 如果您具有HTML和CSS經驗,使用IronPDF會使這一過程更簡單。 Spire.PDF的方法較長,需更手動的過程,但仍提供強大的水印工具,並可完全控制設計和位置。
如何在PDF上加蓋圖像和文字?
IronPDF範例:
using IronPdf;
using IronPdf.Editing;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>");
// Create text stamper
TextStamper textStamper = new TextStamper()
{
Text = "Text Stamper!",
FontFamily = "Bungee Spice",
UseGoogleFont = true,
FontSize = 30,
IsBold = true,
IsItalic = true,
VerticalAlignment = VerticalAlignment.Top,
};
// Stamp the text stamper
pdf.ApplyStamp(textStamper);
pdf.SaveAs("stampText.pdf");
// Create image stamper
ImageStamper imageStamper = new ImageStamper(new Uri("https://ironpdf.com/img/svgs/iron-pdf-logo.svg"))
{
VerticalAlignment = VerticalAlignment.Top,
};
// Stamp the image stamper
pdf.ApplyStamp(imageStamper, 0);
pdf.SaveAs("stampImage.pdf");
using IronPdf;
using IronPdf.Editing;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>");
// Create text stamper
TextStamper textStamper = new TextStamper()
{
Text = "Text Stamper!",
FontFamily = "Bungee Spice",
UseGoogleFont = true,
FontSize = 30,
IsBold = true,
IsItalic = true,
VerticalAlignment = VerticalAlignment.Top,
};
// Stamp the text stamper
pdf.ApplyStamp(textStamper);
pdf.SaveAs("stampText.pdf");
// Create image stamper
ImageStamper imageStamper = new ImageStamper(new Uri("https://ironpdf.com/img/svgs/iron-pdf-logo.svg"))
{
VerticalAlignment = VerticalAlignment.Top,
};
// Stamp the image stamper
pdf.ApplyStamp(imageStamper, 0);
pdf.SaveAs("stampImage.pdf");
Imports IronPdf
Imports IronPdf.Editing
' Instantiate Renderer
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>")
' Create text stamper
Private textStamper As New TextStamper() With {
.Text = "Text Stamper!",
.FontFamily = "Bungee Spice",
.UseGoogleFont = True,
.FontSize = 30,
.IsBold = True,
.IsItalic = True,
.VerticalAlignment = VerticalAlignment.Top
}
' Stamp the text stamper
pdf.ApplyStamp(textStamper)
pdf.SaveAs("stampText.pdf")
' Create image stamper
Dim imageStamper As New ImageStamper(New Uri("https://ironpdf.com/img/svgs/iron-pdf-logo.svg")) With {.VerticalAlignment = VerticalAlignment.Top}
' Stamp the image stamper
pdf.ApplyStamp(imageStamper, 0)
pdf.SaveAs("stampImage.pdf")
IronPDF的加蓋API使用專門的類處理不同的加蓋型別。UseGoogleFont屬性能載入來自URL或本地文件的圖像。 兩個加蓋工具共享常見的對齊屬性,以確保一致的位置。 請瀏覽更多加蓋選項,包括HTML加蓋器和條碼整合。
Spire.PDF(文字加蓋範例):
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
// Assumes a PdfDocument is already loaded as `doc` object
PdfPageBase page = doc.Pages[0];
PdfGraphicsState state = page.Canvas.Save();
// Define font and brushes for different effects
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 18f);
PdfSolidBrush brush1 = new PdfSolidBrush(Color.DeepSkyBlue);
PdfSolidBrush brush2 = new PdfSolidBrush(Color.CadetBlue);
// Apply transformations and draw strings with shadow and effect
page.Canvas.TranslateTransform(20, 200);
page.Canvas.ScaleTransform(1f, 0.6f);
page.Canvas.SkewTransform(-10, 0);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush1, 0, 0);
page.Canvas.SkewTransform(10, 0);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, 0);
page.Canvas.ScaleTransform(1f, -1f);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, -2 * 18);
// Restore graphics to previous state
page.Canvas.Restore(state);
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
// Assumes a PdfDocument is already loaded as `doc` object
PdfPageBase page = doc.Pages[0];
PdfGraphicsState state = page.Canvas.Save();
// Define font and brushes for different effects
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 18f);
PdfSolidBrush brush1 = new PdfSolidBrush(Color.DeepSkyBlue);
PdfSolidBrush brush2 = new PdfSolidBrush(Color.CadetBlue);
// Apply transformations and draw strings with shadow and effect
page.Canvas.TranslateTransform(20, 200);
page.Canvas.ScaleTransform(1f, 0.6f);
page.Canvas.SkewTransform(-10, 0);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush1, 0, 0);
page.Canvas.SkewTransform(10, 0);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, 0);
page.Canvas.ScaleTransform(1f, -1f);
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, -2 * 18);
// Restore graphics to previous state
page.Canvas.Restore(state);
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing
' Assumes a PdfDocument is already loaded as `doc` object
Private page As PdfPageBase = doc.Pages(0)
Private state As PdfGraphicsState = page.Canvas.Save()
' Define font and brushes for different effects
Private font As New PdfFont(PdfFontFamily.Helvetica, 18F)
Private brush1 As New PdfSolidBrush(Color.DeepSkyBlue)
Private brush2 As New PdfSolidBrush(Color.CadetBlue)
' Apply transformations and draw strings with shadow and effect
page.Canvas.TranslateTransform(20, 200)
page.Canvas.ScaleTransform(1F, 0.6F)
page.Canvas.SkewTransform(-10, 0)
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush1, 0, 0)
page.Canvas.SkewTransform(10, 0)
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, 0)
page.Canvas.ScaleTransform(1F, -1F)
page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, -2 * 18)
' Restore graphics to previous state
page.Canvas.Restore(state)
Spire.PDF需要直接畫布操控,對每個效果進行手動變換。 建立複雜的加蓋涉及到了解圖形狀態管理和坐標變換。
IronPDF的文字和圖像加蓋工具是強大的、易於使用的加蓋工具,在應用加蓋內容時它遵循類似於HTML和CSS的方法。 雖然Spire.PDF也提供一個基本的文字加蓋工具,但將加蓋文字應用到PDF文件需要更多努力。
哪個庫處理DOCX到PDF轉換更好?
IronPDF範例:
using IronPdf;
// Instantiate Renderer
DocxToPdfRenderer renderer = new DocxToPdfRenderer();
// Render from DOCX file
PdfDocument pdf = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx");
// Save the PDF
pdf.SaveAs("pdfFromDocx.pdf");
using IronPdf;
// Instantiate Renderer
DocxToPdfRenderer renderer = new DocxToPdfRenderer();
// Render from DOCX file
PdfDocument pdf = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx");
// Save the PDF
pdf.SaveAs("pdfFromDocx.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer As New DocxToPdfRenderer()
' Render from DOCX file
Private pdf As PdfDocument = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx")
' Save the PDF
pdf.SaveAs("pdfFromDocx.pdf")
IronPDF包括一個專用的DocxToPdfRenderer類,負責對DOCX的本機轉換。 API與IronPDF中的其他渲染類一致,基本轉換只需要兩行程式碼。 通過渲染器的屬性可以使用高級選項進行頁面設置和格式調整。 了解更多關於DOCX到PDF轉換的功能。
使用Spire.Doc進行Spire.PDF的DOCX到PDF轉換:
Spire.PDF本身無法將DOCX轉換為PDF; 然而,可以使用Spire.Doc庫來處理此轉換,然後您可以使用Spire.PDF處理生成的PDF。
using Spire.Doc;
// Create a Document object
Document doc = new Document();
// Load a Word document
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");
// Save the document to PDF
doc.SaveToFile("ToPDF.pdf", FileFormat.PDF);
// Dispose of resources
doc.Dispose();
using Spire.Doc;
// Create a Document object
Document doc = new Document();
// Load a Word document
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");
// Save the document to PDF
doc.SaveToFile("ToPDF.pdf", FileFormat.PDF);
// Dispose of resources
doc.Dispose();
Imports Spire.Doc
' Create a Document object
Private doc As New Document()
' Load a Word document
doc.LoadFromFile("C:\Users\Administrator\Desktop\Sample.docx")
' Save the document to PDF
doc.SaveToFile("ToPDF.pdf", FileFormat.PDF)
' Dispose of resources
doc.Dispose()
這種方法需要購買和管理一個額外的庫(Spire.Doc),增加了成本和複雜性。
IronPDF提供對直接DOCX到PDF轉換的內建支持,這意味著您不需要額外的庫來處理這一任務,從而節省時間。 另一方面,Spire.PDF無法直接處理DOCX到PDF轉換,需Spire.Doc庫來將DOCX文件轉換為PDF。
性能指標揭示了什麼?
根據測試和使用者反饋,以下是兩個庫在實際使用中的比較:
渲染性能
對於基本佈局,Spire.PDF針對靜態表或基本樣式文字等簡單內容進行了優化,使其在這些用例中快速且高效。 然而,當處理包含現代CSS3功能、JavaScript或響應式佈局的複雜HTML時,IronPDF的基於Chrome的引擎在稍高的渲染時間下提供更準確的結果。
記憶體使用
由於其更簡單的渲染引擎,Spire.PDF通常會使用比IronPDF更少的記憶體。但這是以渲染保真度和功能支持的代價。 對於記憶體至關重要且HTML複雜性最低的應用,Spire.PDF可能更具優勢。
執行緒與異步支持
IronPDF提供了原生async/await支持,具有RenderHtmlAsPdfAsync()等方法,使其適合現代.NET應用程式。 Spire.PDF需要通過STA執行緒進行手動執行緒管理,增加了多執行緒應用程式的複雜性。
價格和授權模式如何比較?
IronPDF定價和授權
IronPDF提供多個級別和附加功能來購買許可。 開發者還可以購買Iron Suite,可以以兩個價格存取Iron Software的所有產品。 如果您還未準備好購買許可,IronPDF提供一個持續30天的免費試用授權。
價格:
- 永久授權: 提供多種永久授權,根據團隊規模、項目需求和位置的數量而有所不同。 每一種授權型別都包含電子郵件支援。
- Lite License: 這一授權費用$999,支持一名開發者、一個地點和一個項目。
- Plus License: 支持三名開發者、三個地點和三個項目,這是從lite授權升級的下一步,費用$1,499。 Plus授權除了基本的電子郵件支援外,還提供聊天支援和電話支援。
- Professional License: 這一授權適合較大的團隊,支持十名開發者、十個地點和十個項目,費用$2,999。 它提供與前幾個等級相同的聯繫支援渠道,但還提供螢幕分享支援。
- 免版稅再分發: IronPDF的授權還提供了額外$2,999的免版稅再分發範圍
- 不中斷的產品支持: IronPDF提供存取持續的產品更新、安全功能升級和來自工程團隊的支持,如果選擇每年$999/年或一次性購買$1,999,提供5年覆蓋。
- Iron Suite: 用$2,998,您可以存取包括IronPDF,IronOCR,IronWord,IronXL,IronBarcode,IronQR,IronZIP,IronPrint和IronWebScraper在內的所有Iron Software產品。
IronPDF提供靈活的許可選擇,包含永久許可和綜合支持
Spire.PDF定價和許可
Spire.PDF根據您的需求提供多種許可。
- 免費版本: Spire.PDF提供一個免費版本,限制為10個PDF頁面; 超出此限制,您需要購買付費許可。
- 開發者訂閱: 價格為$999/年,這一選項適合需要構建PDF相關功能但不需要OEM分發權限的開 發者。
- 開發者OEM訂閱: 價格為$2,999/年,包括免費升級、優先支持,以及能將應用分發給最終使用者的能力。
- 站點企業訂閱: 價格為$4,599/年,這個許可階層支持多個地點的多位開發者,並提供更新和 在線技術資源。
- 站點OEM訂閱: 價格為$13,088/年,專為需要將應用部署到多個地點的大型企業設計。
哪個庫提供更好的文件和支持?
IronPDF
IronPDF在提供豐富的文件和支持方面表現出色:
- 全面的文件: 覆蓋所有功能的豐富且易於使用文件。
- 24/5支持: 可用的工程師支持。
- 影片教程: 在YouTube上提供逐步影片指南。
- 社區論壇: 進取的社區以獲得額外支持。
- 定期更新: 每月產品更新,以確保最新功能和安全補丁。
- PDF API參考: 提供API參考文件,以便您充分享受我們工具所提供的功能。
有關更多資訊,請查看IronPDF的豐富文件,並存取Iron Software YouTube頻道。
Spire.PDF for .NET文件和支持
- 論壇: Spire.PDF擁有一個使用者社區論壇,使用者可以在這裡互動,分享使用技巧、用途和遇到的問題。
- 程式碼範例: Spire.PDF在其網站上提供程式碼範例,展示如何在多種用例中使用該產品。
- 電子報: Spire.PDF提供開發者的電子報,以便發布更新通知和其他重要資訊。
- 支持: 主要通過論壇提供支持,根據許可版本,可選支付電子郵件/電話支持。
常見開發者體驗和反饋是什麼?
根據社區反饋和實際使用:
IronPDF反馈
開發者不斷稱讚IronPDF提供了"對原始HTML頁面的更全面和精確的表現"。 其处理複雜CSS3佈局、JavaScript-heavy頁面和現代Web框架的能力,使它成為需要高保真PDF生成的應用的首選。
常見的積極點包括:
- 直觀的API設計,可減少開發時間
- 出色的渲染質量,匹配瀏覽器輸出
- 搭配實用範例的豐富文件
- 反應迅速的技術支持
Spire.PDF反馈
社區反映"Spire生成的PDF文件只是影像。 有些CSS甚至不正確,比如忽略粗體字。 此外,Spire.PDF預設的HTML轉換路徑中的JavaScript支持有限,開發者報告稱動態內容的執行不完整。
常見的關注點包括:
- CSS3和現代Web標準的有限支持
- 缺乏JavaScript执行能力
- HTML轉換的複雜執行緒要求
- 某些功能的額外庫需求
何時應選擇每個庫?
選擇IronPDF當:
- 您的HTML包含現代CSS3、JavaScript或響應式設計
- 您需要諸如瀏覽器輸出的像素完美渲染
- 需要跨平台部署(Linux、macOS、Docker)
- 您想要的许可包括全面支持
- 您需要內建功能,例如不需要額外庫的DOCX轉換
- 您的團隊重視快速開發和最少的程式碼
可選擇Spire.PDF的情況:
- 您的PDF僅包含簡單樣式的基本HTML
- 記憶體使用是一個關鍵限制
- 主要在Windows环境中工作
- 您的HTML不需要JavaScript执行
- 您已經在您的軟體棧中使用了其他Spire產品
總結
總之,IronPDF和Spire.PDF for .NET都是處理.NET應用中的PDF文件的強大工具。 IronPDF在使用方便性、跨平臺相容性和對現代Web標準的支持方面表現卓越,使其成爲想提升PDF文件處理能力的使用者的首選。 Spire.PDF提供了全面的功能集,但可能需要更多的努力去處理複雜任務,並缺乏現代Web應用程式所需的渲染精準度。
對於需要準確HTML到PDF轉換或需要可靠的跨平臺支持的使用現代Web技術的開發者來說,IronPDF提供了更完整的解決方案。 其基於Chrome的渲染引擎、直觀的API和全面的支持使其特別適合企業應用程式和複雜文件生成場景。
您可以試用30天的免費試用以查看他們的可用功能。
常見問題
如何在C#中將HTML轉換為PDF?
您可以使用IronPDF的RenderHtmlAsPdf方法將HTML字串轉換成PDF。也可以使用RenderHtmlFileAsPdf將HTML文件轉換為PDF。
IronPDF是否支援在HTML到PDF轉換過程中的JavaScript執行?
是的,IronPDF支持完整的JavaScript執行,使其成為將動態內容或依賴JavaScript的佈局轉換為PDF的理想選擇。
IronPDF支持哪些平台的PDF轉換?
IronPDF在多個平台上提供了原生支持,包括Windows、Linux、macOS、Docker,以及雲服務如Azure和AWS。
IronPDF的記憶體使用量如何與Spire.PDF相比?
IronPDF使用更多的記憶體,通常在150-200MB之間,相比Spire.PDF的80-120MB。但它提供了更好的渲染品質並支持現代async/await模式。
IronPDF能直接將DOCX文件轉換為PDF嗎?
是的,IronPDF通過其DocxToPdfRenderer類包含內建的DOCX到PDF轉換功能,無需額外的程式庫。
IronPDF有哪些授權選項?
IronPDF提供永久授權,單個開發者起價為$749,包含所有功能和支持。它還提供包含10個產品的Iron Suite套件,價格為$1,498。
IronPDF提供什麼樣的支持?
IronPDF提供24/5工程支持,通過電子郵件、聊天、電話和螢幕分享,確保全面協助。
我如何能保證使用IronPDF的PDF安全性和加密?
IronPDF通過其SecuritySettings類支持AES-256加密和密碼保護,允許對PDF權限進行細緻控制。
IronPDF適合渲染使用現代CSS的複雜網頁嗎?
是的,IronPDF利用完整的Chrome渲染引擎,它支援CSS3、flexbox、grid佈局、網頁字體和JavaScript,使其非常適合處理複雜網頁。
IronPDF的免費版本有哪些限制?
IronPDF提供一個完全功能的30天免費試用,無頁面限制,提供充足的機會來測試其所有功能,然後再決定是否購買。
IronPDF如何確保高品質的HTML渲染?
IronPDF提供像素級的渲染,與Chrome瀏覽器的輸出匹配,確保高保真度和準確表示原始HTML內容。



