跳至頁尾內容
影片

如何在 C# 中將 HTML 文件渲染為 PDF

Full Comparison

Looking for a detailed feature-by-feature breakdown? See how IronPDF stacks up against Aspose PDF on pricing, HTML support, and licensing.

View Full Comparison

為什麼要從Aspose.PDF遷移?

雖然Aspose.PDF提供企業級的功能,但有幾個因素促使開發團隊尋求現代化替代方案來滿足其PDF生成需求。

成本比較

Aspose.PDF使用永久授權模式,其中包含一年的更新; 可選的續約延長更新時間窗口。 來源:Aspose 定價頁面

方面 Aspose.PDF IronPDF
起始價格(開發者小型企業) $1,199/開發者 $749一次性(Lite)
許可模式 永久+一年更新; optional renewal 永久授權
開發者OEM $3,597/開發者(無限部署) 包含在更高級別中
支援 包含在所有付費級別中 包括
免費評估 30天臨時授權(否則水印+大小限制) 開發免費

HTML渲染引擎比較

Aspose.PDF使用內部開發的HTML/CSS渲染引擎(不是Chromium); 使用者在Aspose論壇上回報了現代CSS佈局功能(如Flexbox和CSS Grid)的缺陷。 IronPDF使用嵌入的Chromium構建來進行HTML-to-PDF渲染。

功能 Aspose.PDF(內部引擎) IronPDF(Chromium)
CSS3支援 部分; 現代佈局功能有缺陷 完整支持 CSS3
Flexbox/Grid 有限/不一致(根據Aspose論壇報告) 全面支持
JavaScript 有限 完全支援(V8透過Chromium)
網頁字型 部分 完整
現代HTML5 部分 完整
渲染品質 隨著複雜佈局變化 Chrome等效

性能特性

使用者在Aspose支援論壇上報告了性能差異。 以下資料反映社群報告的情境——與您自己的工作負載進行驗證。

指標 Aspose.PDF IronPDF
HTML渲染 使用者報告的複雜CSS工作負載減速 優化的Chromium引擎
大型文件 某些情境下報告了記憶體增長 高效流媒體
Linux性能 社群論壇上報告了高CPU和記憶體增長 穩定

Aspose.PDF對IronPDF:主要差異

