
如何在 C# 中設置自定義邊距
從Foxit PDF SDK遷移到IronPDF簡化了您的.NET PDF生成工作流程,通過用現代、開發者友好的模式替換複雜的企業專用API。 本指南提供了一個完整的、逐步的遷移路徑,去除不必要的程式碼,並使整個程式碼庫中的PDF操作更容易。
為什麼要從Foxit PDF SDK遷移到IronPDF
Foxit PDF的挑戰
Foxit PDF SDK是一個強大的企業級庫,但它伴隨著顯著的複雜性,可能會降低開發速度:
-
複雜的授權系統:多種產品,SKU和授權型別(每開發人員,每伺服器,OEM等)使得選擇適合您項目的選項變得困難。
-
企業定價:定價針對大型組織,對於小團隊或個人開發者來說可能是禁止性的。
-
龐大的本地包:公共NuGet包(
Foxit.SDK.Dotnet)很大(約240 MB),舊項目可能仍然攜帶直接的DLL引用或私人供應配置。 -
冗長的API:庫初始化需要
Library.Release()調用為每個操作增加了樣板程式碼。 -
獨立的HTML2PDF引擎:HTML到PDF的轉換需要HTML2PDF引擎二進位檔,自Foxit支持/銷售部門單獨分發,而不是在NuGet包中。
-
複雜的配置:需要詳細的物件配置(例如
HTML2PDFSettingData)及多重屬性。 -
C++來源:API模式反映了C++的來源,在現代C#應用程式中感覺不太自然。
Foxit PDF與IronPDF比較
| 方面 | Foxit PDF SDK | IronPDF |
|---|---|---|
| 安裝 | Foxit.SDK.Dotnet(約240 MB)+單獨的HTML2PDF引擎 | 簡單的NuGet包 |
| 授權 | 由銷售主導,每開發者每平台 | 透明,適合所有規模 |
| 初始化 | Library.Initialize(sn, key) | 設置許可金鑰一次 |
| 錯誤處理 | ErrorCode列舉 | 標準的.NET異常 |
| HTML轉PDF | 單獨下載引擎 | 內建 Chromium 引擎 |
| API風格 | C++來源,冗長 | 現代.NET模式 |
| 資源清理 | 手動Release() | IDisposable/自動 |
| 文件 | 企業文件門戶 | 公共教程 |
成本效益分析
從Foxit PDF遷移到IronPDF提供了實際的開發收益:通過更簡單的API降低了複雜性,通過直觀的方法加快了開發,現代.NET相容性包括async/await和LINQ支持,HTML優先的方法使用現有的Web技能,以及HTML轉換包括在內不需要單獨下載引擎。 IronPDF運行在當前的.NET版本上,並與現代C#模式完美配合。
開始之前
前提條件
- .NET環境: IronPDF支持.NET Framework 4.6.2+,.NET Core 3.1+,.NET 5/6/7/8/9+
- NuGet存取權限: 確保您能從NuGet上安裝包
- 授權金鑰: 從ironpdf.com獲取您的IronPDF生產用途授權金鑰
備份您的專案
# Create a backup branch
git checkout -b pre-ironpdf-migration
git add .
git commit -m "Backup beforeFoxit PDF SDKtoIronPDFmigration"
識別所有Foxit PDF的使用
# Find allFoxit PDF SDKreferences
grep -r "foxit\|PDFDoc\|PDFPage\|Library.Initialize\|Library.Release" --include="*.cs" --include="*.csproj" .
# Find Foxit DLL references
find . -name "*.csproj" | xargs grep -l "Foxit\|fsdk"
記錄當前功能
在遷移前, catalog:
- 您使用的哪些Foxit PDF功能(HTML轉換、註釋、表單、安全性)
- 許可金鑰位置和初始化程式碼
- 自定義配置和設置
- 使用ErrorCode枚舉的錯誤處理模式
快速開始遷移
步驟1:更新NuGet包
# Remove the Foxit NuGet package
dotnet remove package Foxit.SDK.Dotnet
# Install IronPDF
dotnet add package IronPdf
如果您在.csproj(較舊的構建)中有較舊的直接Foxit DLL引用,請手動刪除它們:
<!-- Remove these manually -->
<Reference Include="fsdk_dotnet">
<HintPath>..\libs\Foxit\fsdk_dotnet.dll</HintPath>
</Reference>
同時刪除任何獨立解壓的HTML2PDF引擎文件夾。
步驟 2:更新命名空間
// Before (Foxit PDF)
using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.annots;
using foxit.addon.conversion;
// After (IronPDF)
using IronPdf;
using IronPdf.Rendering;
using IronPdf.Editing;Imports IronPdf
Imports IronPdf.Rendering
Imports IronPdf.EditingImports IronPdf
Imports IronPdf.Rendering
Imports IronPdf.Editing步驟3:初始化IronPDF
此Foxit PDF遷移中最顯著的改進之一是消除了複雜的初始化和清理模式:
// Before (Foxit PDF)
string sn = "YOUR_SERIAL_NUMBER";
string key = "YOUR_LICENSE_KEY";
ErrorCode error_code = Library.Initialize(sn, key);
if (error_code != ErrorCode.e_ErrSuccess)
{
throw new Exception("Failed to initialize Foxit PDF SDK");
}
// ... your code ...
Library.Release(); // Don't forget this!
// After (IronPDF)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// That's it! No Release() needed// Before (Foxit PDF)
string sn = "YOUR_SERIAL_NUMBER";
string key = "YOUR_LICENSE_KEY";
ErrorCode error_code = Library.Initialize(sn, key);
if (error_code != ErrorCode.e_ErrSuccess)
{
throw new Exception("Failed to initialize Foxit PDF SDK");
}
// ... your code ...
Library.Release(); // Don't forget this!
// After (IronPDF)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// That's it! No Release() neededImports System
' Before (Foxit PDF)
Dim sn As String = "YOUR_SERIAL_NUMBER"
Dim key As String = "YOUR_LICENSE_KEY"
Dim error_code As ErrorCode = Library.Initialize(sn, key)
If error_code <> ErrorCode.e_ErrSuccess Then
Throw New Exception("Failed to initialize Foxit PDF SDK")
End If
' ... your code ...
Library.Release() ' Don't forget this!
' After (IronPDF)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
' That's it! No Release() neededImports System
' Before (Foxit PDF)
Dim sn As String = "YOUR_SERIAL_NUMBER"
Dim key As String = "YOUR_LICENSE_KEY"
Dim error_code As ErrorCode = Library.Initialize(sn, key)
If error_code <> ErrorCode.e_ErrSuccess Then
Throw New Exception("Failed to initialize Foxit PDF SDK")
End If
' ... your code ...
Library.Release() ' Don't forget this!
' After (IronPDF)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
' That's it! No Release() needed步驟4:基本轉換模式
// Before (Foxit PDF)
Library.Initialize(sn, key);
HTML2PDFSettingData settings = new HTML2PDFSettingData();
settings.page_width = 612.0f;
settings.page_height = 792.0f;
Convert.FromHTML(htmlContent, @"C:\Foxit\html2pdf_engine", "",
settings, "output.pdf", 30);
Library.Release();
// After (IronPDF)
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("output.pdf");// Before (Foxit PDF)
Library.Initialize(sn, key);
HTML2PDFSettingData settings = new HTML2PDFSettingData();
settings.page_width = 612.0f;
settings.page_height = 792.0f;
Convert.FromHTML(htmlContent, @"C:\Foxit\html2pdf_engine", "",
settings, "output.pdf", 30);
Library.Release();
// After (IronPDF)
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("output.pdf");' Before (Foxit PDF)
Library.Initialize(sn, key)
Dim settings As New HTML2PDFSettingData()
settings.page_width = 612.0F
settings.page_height = 792.0F
Convert.FromHTML(htmlContent, "C:\Foxit\html2pdf_engine", "", settings, "output.pdf", 30)
Library.Release()
' After (IronPDF)
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
pdf.SaveAs("output.pdf")' Before (Foxit PDF)
Library.Initialize(sn, key)
Dim settings As New HTML2PDFSettingData()
settings.page_width = 612.0F
settings.page_height = 792.0F
Convert.FromHTML(htmlContent, "C:\Foxit\html2pdf_engine", "", settings, "output.pdf", 30)
Library.Release()
' After (IronPDF)
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
pdf.SaveAs("output.pdf")完整API參考
命名空間映射
| Foxit PDF命名空間 | IronPDF等價 |
|---|---|
foxit | IronPdf |
foxit.common | IronPdf |
foxit.common.fxcrt | 無 |
foxit.pdf | IronPdf |
foxit.pdf.annots | IronPdf.Editing |
foxit.addon.conversion | IronPdf.Rendering |
核心類映射
| Foxit PDF SDK類 | IronPDF等價 |
|---|---|
Library | 無 |
PDFDoc | PdfDocument |
PDFPage | PdfDocument.Pages[i] |
HTML2PDF | ChromePdfRenderer |
TextPage | pdf.ExtractTextFromPage(i) |
Watermark | TextStamper / ImageStamper |
Security | SecuritySettings |
Form | pdf.Form |
Metadata | pdf.MetaData |
PDFDoc方法
| Foxit PDFDoc | IronPDF PdfDocument |
|---|---|
new PDFDoc(path) | PdfDocument.FromFile(path) |
doc.LoadW(password) | PdfDocument.FromFile(path, password) |
doc.GetPageCount() | pdf.PageCount |
doc.GetPage(index) | pdf.Pages[index] |
doc.SaveAs(path, flags) | pdf.SaveAs(path) |
doc.Close() | pdf.Dispose()或using語句 |
doc.InsertDocument() | PdfDocument.Merge() |
HTML2PDF / 轉換
| Foxit HTML2PDF | IronPDF等價 |
|---|---|
new HTML2PDFSettingData() | new ChromePdfRenderer() |
settings.page_width | RenderingOptions.PaperSize |
settings.page_height | RenderingOptions.SetCustomPaperSize() |
Convert.FromHTML(html, engine, ...) | renderer.RenderHtmlAsPdf(html) |
Convert.FromHTML(url, engine, ...) | renderer.RenderUrlAsPdf(url) |
水印設置
| Foxit水印 | IronPDF等價 |
|---|---|
new Watermark(doc, text, font, size, color) | new TextStamper() |
WatermarkSettings.position | VerticalAlignment + HorizontalAlignment |
WatermarkSettings.rotation | Rotation |
WatermarkSettings.opacity | Opacity |
watermark.InsertToAllPages() | pdf.ApplyStamp(stamper) |
程式碼範例
範例1:HTML轉PDF轉換
之前(Foxit PDF SDK):
// NuGet: Install-Package Foxit.SDK.Dotnet
// HTML-to-PDF requires the separateFoxit HTML2PDFengine (engine_path),
// obtained from Foxit support/sales — not in the NuGet package.
using foxit;
using foxit.common;
using foxit.addon.conversion;
using System;
class Program
{
static void Main()
{
Library.Initialize("sn", "key");
HTML2PDFSettingData settingData = new HTML2PDFSettingData();
settingData.page_width = 612.0f;
settingData.page_height = 792.0f;
settingData.page_mode = HTML2PDFPageMode.e_HTML2PDFPageModeSinglePage;
Convert.FromHTML(
"<html><body><h1>Hello World</h1></body></html>",
@"C:\Foxit\html2pdf_engine", // engine_path (separate download)
"", // cookies path
settingData,
"output.pdf",
30); // timeout (seconds)
Library.Release();
}
}// NuGet: Install-Package Foxit.SDK.Dotnet
// HTML-to-PDF requires the separateFoxit HTML2PDFengine (engine_path),
// obtained from Foxit support/sales — not in the NuGet package.
using foxit;
using foxit.common;
using foxit.addon.conversion;
using System;
class Program
{
static void Main()
{
Library.Initialize("sn", "key");
HTML2PDFSettingData settingData = new HTML2PDFSettingData();
settingData.page_width = 612.0f;
settingData.page_height = 792.0f;
settingData.page_mode = HTML2PDFPageMode.e_HTML2PDFPageModeSinglePage;
Convert.FromHTML(
"<html><body><h1>Hello World</h1></body></html>",
@"C:\Foxit\html2pdf_engine", // engine_path (separate download)
"", // cookies path
settingData,
"output.pdf",
30); // timeout (seconds)
Library.Release();
}
}Imports foxit
Imports foxit.common
Imports foxit.addon.conversion
Imports System
Class Program
Shared Sub Main()
Library.Initialize("sn", "key")
Dim settingData As New HTML2PDFSettingData()
settingData.page_width = 612.0F
settingData.page_height = 792.0F
settingData.page_mode = HTML2PDFPageMode.e_HTML2PDFPageModeSinglePage
Convert.FromHTML("<html><body><h1>Hello World</h1></body></html>", "C:\Foxit\html2pdf_engine", "", settingData, "output.pdf", 30)
Library.Release()
End Sub
End ClassImports foxit
Imports foxit.common
Imports foxit.addon.conversion
Imports System
Class Program
Shared Sub Main()
Library.Initialize("sn", "key")
Dim settingData As New HTML2PDFSettingData()
settingData.page_width = 612.0F
settingData.page_height = 792.0F
settingData.page_mode = HTML2PDFPageMode.e_HTML2PDFPageModeSinglePage
Convert.FromHTML("<html><body><h1>Hello World</h1></body></html>", "C:\Foxit\html2pdf_engine", "", settingData, "output.pdf", 30)
Library.Release()
End Sub
End Class之後(IronPDF):
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<html><body><h1>Hello World</h1></body></html>");
pdf.SaveAs("output.pdf");
}
}// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<html><body><h1>Hello World</h1></body></html>");
pdf.SaveAs("output.pdf");
}
}Imports IronPdf
Imports System
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<html><body><h1>Hello World</h1></body></html>")
pdf.SaveAs("output.pdf")
End Sub
End ClassImports IronPdf
Imports System
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<html><body><h1>Hello World</h1></body></html>")
pdf.SaveAs("output.pdf")
End Sub
End ClassIronPDF方法將15條以上的配置程式碼減少到只有4條。 沒有庫初始化,沒有顯式清理,沒有複雜的設置物件。 有關更多HTML渲染選項,請查看 HTML轉PDF文件。
範例2:URL轉PDF轉換
之前(Foxit PDF SDK):
// NuGet: Install-Package Foxit.SDK.Dotnet
// Convert.FromHTML accepts either a URL or a literal HTML string in the
// first argument; the URL form is what does URL-to-PDF.
using foxit;
using foxit.common;
using foxit.addon.conversion;
using System;
class Program
{
static void Main()
{
Library.Initialize("sn", "key");
HTML2PDFSettingData settingData = new HTML2PDFSettingData();
settingData.page_width = 612.0f;
settingData.page_height = 792.0f;
settingData.page_mode = HTML2PDFPageMode.e_HTML2PDFPageModeSinglePage;
Convert.FromHTML(
"https://www.example.com",
@"C:\Foxit\html2pdf_engine", // engine_path (separate download)
"", // cookies path
settingData,
"output.pdf",
30); // timeout (seconds)
Library.Release();
}
}// NuGet: Install-Package Foxit.SDK.Dotnet
// Convert.FromHTML accepts either a URL or a literal HTML string in the
// first argument; the URL form is what does URL-to-PDF.
using foxit;
using foxit.common;
using foxit.addon.conversion;
using System;
class Program
{
static void Main()
{
Library.Initialize("sn", "key");
HTML2PDFSettingData settingData = new HTML2PDFSettingData();
settingData.page_width = 612.0f;
settingData.page_height = 792.0f;
settingData.page_mode = HTML2PDFPageMode.e_HTML2PDFPageModeSinglePage;
Convert.FromHTML(
"https://www.example.com",
@"C:\Foxit\html2pdf_engine", // engine_path (separate download)
"", // cookies path
settingData,
"output.pdf",
30); // timeout (seconds)
Library.Release();
}
}Imports foxit
Imports foxit.common
Imports foxit.addon.conversion
Imports System
Module Program
Sub Main()
Library.Initialize("sn", "key")
Dim settingData As New HTML2PDFSettingData()
settingData.page_width = 612.0F
settingData.page_height = 792.0F
settingData.page_mode = HTML2PDFPageMode.e_HTML2PDFPageModeSinglePage
Convert.FromHTML(
"https://www.example.com",
"C:\Foxit\html2pdf_engine", ' engine_path (separate download)
"", ' cookies path
settingData,
"output.pdf",
30) ' timeout (seconds)
Library.Release()
End Sub
End ModuleImports foxit
Imports foxit.common
Imports foxit.addon.conversion
Imports System
Module Program
Sub Main()
Library.Initialize("sn", "key")
Dim settingData As New HTML2PDFSettingData()
settingData.page_width = 612.0F
settingData.page_height = 792.0F
settingData.page_mode = HTML2PDFPageMode.e_HTML2PDFPageModeSinglePage
Convert.FromHTML(
"https://www.example.com",
"C:\Foxit\html2pdf_engine", ' engine_path (separate download)
"", ' cookies path
settingData,
"output.pdf",
30) ' timeout (seconds)
Library.Release()
End Sub
End Module之後(IronPDF):
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.example.com");
pdf.SaveAs("output.pdf");
}
}// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.example.com");
pdf.SaveAs("output.pdf");
}
}Imports IronPdf
Imports System
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://www.example.com")
pdf.SaveAs("output.pdf")
End Sub
End ClassImports IronPdf
Imports System
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://www.example.com")
pdf.SaveAs("output.pdf")
End Sub
End ClassIronPDF的內建Chromium引擎自動處理JavaScript執行、CSS渲染和動態內容。 瞭解更多關於URL到PDF轉換。
範例3:新增水印
之前(Foxit PDF SDK):
// NuGet: Install-Package Foxit.SDK.Dotnet
using foxit;
using foxit.common;
using foxit.pdf;
using System;
class Program
{
static void Main()
{
Library.Initialize("sn", "key");
using (PDFDoc doc = new PDFDoc("input.pdf"))
{
doc.Load("");
WatermarkSettings settings = new WatermarkSettings();
settings.flags = (int)Watermark.Flags.e_FlagASPageContents;
settings.position = Position.e_PosCenter;
settings.rotation = -45.0f;
settings.opacity = 50; // 0-100 in newer SDKs
WatermarkTextProperties props = new WatermarkTextProperties();
props.font = new Font(Font.StandardID.e_StdIDHelvetica);
props.font_size = 48.0f;
props.color = 0xFF0000;
props.alignment = Alignment.e_AlignmentCenter;
Watermark watermark = new Watermark(doc, "Confidential", props, settings);
// No InsertToAllPages helper — iterate pages explicitly.
for (int i = 0; i < doc.GetPageCount(); i++)
{
using (PDFPage page = doc.GetPage(i))
{
watermark.InsertToPage(page);
}
}
doc.SaveAs("output.pdf", (int)PDFDoc.SaveFlags.e_SaveFlagNoOriginal);
}
Library.Release();
}
}// NuGet: Install-Package Foxit.SDK.Dotnet
using foxit;
using foxit.common;
using foxit.pdf;
using System;
class Program
{
static void Main()
{
Library.Initialize("sn", "key");
using (PDFDoc doc = new PDFDoc("input.pdf"))
{
doc.Load("");
WatermarkSettings settings = new WatermarkSettings();
settings.flags = (int)Watermark.Flags.e_FlagASPageContents;
settings.position = Position.e_PosCenter;
settings.rotation = -45.0f;
settings.opacity = 50; // 0-100 in newer SDKs
WatermarkTextProperties props = new WatermarkTextProperties();
props.font = new Font(Font.StandardID.e_StdIDHelvetica);
props.font_size = 48.0f;
props.color = 0xFF0000;
props.alignment = Alignment.e_AlignmentCenter;
Watermark watermark = new Watermark(doc, "Confidential", props, settings);
// No InsertToAllPages helper — iterate pages explicitly.
for (int i = 0; i < doc.GetPageCount(); i++)
{
using (PDFPage page = doc.GetPage(i))
{
watermark.InsertToPage(page);
}
}
doc.SaveAs("output.pdf", (int)PDFDoc.SaveFlags.e_SaveFlagNoOriginal);
}
Library.Release();
}
}Imports foxit
Imports foxit.common
Imports foxit.pdf
Imports System
Module Program
Sub Main()
Library.Initialize("sn", "key")
Using doc As New PDFDoc("input.pdf")
doc.Load("")
Dim settings As New WatermarkSettings()
settings.flags = CInt(Watermark.Flags.e_FlagASPageContents)
settings.position = Position.e_PosCenter
settings.rotation = -45.0F
settings.opacity = 50 ' 0-100 in newer SDKs
Dim props As New WatermarkTextProperties()
props.font = New Font(Font.StandardID.e_StdIDHelvetica)
props.font_size = 48.0F
props.color = &HFF0000
props.alignment = Alignment.e_AlignmentCenter
Dim watermark As New Watermark(doc, "Confidential", props, settings)
' No InsertToAllPages helper — iterate pages explicitly.
For i As Integer = 0 To doc.GetPageCount() - 1
Using page As PDFPage = doc.GetPage(i)
watermark.InsertToPage(page)
End Using
Next
doc.SaveAs("output.pdf", CInt(PDFDoc.SaveFlags.e_SaveFlagNoOriginal))
End Using
Library.Release()
End Sub
End ModuleImports foxit
Imports foxit.common
Imports foxit.pdf
Imports System
Module Program
Sub Main()
Library.Initialize("sn", "key")
Using doc As New PDFDoc("input.pdf")
doc.Load("")
Dim settings As New WatermarkSettings()
settings.flags = CInt(Watermark.Flags.e_FlagASPageContents)
settings.position = Position.e_PosCenter
settings.rotation = -45.0F
settings.opacity = 50 ' 0-100 in newer SDKs
Dim props As New WatermarkTextProperties()
props.font = New Font(Font.StandardID.e_StdIDHelvetica)
props.font_size = 48.0F
props.color = &HFF0000
props.alignment = Alignment.e_AlignmentCenter
Dim watermark As New Watermark(doc, "Confidential", props, settings)
' No InsertToAllPages helper — iterate pages explicitly.
For i As Integer = 0 To doc.GetPageCount() - 1
Using page As PDFPage = doc.GetPage(i)
watermark.InsertToPage(page)
End Using
Next
doc.SaveAs("output.pdf", CInt(PDFDoc.SaveFlags.e_SaveFlagNoOriginal))
End Using
Library.Release()
End Sub
End Module之後(IronPDF):
// NuGet: Install-Package IronPdf
using IronPdf;
using IronPdf.Editing;
using System;
class Program
{
static void Main()
{
var pdf = PdfDocument.FromFile("input.pdf");
pdf.ApplyWatermark(new TextStamper()
{
Text = "Confidential",
FontSize = 48,
Opacity = 50,
Rotation = -45,
VerticalAlignment = VerticalAlignment.Middle,
HorizontalAlignment = HorizontalAlignment.Center
});
pdf.SaveAs("output.pdf");
}
}// NuGet: Install-Package IronPdf
using IronPdf;
using IronPdf.Editing;
using System;
class Program
{
static void Main()
{
var pdf = PdfDocument.FromFile("input.pdf");
pdf.ApplyWatermark(new TextStamper()
{
Text = "Confidential",
FontSize = 48,
Opacity = 50,
Rotation = -45,
VerticalAlignment = VerticalAlignment.Middle,
HorizontalAlignment = HorizontalAlignment.Center
});
pdf.SaveAs("output.pdf");
}
}Imports IronPdf
Imports IronPdf.Editing
Imports System
Class Program
Shared Sub Main()
Dim pdf = PdfDocument.FromFile("input.pdf")
pdf.ApplyWatermark(New TextStamper() With {
.Text = "Confidential",
.FontSize = 48,
.Opacity = 50,
.Rotation = -45,
.VerticalAlignment = VerticalAlignment.Middle,
.HorizontalAlignment = HorizontalAlignment.Center
})
pdf.SaveAs("output.pdf")
End Sub
End ClassImports IronPdf
Imports IronPdf.Editing
Imports System
Class Program
Shared Sub Main()
Dim pdf = PdfDocument.FromFile("input.pdf")
pdf.ApplyWatermark(New TextStamper() With {
.Text = "Confidential",
.FontSize = 48,
.Opacity = 50,
.Rotation = -45,
.VerticalAlignment = VerticalAlignment.Middle,
.HorizontalAlignment = HorizontalAlignment.Center
})
pdf.SaveAs("output.pdf")
End Sub
End ClassIronPDF的TextStamper提供直觀的基於屬性的配置,而不是獨立的設置物件和手動頁面迭代。 有關其他選項,請參見完整的水印文件。
範例4:帶頁眉和頁腳的URL轉PDF
之前(Foxit PDF SDK):
using foxit;
using foxit.addon.conversion;
class Program
{
static void Main()
{
Library.Initialize("sn", "key");
try
{
HTML2PDFSettingData settings = new HTML2PDFSettingData();
settings.page_width = 595.0f; // A4
settings.page_height = 842.0f;
settings.page_margin_top = 100.0f;
settings.page_margin_bottom = 100.0f;
//Foxit PDF SDKhas limited header/footer support
// Often requires post-processing or additional code
Convert.FromHTML(
"https://www.example.com",
@"C:\Foxit\html2pdf_engine", // engine_path (separate download)
"", // cookies path
settings,
"webpage.pdf",
30); // timeout (seconds)
}
finally
{
Library.Release();
}
}
}using foxit;
using foxit.addon.conversion;
class Program
{
static void Main()
{
Library.Initialize("sn", "key");
try
{
HTML2PDFSettingData settings = new HTML2PDFSettingData();
settings.page_width = 595.0f; // A4
settings.page_height = 842.0f;
settings.page_margin_top = 100.0f;
settings.page_margin_bottom = 100.0f;
//Foxit PDF SDKhas limited header/footer support
// Often requires post-processing or additional code
Convert.FromHTML(
"https://www.example.com",
@"C:\Foxit\html2pdf_engine", // engine_path (separate download)
"", // cookies path
settings,
"webpage.pdf",
30); // timeout (seconds)
}
finally
{
Library.Release();
}
}
}Imports foxit
Imports foxit.addon.conversion
Class Program
Shared Sub Main()
Library.Initialize("sn", "key")
Try
Dim settings As New HTML2PDFSettingData()
settings.page_width = 595.0F ' A4
settings.page_height = 842.0F
settings.page_margin_top = 100.0F
settings.page_margin_bottom = 100.0F
'Foxit PDF SDKhas limited header/footer support
' Often requires post-processing or additional code
Convert.FromHTML("https://www.example.com", "C:\Foxit\html2pdf_engine", "" , settings, "webpage.pdf", 30) ' timeout (seconds)
Finally
Library.Release()
End Try
End Sub
End ClassImports foxit
Imports foxit.addon.conversion
Class Program
Shared Sub Main()
Library.Initialize("sn", "key")
Try
Dim settings As New HTML2PDFSettingData()
settings.page_width = 595.0F ' A4
settings.page_height = 842.0F
settings.page_margin_top = 100.0F
settings.page_margin_bottom = 100.0F
'Foxit PDF SDKhas limited header/footer support
' Often requires post-processing or additional code
Convert.FromHTML("https://www.example.com", "C:\Foxit\html2pdf_engine", "" , settings, "webpage.pdf", 30) ' timeout (seconds)
Finally
Library.Release()
End Try
End Sub
End Class之後(IronPDF):
using IronPdf;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.WaitFor.RenderDelay(3000); // Wait for JS
// Built-in header/footer support
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
HtmlFragment = "<div style='text-align:center; font-size:12pt;'>Company Report</div>",
DrawDividerLine = true
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
HtmlFragment = "<div style='text-align:right; font-size:10pt;'>Page {page} of {total-pages}</div>",
DrawDividerLine = true
};
var pdf = renderer.RenderUrlAsPdf("https://www.example.com");
pdf.SaveAs("webpage.pdf");
}
}using IronPdf;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.WaitFor.RenderDelay(3000); // Wait for JS
// Built-in header/footer support
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
HtmlFragment = "<div style='text-align:center; font-size:12pt;'>Company Report</div>",
DrawDividerLine = true
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
HtmlFragment = "<div style='text-align:right; font-size:10pt;'>Page {page} of {total-pages}</div>",
DrawDividerLine = true
};
var pdf = renderer.RenderUrlAsPdf("https://www.example.com");
pdf.SaveAs("webpage.pdf");
}
}Imports IronPdf
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.PrintHtmlBackgrounds = True
renderer.RenderingOptions.WaitFor.RenderDelay(3000) ' Wait for JS
' Built-in header/footer support
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
.HtmlFragment = "<div style='text-align:center; font-size:12pt;'>Company Report</div>",
.DrawDividerLine = True
}
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {
.HtmlFragment = "<div style='text-align:right; font-size:10pt;'>Page {page} of {total-pages}</div>",
.DrawDividerLine = True
}
Dim pdf = renderer.RenderUrlAsPdf("https://www.example.com")
pdf.SaveAs("webpage.pdf")
End Sub
End ClassImports IronPdf
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.PrintHtmlBackgrounds = True
renderer.RenderingOptions.WaitFor.RenderDelay(3000) ' Wait for JS
' Built-in header/footer support
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
.HtmlFragment = "<div style='text-align:center; font-size:12pt;'>Company Report</div>",
.DrawDividerLine = True
}
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {
.HtmlFragment = "<div style='text-align:right; font-size:10pt;'>Page {page} of {total-pages}</div>",
.DrawDividerLine = True
}
Dim pdf = renderer.RenderUrlAsPdf("https://www.example.com")
pdf.SaveAs("webpage.pdf")
End Sub
End ClassIronPDF提供本機頁眉和頁腳支持,具備HTML樣式和動態頁碼佔位符。
範例5:PDF安全性和加密
之前(Foxit PDF SDK):
using foxit;
using foxit.pdf;
class Program
{
static void Main()
{
Library.Initialize("sn", "key");
try
{
using (PDFDoc doc = new PDFDoc("input.pdf"))
{
doc.LoadW("");
// Build the encryption data (cipher, key length, permissions)
using (StdEncryptData encryptData = new StdEncryptData(
true, // is_encrypt_metadata
(int)(PDFDoc.UserPermissions.e_PermPrint |
PDFDoc.UserPermissions.e_PermModify),
SecurityHandler.CipherType.e_CipherAES,
16)) // key length (bytes) -> AES-128
using (StdSecurityHandler securityHandler = new StdSecurityHandler())
{
securityHandler.Initialize(encryptData, "user_password", "owner_password");
doc.SetSecurityHandler(securityHandler);
}
doc.SaveAs("encrypted.pdf", (int)PDFDoc.SaveFlags.e_SaveFlagNoOriginal);
}
}
finally
{
Library.Release();
}
}
}using foxit;
using foxit.pdf;
class Program
{
static void Main()
{
Library.Initialize("sn", "key");
try
{
using (PDFDoc doc = new PDFDoc("input.pdf"))
{
doc.LoadW("");
// Build the encryption data (cipher, key length, permissions)
using (StdEncryptData encryptData = new StdEncryptData(
true, // is_encrypt_metadata
(int)(PDFDoc.UserPermissions.e_PermPrint |
PDFDoc.UserPermissions.e_PermModify),
SecurityHandler.CipherType.e_CipherAES,
16)) // key length (bytes) -> AES-128
using (StdSecurityHandler securityHandler = new StdSecurityHandler())
{
securityHandler.Initialize(encryptData, "user_password", "owner_password");
doc.SetSecurityHandler(securityHandler);
}
doc.SaveAs("encrypted.pdf", (int)PDFDoc.SaveFlags.e_SaveFlagNoOriginal);
}
}
finally
{
Library.Release();
}
}
}Imports foxit
Imports foxit.pdf
Class Program
Shared Sub Main()
Library.Initialize("sn", "key")
Try
Using doc As New PDFDoc("input.pdf")
doc.LoadW("")
' Build the encryption data (cipher, key length, permissions)
Using encryptData As New StdEncryptData(True, CType(PDFDoc.UserPermissions.e_PermPrint Or PDFDoc.UserPermissions.e_PermModify, Integer), SecurityHandler.CipherType.e_CipherAES, 16) ' key length (bytes) -> AES-128
Using securityHandler As New StdSecurityHandler()
securityHandler.Initialize(encryptData, "user_password", "owner_password")
doc.SetSecurityHandler(securityHandler)
End Using
End Using
doc.SaveAs("encrypted.pdf", CType(PDFDoc.SaveFlags.e_SaveFlagNoOriginal, Integer))
End Using
Finally
Library.Release()
End Try
End Sub
End ClassImports foxit
Imports foxit.pdf
Class Program
Shared Sub Main()
Library.Initialize("sn", "key")
Try
Using doc As New PDFDoc("input.pdf")
doc.LoadW("")
' Build the encryption data (cipher, key length, permissions)
Using encryptData As New StdEncryptData(True, CType(PDFDoc.UserPermissions.e_PermPrint Or PDFDoc.UserPermissions.e_PermModify, Integer), SecurityHandler.CipherType.e_CipherAES, 16) ' key length (bytes) -> AES-128
Using securityHandler As New StdSecurityHandler()
securityHandler.Initialize(encryptData, "user_password", "owner_password")
doc.SetSecurityHandler(securityHandler)
End Using
End Using
doc.SaveAs("encrypted.pdf", CType(PDFDoc.SaveFlags.e_SaveFlagNoOriginal, Integer))
End Using
Finally
Library.Release()
End Try
End Sub
End Class之後(IronPDF):
using IronPdf;
class Program
{
static void Main()
{
var pdf = PdfDocument.FromFile("input.pdf");
// Set passwords
pdf.SecuritySettings.OwnerPassword = "owner_password";
pdf.SecuritySettings.UserPassword = "user_password";
// Set permissions
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserEdits = IronPdf.Security.PdfEditSecurity.EditAll;
pdf.SecuritySettings.AllowUserCopyPasteContent = true;
pdf.SecuritySettings.AllowUserAnnotations = true;
pdf.SaveAs("encrypted.pdf");
}
}using IronPdf;
class Program
{
static void Main()
{
var pdf = PdfDocument.FromFile("input.pdf");
// Set passwords
pdf.SecuritySettings.OwnerPassword = "owner_password";
pdf.SecuritySettings.UserPassword = "user_password";
// Set permissions
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserEdits = IronPdf.Security.PdfEditSecurity.EditAll;
pdf.SecuritySettings.AllowUserCopyPasteContent = true;
pdf.SecuritySettings.AllowUserAnnotations = true;
pdf.SaveAs("encrypted.pdf");
}
}Imports IronPdf
Class Program
Shared Sub Main()
Dim pdf = PdfDocument.FromFile("input.pdf")
' Set passwords
pdf.SecuritySettings.OwnerPassword = "owner_password"
pdf.SecuritySettings.UserPassword = "user_password"
' Set permissions
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights
pdf.SecuritySettings.AllowUserEdits = IronPdf.Security.PdfEditSecurity.EditAll
pdf.SecuritySettings.AllowUserCopyPasteContent = True
pdf.SecuritySettings.AllowUserAnnotations = True
pdf.SaveAs("encrypted.pdf")
End Sub
End ClassImports IronPdf
Class Program
Shared Sub Main()
Dim pdf = PdfDocument.FromFile("input.pdf")
' Set passwords
pdf.SecuritySettings.OwnerPassword = "owner_password"
pdf.SecuritySettings.UserPassword = "user_password"
' Set permissions
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights
pdf.SecuritySettings.AllowUserEdits = IronPdf.Security.PdfEditSecurity.EditAll
pdf.SecuritySettings.AllowUserCopyPasteContent = True
pdf.SecuritySettings.AllowUserAnnotations = True
pdf.SaveAs("encrypted.pdf")
End Sub
End Class效能考量
重用ChromePdfRenderer
為了在您的Foxit PDF遷移期間獲得最佳效能,請重用ChromePdfRenderer實例——它是執行緒安全的:
// GOOD - Reuse renderer (thread-safe)
public class PdfService
{
private static readonly ChromePdfRenderer _renderer = new ChromePdfRenderer();
public byte[] Generate(string html) => _renderer.RenderHtmlAsPdf(html).BinaryData;
}
// BAD - Creates new instance each time
public byte[] GenerateBad(string html)
{
var renderer = new ChromePdfRenderer(); // Wasteful
return renderer.RenderHtmlAsPdf(html).BinaryData;
}// GOOD - Reuse renderer (thread-safe)
public class PdfService
{
private static readonly ChromePdfRenderer _renderer = new ChromePdfRenderer();
public byte[] Generate(string html) => _renderer.RenderHtmlAsPdf(html).BinaryData;
}
// BAD - Creates new instance each time
public byte[] GenerateBad(string html)
{
var renderer = new ChromePdfRenderer(); // Wasteful
return renderer.RenderHtmlAsPdf(html).BinaryData;
}Imports System
Public Class PdfService
Private Shared ReadOnly _renderer As New ChromePdfRenderer()
Public Function Generate(html As String) As Byte()
Return _renderer.RenderHtmlAsPdf(html).BinaryData
End Function
' BAD - Creates new instance each time
Public Function GenerateBad(html As String) As Byte()
Dim renderer As New ChromePdfRenderer() ' Wasteful
Return renderer.RenderHtmlAsPdf(html).BinaryData
End Function
End ClassImports System
Public Class PdfService
Private Shared ReadOnly _renderer As New ChromePdfRenderer()
Public Function Generate(html As String) As Byte()
Return _renderer.RenderHtmlAsPdf(html).BinaryData
End Function
' BAD - Creates new instance each time
Public Function GenerateBad(html As String) As Byte()
Dim renderer As New ChromePdfRenderer() ' Wasteful
Return renderer.RenderHtmlAsPdf(html).BinaryData
End Function
End Class單位轉換助手
Foxit PDF SDK使用點; IronPDF使用毫米。 在遷移期間使用此助手:
public static class UnitConverter
{
public static double PointsToMm(double points) => points * 0.352778;
public static double MmToPoints(double mm) => mm / 0.352778;
public static double InchesToMm(double inches) => inches * 25.4;
}
// Usage: Convert Foxit's 72 points (1 inch) toIronPDFmillimeters
renderer.RenderingOptions.MarginTop = UnitConverter.PointsToMm(72); // ~25.4mmpublic static class UnitConverter
{
public static double PointsToMm(double points) => points * 0.352778;
public static double MmToPoints(double mm) => mm / 0.352778;
public static double InchesToMm(double inches) => inches * 25.4;
}
// Usage: Convert Foxit's 72 points (1 inch) toIronPDFmillimeters
renderer.RenderingOptions.MarginTop = UnitConverter.PointsToMm(72); // ~25.4mmPublic Module UnitConverter
Public Function PointsToMm(points As Double) As Double
Return points * 0.352778
End Function
Public Function MmToPoints(mm As Double) As Double
Return mm / 0.352778
End Function
Public Function InchesToMm(inches As Double) As Double
Return inches * 25.4
End Function
End Module
' Usage: Convert Foxit's 72 points (1 inch) to IronPDF millimeters
renderer.RenderingOptions.MarginTop = UnitConverter.PointsToMm(72) ' ~25.4mmPublic Module UnitConverter
Public Function PointsToMm(points As Double) As Double
Return points * 0.352778
End Function
Public Function MmToPoints(mm As Double) As Double
Return mm / 0.352778
End Function
Public Function InchesToMm(inches As Double) As Double
Return inches * 25.4
End Function
End Module
' Usage: Convert Foxit's 72 points (1 inch) to IronPDF millimeters
renderer.RenderingOptions.MarginTop = UnitConverter.PointsToMm(72) ' ~25.4mm正確的資源處置
// GOOD - Using statement for automatic cleanup
using (var pdf = PdfDocument.FromFile("large.pdf"))
{
string text = pdf.ExtractAllText();
} // pdf is disposed automatically// GOOD - Using statement for automatic cleanup
using (var pdf = PdfDocument.FromFile("large.pdf"))
{
string text = pdf.ExtractAllText();
} // pdf is disposed automaticallyImports PdfDocument
' GOOD - Using block for automatic cleanup
Using pdf = PdfDocument.FromFile("large.pdf")
Dim text As String = pdf.ExtractAllText()
End Using ' pdf is disposed automaticallyImports PdfDocument
' GOOD - Using block for automatic cleanup
Using pdf = PdfDocument.FromFile("large.pdf")
Dim text As String = pdf.ExtractAllText()
End Using ' pdf is disposed automatically故障排除
問題1:找不到Library.Initialize()
問題:在IronPDF中不存在Library.Initialize()。
解決方案:IronPDF使用更簡單的初始化模式:
// Foxit PDF
Library.Initialize(sn, key);
//IronPDF- just set license key once at startup
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";// Foxit PDF
Library.Initialize(sn, key);
//IronPDF- just set license key once at startup
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";' Foxit PDF
Library.Initialize(sn, key)
' IronPDF- just set license key once at startup
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"' Foxit PDF
Library.Initialize(sn, key)
' IronPDF- just set license key once at startup
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"問題2:ErrorCode處理
問題:程式碼檢查ErrorCode.e_ErrSuccess但IronPDF中沒有這個。
解決方案:使用標準的.NET異常處理:
// Foxit PDF
ErrorCode err = doc.LoadW("");
if (err != ErrorCode.e_ErrSuccess) { /* handle error */ }
// IronPDF
try
{
var pdf = PdfDocument.FromFile("input.pdf");
}
catch (IOException ex)
{
Console.WriteLine($"Failed to load PDF: {ex.Message}");
}// Foxit PDF
ErrorCode err = doc.LoadW("");
if (err != ErrorCode.e_ErrSuccess) { /* handle error */ }
// IronPDF
try
{
var pdf = PdfDocument.FromFile("input.pdf");
}
catch (IOException ex)
{
Console.WriteLine($"Failed to load PDF: {ex.Message}");
}Imports System
Imports System.IO
' Foxit PDF
Dim err As ErrorCode = doc.LoadW("")
If err <> ErrorCode.e_ErrSuccess Then
' handle error
End If
' IronPDF
Try
Dim pdf = PdfDocument.FromFile("input.pdf")
Catch ex As IOException
Console.WriteLine($"Failed to load PDF: {ex.Message}")
End TryImports System
Imports System.IO
' Foxit PDF
Dim err As ErrorCode = doc.LoadW("")
If err <> ErrorCode.e_ErrSuccess Then
' handle error
End If
' IronPDF
Try
Dim pdf = PdfDocument.FromFile("input.pdf")
Catch ex As IOException
Console.WriteLine($"Failed to load PDF: {ex.Message}")
End Try問題3:找不到PDFDoc.Close()
問題:IronPDF中沒有doc.Close()方法。
解決方案:使用using語句:
// Foxit PDF
doc.Close();
// IronPDF
pdf.Dispose();
// or better: wrap in using statement// Foxit PDF
doc.Close();
// IronPDF
pdf.Dispose();
// or better: wrap in using statementnetnet遷移檢查表
遷移前
- 清點所有使用的Foxit PDF SDK功能
- 記錄許可金鑰位置
- 記錄所有
Library.Release()調用 - 列出自定義設置(頁面大小,邊距等)
- 使用ErrorCode識別錯誤處理模式
- 將專案備份到版本控制
- 獲得IronPDF授權金鑰
包遷移
- 從.csproj中刪除Foxit PDF SDK DLL引用
- 刪除任何私人NuGet源配置
- 安裝IronPDF NuGet包:
dotnet add package IronPdf - 更新命名空間導入
- 在啟動時設置IronPDF授權金鑰
程式碼遷移
- 刪除
Library.Release()調用 - 用try/catch替換
ErrorCode檢查 - 用
PDFDoc - 用
Convert.FromHTML(...) - 將頁面存取從
Pages[i] - 用
SaveAs(path, flags) - 用
Close() - 更新水印程式碼以使用
TextStamper - 從點轉換單位到毫米
測試
- 驗證HTML到PDF輸出是否符合期望
- 測試PDF載入和文字提取
- 驗證合併功能
- 檢查水印外觀
- 測試安全性/加密功能
- 驗證表單欄位操作
- 性能測試
遷移後
- 刪除Foxit PDF SDK DLLs
- 移除與Foxit相關的配置文件
- 更新文件
- 清理未使用的助手程式碼
Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。
相關文章