方面 Aspose.PDF IronPDF
價格(入門級) $1,199/開發者(永久+1年更新) $749一次性(Lite)
HTML引擎 內部引擎(現代CSS受限) Chromium(完整CSS3/JS)
性能 論壇報告的複雜CSS減速 優化
許可模式 永久+ .lic 文件;可選續約進行更新 永久+基於程式碼的金鑰
Linux支援 論壇報告的CPU/記憶體問題 穩定
頁碼編索 基於1(Pages[1] 基於0(Pages[0]

遷移前準備

前提條件

確保您的環境符合以下要求:

  • .NET Framework 4.6.2+ or .NET Core 3.1 / .NET 5-9
  • Visual Studio 2019+或VS Code與C#擴展
  • NuGet包管理器存取 -IronPDF許可證金鑰(免費試用可在 ironpdf.com 獲得)

審計Aspose.PDF的使用情況

在您的解決方案目錄中運行這些命令以識別所有的Aspose.PDF引用:

# Find all Aspose.Pdf using statements
grep -r "using Aspose.Pdf" --include="*.cs" .

# Find HtmlLoadOptions usage
grep -r "HtmlLoadOptions\|HtmlFragment" --include="*.cs" .

# Find Facades usage
grep -r "PdfFileEditor\|PdfFileMend\|PdfFileStamp" --include="*.cs" .

# Find TextAbsorber usage
grep -r "TextAbsorber\|TextFragmentAbsorber" --include="*.cs" .
# Find all Aspose.Pdf using statements
grep -r "using Aspose.Pdf" --include="*.cs" .

# Find HtmlLoadOptions usage
grep -r "HtmlLoadOptions\|HtmlFragment" --include="*.cs" .

# Find Facades usage
grep -r "PdfFileEditor\|PdfFileMend\|PdfFileStamp" --include="*.cs" .

# Find TextAbsorber usage
grep -r "TextAbsorber\|TextFragmentAbsorber" --include="*.cs" .
SHELL

預期的中斷變更

Aspose.PDF Pattern 需要更改
new Document() + Pages.Add() 改用HTML渲染
HtmlLoadOptions ChromePdfRenderer.RenderHtmlAsPdf()
TextFragment+手動定位 基於CSS的定位
PdfFileEditor.Concatenate() PdfDocument.Merge()
TextFragmentAbsorber pdf.ExtractAllText()
ImageStamp 基於HTML的水印
.lic 文件許可 基於程式碼的授權金鑰
基於1的頁碼編索 基於0的頁碼編索

逐步遷移過程

步驟1:更新NuGet包

移除Aspose.PDF並安裝IronPDF:

# Remove Aspose.PDF
dotnet remove package Aspose.PDF

# Install IronPDF
dotnet add package IronPdf
# Remove Aspose.PDF
dotnet remove package Aspose.PDF

# Install IronPDF
dotnet add package IronPdf
SHELL

或者通過包管理器控制台:

Uninstall-Package Aspose.PDF
Install-Package IronPdf

步驟 2:更新命名空間引用

取代Aspose.PDF命名空間為IronPDF:

// Remove these
using Aspose.Pdf;
using Aspose.Pdf.Text;
using Aspose.Pdf.Facades;
using Aspose.Pdf.Generator;

// Add these
using IronPdf;
using IronPdf.Rendering;
using IronPdf.Editing;
// Remove these
using Aspose.Pdf;
using Aspose.Pdf.Text;
using Aspose.Pdf.Facades;
using Aspose.Pdf.Generator;

// Add these
using IronPdf;
using IronPdf.Rendering;
using IronPdf.Editing;
' Remove these
' Imports Aspose.Pdf
' Imports Aspose.Pdf.Text
' Imports Aspose.Pdf.Facades
' Imports Aspose.Pdf.Generator

' Add these
Imports IronPdf
Imports IronPdf.Rendering
Imports IronPdf.Editing
$vbLabelText   $csharpLabel

步驟3:更新許可配置

Aspose.PDF使用.lic文件授權。 IronPDF使用簡單的程式碼授權金鑰。

Aspose.PDF實現:

var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.Pdf.lic");
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.Pdf.lic");
Imports Aspose.Pdf

Dim license As New License()
license.SetLicense("Aspose.Pdf.lic")
$vbLabelText   $csharpLabel

IronPDF實現:

IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
$vbLabelText   $csharpLabel

完整 API 遷移參考

核心類映射

Aspose.PDF類 IronPDF等價
Document PdfDocument
HtmlLoadOptions ChromePdfRenderer
TextFragmentAbsorber PdfDocument.ExtractAllText()
PdfFileEditor PdfDocument.Merge()
TextStamp / ImageStamp PdfDocument.ApplyWatermark()
License IronPdf.License

文件操作

Aspose.PDF方法 IronPDF方法
new Document() new PdfDocument()
new Document(path) PdfDocument.FromFile(path)
doc.Save(path) pdf.SaveAs(path)
doc.Pages.Count pdf.PageCount
doc.Pages.Delete(index) pdf.RemovePages(index)

HTML到PDF轉換

Aspose.PDF方法 IronPDF方法
new HtmlLoadOptions() new ChromePdfRenderer()
new Document(stream, htmlOptions) renderer.RenderHtmlAsPdf(html)
new Document(path, htmlOptions) renderer.RenderHtmlFileAsPdf(path)

程式碼遷移範例

HTML字串轉PDF

最常見的Aspose.PDF操作展示了基本的差異——Aspose.PDF需要將HTML包裝在MemoryStream中,而IronPDF直接接受字串。

Aspose.PDF實現:

// NuGet: Install-Package Aspose.PDF
using Aspose.Pdf;
using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string htmlContent = "<html><body><h1>Hello World</h1><p>This is a PDF from HTML string.</p></body></html>";

        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(htmlContent)))
        {
            var htmlLoadOptions = new HtmlLoadOptions();
            var document = new Document(stream, htmlLoadOptions);
            document.Save("output.pdf");
        }

        Console.WriteLine("PDF created from HTML string");
    }
}
// NuGet: Install-Package Aspose.PDF
using Aspose.Pdf;
using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string htmlContent = "<html><body><h1>Hello World</h1><p>This is a PDF from HTML string.</p></body></html>";

        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(htmlContent)))
        {
            var htmlLoadOptions = new HtmlLoadOptions();
            var document = new Document(stream, htmlLoadOptions);
            document.Save("output.pdf");
        }

        Console.WriteLine("PDF created from HTML string");
    }
}
Imports Aspose.Pdf
Imports System
Imports System.IO
Imports System.Text

Module Program
    Sub Main()
        Dim htmlContent As String = "<html><body><h1>Hello World</h1><p>This is a PDF from HTML string.</p></body></html>"

        Using stream As New MemoryStream(Encoding.UTF8.GetBytes(htmlContent))
            Dim htmlLoadOptions As New HtmlLoadOptions()
            Dim document As New Document(stream, htmlLoadOptions)
            document.Save("output.pdf")
        End Using

        Console.WriteLine("PDF created from HTML string")
    End Sub
End Module
$vbLabelText   $csharpLabel

IronPDF實現:

// NuGet: Install-Package IronPdf
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        string htmlContent = "<html><body><h1>Hello World</h1><p>This is a PDF from HTML string.</p></body></html>";

        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        pdf.SaveAs("output.pdf");

        Console.WriteLine("PDF created from HTML string");
    }
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        string htmlContent = "<html><body><h1>Hello World</h1><p>This is a PDF from HTML string.</p></body></html>";

        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        pdf.SaveAs("output.pdf");

        Console.WriteLine("PDF created from HTML string");
    }
}
Imports IronPdf
Imports System

Class Program
    Shared Sub Main()
        Dim htmlContent As String = "<html><body><h1>Hello World</h1><p>This is a PDF from HTML string.</p></body></html>"

        Dim renderer = New ChromePdfRenderer()
        Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
        pdf.SaveAs("output.pdf")

        Console.WriteLine("PDF created from HTML string")
    End Sub
End Class
$vbLabelText   $csharpLabel

IronPDF完全消除了MemoryStream包裝器——一個更乾淨,直觀的API。

HTML文件到PDF

Aspose.PDF實現:

// NuGet: Install-Package Aspose.PDF
using Aspose.Pdf;
using System;

class Program
{
    static void Main()
    {
        var htmlLoadOptions = new HtmlLoadOptions();
        var document = new Document("input.html", htmlLoadOptions);
        document.Save("output.pdf");
        Console.WriteLine("PDF created successfully");
    }
}
// NuGet: Install-Package Aspose.PDF
using Aspose.Pdf;
using System;

class Program
{
    static void Main()
    {
        var htmlLoadOptions = new HtmlLoadOptions();
        var document = new Document("input.html", htmlLoadOptions);
        document.Save("output.pdf");
        Console.WriteLine("PDF created successfully");
    }
}
Imports Aspose.Pdf
Imports System

Class Program
    Shared Sub Main()
        Dim htmlLoadOptions As New HtmlLoadOptions()
        Dim document As New Document("input.html", htmlLoadOptions)
        document.Save("output.pdf")
        Console.WriteLine("PDF created successfully")
    End Sub
End Class
$vbLabelText   $csharpLabel

IronPDF實現:

// NuGet: Install-Package IronPdf
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlFileAsPdf("input.html");
        pdf.SaveAs("output.pdf");
        Console.WriteLine("PDF created successfully");
    }
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlFileAsPdf("input.html");
        pdf.SaveAs("output.pdf");
        Console.WriteLine("PDF created successfully");
    }
}
Imports IronPdf
Imports System

Class Program
    Shared Sub Main()
        Dim renderer = New ChromePdfRenderer()
        Dim pdf = renderer.RenderHtmlFileAsPdf("input.html")
        pdf.SaveAs("output.pdf")
        Console.WriteLine("PDF created successfully")
    End Sub
End Class
$vbLabelText   $csharpLabel

合併多個 PDF

Aspose.PDF需要手動遍歷頁面。 IronPDF提供了一個靜態的Merge方法。

Aspose.PDF實現:

// NuGet: Install-Package Aspose.PDF
using Aspose.Pdf;
using System;

class Program
{
    static void Main()
    {
        var document1 = new Document("file1.pdf");
        var document2 = new Document("file2.pdf");

        foreach (Page page in document2.Pages)
        {
            document1.Pages.Add(page);
        }

        document1.Save("merged.pdf");
        Console.WriteLine("PDFs merged successfully");
    }
}
// NuGet: Install-Package Aspose.PDF
using Aspose.Pdf;
using System;

class Program
{
    static void Main()
    {
        var document1 = new Document("file1.pdf");
        var document2 = new Document("file2.pdf");

        foreach (Page page in document2.Pages)
        {
            document1.Pages.Add(page);
        }

        document1.Save("merged.pdf");
        Console.WriteLine("PDFs merged successfully");
    }
}
Imports Aspose.Pdf
Imports System

Class Program
    Shared Sub Main()
        Dim document1 As New Document("file1.pdf")
        Dim document2 As New Document("file2.pdf")

        For Each page As Page In document2.Pages
            document1.Pages.Add(page)
        Next

        document1.Save("merged.pdf")
        Console.WriteLine("PDFs merged successfully")
    End Sub
End Class
$vbLabelText   $csharpLabel

IronPDF實現:

// NuGet: Install-Package IronPdf
using IronPdf;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var pdf1 = PdfDocument.FromFile("file1.pdf");
        var pdf2 = PdfDocument.FromFile("file2.pdf");

        var merged = PdfDocument.Merge(pdf1, pdf2);
        merged.SaveAs("merged.pdf");

        Console.WriteLine("PDFs merged successfully");
    }
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var pdf1 = PdfDocument.FromFile("file1.pdf");
        var pdf2 = PdfDocument.FromFile("file2.pdf");

        var merged = PdfDocument.Merge(pdf1, pdf2);
        merged.SaveAs("merged.pdf");

        Console.WriteLine("PDFs merged successfully");
    }
}
Imports IronPdf
Imports System
Imports System.Collections.Generic

Module Program
    Sub Main()
        Dim pdf1 = PdfDocument.FromFile("file1.pdf")
        Dim pdf2 = PdfDocument.FromFile("file2.pdf")

        Dim merged = PdfDocument.Merge(pdf1, pdf2)
        merged.SaveAs("merged.pdf")

        Console.WriteLine("PDFs merged successfully")
    End Sub
End Module
$vbLabelText   $csharpLabel

文字提取

Aspose.PDF實現:

using Aspose.Pdf;
using Aspose.Pdf.Text;

var document = new Document("document.pdf");
var absorber = new TextAbsorber();

foreach (Page page in document.Pages)
{
    page.Accept(absorber);
}

string extractedText = absorber.Text;
Console.WriteLine(extractedText);
using Aspose.Pdf;
using Aspose.Pdf.Text;

var document = new Document("document.pdf");
var absorber = new TextAbsorber();

foreach (Page page in document.Pages)
{
    page.Accept(absorber);
}

string extractedText = absorber.Text;
Console.WriteLine(extractedText);
Imports Aspose.Pdf
Imports Aspose.Pdf.Text

Dim document As New Document("document.pdf")
Dim absorber As New TextAbsorber()

For Each page As Page In document.Pages
    page.Accept(absorber)
Next

Dim extractedText As String = absorber.Text
Console.WriteLine(extractedText)
$vbLabelText   $csharpLabel

IronPDF實現:

using IronPdf;

var pdf = PdfDocument.FromFile("document.pdf");

// Extract all text - one line!
string allText = pdf.ExtractAllText();
Console.WriteLine(allText);

// Or extract from specific page
string page1Text = pdf.ExtractTextFromPage(0);
using IronPdf;

var pdf = PdfDocument.FromFile("document.pdf");

// Extract all text - one line!
string allText = pdf.ExtractAllText();
Console.WriteLine(allText);

// Or extract from specific page
string page1Text = pdf.ExtractTextFromPage(0);
Imports IronPdf

Dim pdf = PdfDocument.FromFile("document.pdf")

' Extract all text - one line!
Dim allText As String = pdf.ExtractAllText()
Console.WriteLine(allText)

' Or extract from specific page
Dim page1Text As String = pdf.ExtractTextFromPage(0)
$vbLabelText   $csharpLabel

IronPDF簡化了從多個步驟提取文字為單個方法調用。

新增水印

Aspose.PDF實現:

using Aspose.Pdf;
using Aspose.Pdf.Text;

var document = new Document("document.pdf");

var textStamp = new TextStamp("CONFIDENTIAL");
textStamp.Background = true;
textStamp.XIndent = 100;
textStamp.YIndent = 100;
textStamp.Rotate = Rotation.on45;
textStamp.Opacity = 0.5;
textStamp.TextState.Font = FontRepository.FindFont("Arial");
textStamp.TextState.FontSize = 72;
textStamp.TextState.ForegroundColor = Color.Red;

foreach (Page page in document.Pages)
{
    page.AddStamp(textStamp);
}

document.Save("watermarked.pdf");
using Aspose.Pdf;
using Aspose.Pdf.Text;

var document = new Document("document.pdf");

var textStamp = new TextStamp("CONFIDENTIAL");
textStamp.Background = true;
textStamp.XIndent = 100;
textStamp.YIndent = 100;
textStamp.Rotate = Rotation.on45;
textStamp.Opacity = 0.5;
textStamp.TextState.Font = FontRepository.FindFont("Arial");
textStamp.TextState.FontSize = 72;
textStamp.TextState.ForegroundColor = Color.Red;

foreach (Page page in document.Pages)
{
    page.AddStamp(textStamp);
}

document.Save("watermarked.pdf");
Imports Aspose.Pdf
Imports Aspose.Pdf.Text

Dim document As New Document("document.pdf")

Dim textStamp As New TextStamp("CONFIDENTIAL")
textStamp.Background = True
textStamp.XIndent = 100
textStamp.YIndent = 100
textStamp.Rotate = Rotation.on45
textStamp.Opacity = 0.5
textStamp.TextState.Font = FontRepository.FindFont("Arial")
textStamp.TextState.FontSize = 72
textStamp.TextState.ForegroundColor = Color.Red

For Each page As Page In document.Pages
    page.AddStamp(textStamp)
Next

document.Save("watermarked.pdf")
$vbLabelText   $csharpLabel

IronPDF實現:

using IronPdf;
using IronPdf.Editing;

var pdf = PdfDocument.FromFile("document.pdf");

// HTML-based watermark with full styling control
string watermarkHtml = @"
<div style='
    color: red;
    opacity: 0.5;
    font-family: Arial;
    font-size: 72px;
    font-weight: bold;
    text-align: center;
'>CONFIDENTIAL</div>";

pdf.ApplyWatermark(watermarkHtml,
    rotation: 45,
    verticalAlignment: VerticalAlignment.Middle,
    horizontalAlignment: HorizontalAlignment.Center);

pdf.SaveAs("watermarked.pdf");
using IronPdf;
using IronPdf.Editing;

var pdf = PdfDocument.FromFile("document.pdf");

// HTML-based watermark with full styling control
string watermarkHtml = @"
<div style='
    color: red;
    opacity: 0.5;
    font-family: Arial;
    font-size: 72px;
    font-weight: bold;
    text-align: center;
'>CONFIDENTIAL</div>";

pdf.ApplyWatermark(watermarkHtml,
    rotation: 45,
    verticalAlignment: VerticalAlignment.Middle,
    horizontalAlignment: HorizontalAlignment.Center);

pdf.SaveAs("watermarked.pdf");
Imports IronPdf
Imports IronPdf.Editing

Dim pdf = PdfDocument.FromFile("document.pdf")

' HTML-based watermark with full styling control
Dim watermarkHtml As String = "
<div style='
    color: red;
    opacity: 0.5;
    font-family: Arial;
    font-size: 72px;
    font-weight: bold;
    text-align: center;
'>CONFIDENTIAL</div>"

pdf.ApplyWatermark(watermarkHtml,
    rotation:=45,
    verticalAlignment:=VerticalAlignment.Middle,
    horizontalAlignment:=HorizontalAlignment.Center)

pdf.SaveAs("watermarked.pdf")
$vbLabelText   $csharpLabel

IronPDF使用基於HTML/CSS的水印功能,通過熟悉的網頁技術提供完整的樣式控制。

密碼保護

Aspose.PDF實現:

using Aspose.Pdf;

var document = new Document("document.pdf");
document.Encrypt("userPassword", "ownerPassword", DocumentPrivilege.ForbidAll, CryptoAlgorithm.AESx256);
document.Save("protected.pdf");
using Aspose.Pdf;

var document = new Document("document.pdf");
document.Encrypt("userPassword", "ownerPassword", DocumentPrivilege.ForbidAll, CryptoAlgorithm.AESx256);
document.Save("protected.pdf");
Imports Aspose.Pdf

Dim document As New Document("document.pdf")
document.Encrypt("userPassword", "ownerPassword", DocumentPrivilege.ForbidAll, CryptoAlgorithm.AESx256)
document.Save("protected.pdf")
$vbLabelText   $csharpLabel

IronPDF實現:

using IronPdf;

var pdf = PdfDocument.FromFile("document.pdf");

// Set passwords
pdf.SecuritySettings.UserPassword = "userPassword";
pdf.SecuritySettings.OwnerPassword = "ownerPassword";

// Set permissions
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserEdits = PdfEditSecurity.NoEdit;

pdf.SaveAs("protected.pdf");
using IronPdf;

var pdf = PdfDocument.FromFile("document.pdf");

// Set passwords
pdf.SecuritySettings.UserPassword = "userPassword";
pdf.SecuritySettings.OwnerPassword = "ownerPassword";

// Set permissions
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserEdits = PdfEditSecurity.NoEdit;

pdf.SaveAs("protected.pdf");
Imports IronPdf

Dim pdf = PdfDocument.FromFile("document.pdf")

' Set passwords
pdf.SecuritySettings.UserPassword = "userPassword"
pdf.SecuritySettings.OwnerPassword = "ownerPassword"

' Set permissions
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserEdits = PdfEditSecurity.NoEdit

pdf.SaveAs("protected.pdf")
$vbLabelText   $csharpLabel

IronPDF透過強型別屬性提供了對權限的細粒度控制。 更多選項請參見加密文件

頭部和尾部

IronPDF實現:

using IronPdf;

var renderer = new ChromePdfRenderer();

renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    HtmlFragment = @"
        <div style='text-align:center; font-family:Arial; font-size:12px;'>
            Company Header
        </div>",
    DrawDividerLine = true,
    MaxHeight = 30
};

renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
    HtmlFragment = @"
        <div style='text-align:center; font-family:Arial; font-size:10px;'>
            Page {page} of {total-pages}
        </div>",
    DrawDividerLine = true,
    MaxHeight = 25
};

var pdf = renderer.RenderHtmlAsPdf("<h1>Content here</h1>");
pdf.SaveAs("with_headers.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    HtmlFragment = @"
        <div style='text-align:center; font-family:Arial; font-size:12px;'>
            Company Header
        </div>",
    DrawDividerLine = true,
    MaxHeight = 30
};

renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
    HtmlFragment = @"
        <div style='text-align:center; font-family:Arial; font-size:10px;'>
            Page {page} of {total-pages}
        </div>",
    DrawDividerLine = true,
    MaxHeight = 25
};

var pdf = renderer.RenderHtmlAsPdf("<h1>Content here</h1>");
pdf.SaveAs("with_headers.pdf");
Imports IronPdf

Dim renderer As New ChromePdfRenderer()

renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
    .HtmlFragment = "
        <div style='text-align:center; font-family:Arial; font-size:12px;'>
            Company Header
        </div>",
    .DrawDividerLine = True,
    .MaxHeight = 30
}

renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter With {
    .HtmlFragment = "
        <div style='text-align:center; font-family:Arial; font-size:10px;'>
            Page {page} of {total-pages}
        </div>",
    .DrawDividerLine = True,
    .MaxHeight = 25
}

Dim pdf = renderer.RenderHtmlAsPdf("<h1>Content here</h1>")
pdf.SaveAs("with_headers.pdf")
$vbLabelText   $csharpLabel

IronPDF支援占位符標記如{total-pages}以進行動態頁碼。 欲了解更多選項,請參見 頁眉和頁腳文件

關鍵遷移注意事項

頁碼編索變更

Aspose.PDF使用基於1的編索。 IronPDF使用基於0的編索:

// Aspose.PDF - 1-based indexing
var firstPage = doc.Pages[1];  // First page
var thirdPage = doc.Pages[3];  // Third page

//IronPDF- 0-based indexing
var firstPage = pdf.Pages[0];  // First page
var thirdPage = pdf.Pages[2];  // Third page
// Aspose.PDF - 1-based indexing
var firstPage = doc.Pages[1];  // First page
var thirdPage = doc.Pages[3];  // Third page

//IronPDF- 0-based indexing
var firstPage = pdf.Pages[0];  // First page
var thirdPage = pdf.Pages[2];  // Third page
Imports Aspose.Pdf
Imports IronPdf

' Aspose.PDF - 1-based indexing
Dim firstPageAspose = doc.Pages(1)  ' First page
Dim thirdPageAspose = doc.Pages(3)  ' Third page

' IronPDF - 0-based indexing
Dim firstPageIron = pdf.Pages(0)  ' First page
Dim thirdPageIron = pdf.Pages(2)  ' Third page
$vbLabelText   $csharpLabel

授權文件到程式碼金鑰

.lic文件授權替換為基於程式碼的激活:

// Aspose.PDF
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.Pdf.lic");

// IronPDF
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// Or from environment variable
IronPdf.License.LicenseKey = Environment.GetEnvironmentVariable("IRONPDF_LICENSE_KEY");
// Aspose.PDF
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.Pdf.lic");

// IronPDF
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// Or from environment variable
IronPdf.License.LicenseKey = Environment.GetEnvironmentVariable("IRONPDF_LICENSE_KEY");
Imports Aspose.Pdf
Imports System

Dim license As New License()
license.SetLicense("Aspose.Pdf.lic")

IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
' Or from environment variable
IronPdf.License.LicenseKey = Environment.GetEnvironmentVariable("IRONPDF_LICENSE_KEY")
$vbLabelText   $csharpLabel

ASP.NET Core 整合

IronPDF模式:

[ApiController]
[Route("[controller]")]
public class PdfController : ControllerBase
{
    [HttpGet("generate")]
    public IActionResult GeneratePdf()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Report</h1>");

        return File(pdf.BinaryData, "application/pdf", "report.pdf");
    }

    [HttpGet("generate-async")]
    public async Task<IActionResult> GeneratePdfAsync()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Report</h1>");

        return File(pdf.BinaryData, "application/pdf", "report.pdf");
    }
}
[ApiController]
[Route("[controller]")]
public class PdfController : ControllerBase
{
    [HttpGet("generate")]
    public IActionResult GeneratePdf()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Report</h1>");

        return File(pdf.BinaryData, "application/pdf", "report.pdf");
    }

    [HttpGet("generate-async")]
    public async Task<IActionResult> GeneratePdfAsync()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Report</h1>");

        return File(pdf.BinaryData, "application/pdf", "report.pdf");
    }
}
Imports Microsoft.AspNetCore.Mvc

<ApiController>
<Route("[controller]")>
Public Class PdfController
    Inherits ControllerBase

    <HttpGet("generate")>
    Public Function GeneratePdf() As IActionResult
        Dim renderer = New ChromePdfRenderer()
        Dim pdf = renderer.RenderHtmlAsPdf("<h1>Report</h1>")

        Return File(pdf.BinaryData, "application/pdf", "report.pdf")
    End Function

    <HttpGet("generate-async")>
    Public Async Function GeneratePdfAsync() As Task(Of IActionResult)
        Dim renderer = New ChromePdfRenderer()
        Dim pdf = Await renderer.RenderHtmlAsPdfAsync("<h1>Report</h1>")

        Return File(pdf.BinaryData, "application/pdf", "report.pdf")
    End Function
End Class
$vbLabelText   $csharpLabel

依賴注入配置

// Program.cs
public void ConfigureServices(IServiceCollection services)
{
    // Set license once
    IronPdf.License.LicenseKey = Configuration["IronPdf:LicenseKey"];

    // Register renderer as scoped service
    services.AddScoped<ChromePdfRenderer>();
}
// Program.cs
public void ConfigureServices(IServiceCollection services)
{
    // Set license once
    IronPdf.License.LicenseKey = Configuration["IronPdf:LicenseKey"];

    // Register renderer as scoped service
    services.AddScoped<ChromePdfRenderer>();
}
' Program.vb
Public Sub ConfigureServices(services As IServiceCollection)
    ' Set license once
    IronPdf.License.LicenseKey = Configuration("IronPdf:LicenseKey")

    ' Register renderer as scoped service
    services.AddScoped(Of ChromePdfRenderer)()
End Sub
$vbLabelText   $csharpLabel

性能優化

// 1. Reuse renderer instance
private static readonly ChromePdfRenderer SharedRenderer = new ChromePdfRenderer();

// 2. Disable unnecessary features for speed
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = false; // If not needed
renderer.RenderingOptions.WaitFor.RenderDelay(0);   // No delay
renderer.RenderingOptions.Timeout = 30000;          // 30s max

// 3. Proper disposal
using (var pdf = renderer.RenderHtmlAsPdf(html))
{
    pdf.SaveAs("output.pdf");
}
// 1. Reuse renderer instance
private static readonly ChromePdfRenderer SharedRenderer = new ChromePdfRenderer();

// 2. Disable unnecessary features for speed
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = false; // If not needed
renderer.RenderingOptions.WaitFor.RenderDelay(0);   // No delay
renderer.RenderingOptions.Timeout = 30000;          // 30s max

// 3. Proper disposal
using (var pdf = renderer.RenderHtmlAsPdf(html))
{
    pdf.SaveAs("output.pdf");
}
' 1. Reuse renderer instance
Private Shared ReadOnly SharedRenderer As New ChromePdfRenderer()

' 2. Disable unnecessary features for speed
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.EnableJavaScript = False ' If not needed
renderer.RenderingOptions.WaitFor.RenderDelay(0)   ' No delay
renderer.RenderingOptions.Timeout = 30000          ' 30s max

' 3. Proper disposal
Using pdf = renderer.RenderHtmlAsPdf(html)
    pdf.SaveAs("output.pdf")
End Using
$vbLabelText   $csharpLabel

故障排除常見的遷移問題

問題:HtmlLoadOptions找不到

ChromePdfRenderer替換:

// Remove this
var doc = new Document(stream, new HtmlLoadOptions());

// Use this
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlString);
// Remove this
var doc = new Document(stream, new HtmlLoadOptions());

// Use this
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlString);
Dim doc = New Document(stream, New HtmlLoadOptions())

Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlString)
$vbLabelText   $csharpLabel

問題:TextFragmentAbsorber找不到

直接使用文字提取:

// Remove this
var absorber = new TextFragmentAbsorber();
page.Accept(absorber);
string text = absorber.Text;

// Use this
var pdf = PdfDocument.FromFile("doc.pdf");
string text = pdf.ExtractAllText();
// Remove this
var absorber = new TextFragmentAbsorber();
page.Accept(absorber);
string text = absorber.Text;

// Use this
var pdf = PdfDocument.FromFile("doc.pdf");
string text = pdf.ExtractAllText();
' Remove this
Dim absorber As New TextFragmentAbsorber()
page.Accept(absorber)
Dim text As String = absorber.Text

' Use this
Dim pdf = PdfDocument.FromFile("doc.pdf")
Dim text As String = pdf.ExtractAllText()
$vbLabelText   $csharpLabel

問題:PdfFileEditor.Concatenate不可用

使用PdfDocument.Merge()

// Remove this
var editor = new PdfFileEditor();
editor.Concatenate(files, output);

// Use this
var pdfs = files.Select(PdfDocument.FromFile).ToList();
var merged = PdfDocument.Merge(pdfs);
merged.SaveAs(output);
// Remove this
var editor = new PdfFileEditor();
editor.Concatenate(files, output);

// Use this
var pdfs = files.Select(PdfDocument.FromFile).ToList();
var merged = PdfDocument.Merge(pdfs);
merged.SaveAs(output);
' Remove this
Dim editor = New PdfFileEditor()
editor.Concatenate(files, output)

' Use this
Dim pdfs = files.Select(Function(file) PdfDocument.FromFile(file)).ToList()
Dim merged = PdfDocument.Merge(pdfs)
merged.SaveAs(output)
$vbLabelText   $csharpLabel

後遷移檢查清單

完成程式碼遷移後,請驗證以下內容:

  • 移除Aspose.PDF授權文件(.lic)
  • 驗證HTML渲染品質(CSS Grid,Flexbox應能正常運行)
  • 測試具有大型文件和複雜CSS的極端情況
  • 更新頁碼索引引用(基於1到基於0)
  • 更新 Docker 配置(如適用)
  • 更新CI/CD管道的新許可金鑰配置
  • 為您的團隊記錄新模式

其他資源


從Aspose.PDF遷移到IronPDF將使您的程式碼基礎從內部HTML引擎轉移到基於Chromium的渲染。 MemoryStream包裝器的消除,簡化的文字提取以及更廣泛的CSS3支援立即帶來了生產力提升,IronPDF的程式碼授權金鑰取代了.lic 文件處理。

請注意Aspose是其各自所有者的註冊商標。 本網站未與Aspose Pty Ltd相關聯,未被其認可或贊助。所有產品名稱,標誌和品牌均為其各自所有者的財產。 比較僅供參考,反映撰寫時公開可用的資訊。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話