IRONSOFTWAREHOME
视频

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

Curtis Chau
Curtis Chau
Updated: 2026年1月11日

为什么要从 Aspose.PDF 迁移?

虽然 Aspose.PDF 提供了企业级的功能,但仍有一些因素促使开发团队为其 PDF 生成需求寻求现代的替代方案。

成本比较

Aspose.PDF 使用包含一年更新的永久许可证模式; 可选续订可以延长更新窗口。 来源:Aspose 定价页面

方面Aspose.PDFIronPDF
起始价格(开发者小企业)$1,199/开发者一次性 749 美元(Lite)
许可模式永久 + 一年更新; optional renewal永久许可证
开发者 OEM$3,597/开发者(无限部署)包含在较高的层级中
支持包含于所有付费层级包括
免费评估30天临时许可证(否则则有水印 + 大小限制)开发免费

HTML 渲染引擎比较

Aspose.PDF 使用内部的 HTML/CSS 渲染引擎(非 Chromium); 用户在 Aspose 论坛上报告了与现代 CSS 布局功能(如 Flexbox 和 CSS Grid)的差距。IronPDF使用嵌入的 Chromium 构建进行 HTML 到 PDF 的渲染。

特征Aspose.PDF(内部引擎)IronPDF (Chromium)
CSS3 支持部分; 现代布局功能存在差距完整的 CSS3
Flexbox/网格限制 / 不一致(根据 Aspose 论坛报道)全面支持
JavaScript语言有限的完全支持(通过 Chromium 的 V8)
网络字体部分翻译完成
现代 HTML5.部分翻译完成
渲染质量复杂布局中的变化Chrome 等效

性能特征

用户在 Aspose 支持论坛上报告了性能差异。 以下数字体现了社区上报的场景——请根据您自己的工作负载进行验证。

指标Aspose.PDFIronPDF
HTML 渲染用户在复杂的 CSS 工作负载中报告的缓慢现象优化的 Chromium 引擎
大型文档某些场景中报告的内存增长高效流
Linux 性能社区论坛中报告的高 CPU 和内存增长稳定

Aspose.PDF 与 IronPDF:主要区别

方面Aspose.PDFIronPDF
定价(入门)$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+ 或 .NET Core 3.1 / .NET 5-9
  • Visual Studio 2019+ 或带有 C# 扩展的 VS Code
  • 访问 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" .
SHELL

值得期待的重大变化

Aspose.PDF 模式更改要求
new Document() + Pages.Add()使用 HTML 渲染
HtmlLoadOptionsChromePdfRenderer.RenderHtmlAsPdf()
TextFragment + 手动定位基于 CSS 的定位
PdfFileEditor.Concatenate()PdfDocument.Merge()
TextFragmentAbsorberpdf.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
SHELL

或通过软件包管理器控制台:

Uninstall-Package Aspose.PDF
Install-Package IronPdf
PowerShell

步骤 2:更新命名空间引用

用IronPDF替换 Aspose.PDF 命名空间:

// 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;

步骤 3:更新许可配置

Aspose.PDF 使用 .lic 文件许可。IronPDF使用基于代码的简单密钥。

Aspose.PDF 的实现:

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

IronPDF 实现:

IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";

完整的 API 迁移参考

核心类映射

Aspose.PDF 类IronPDF 同等产品
DocumentPdfDocument
HtmlLoadOptionsChromePdfRenderer
TextFragmentAbsorberPdfDocument.ExtractAllText()
PdfFileEditorPdfDocument.Merge()
TextStamp / ImageStampPdfDocument.ApplyWatermark()
LicenseIronPdf.License

文档操作

Aspose.PDF 方法IronPDF 方法
new Document()new PdfDocument()
new Document(path)PdfDocument.FromFile(path)
doc.Save(path)pdf.SaveAs(path)
doc.Pages.Countpdf.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");
    }
}

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");
    }
}

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");
    }
}

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");
    }
}

合并多个 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");
    }
}

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");
    }
}

文本提取

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);

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);

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");

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");

IronPDF 使用基于 HTML/CSS 的水印技术,通过熟悉的 Web 技术提供完整的样式控制。

密码保护

Aspose.PDF 的实现:

using Aspose.Pdf;

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

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");

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");

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

许可证文件到代码密钥

用基于代码的激活替换.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");

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");
    }
}

依赖注入配置

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

    // Register renderer as scoped service
    services.AddScoped<ChromePdfRenderer>();
}

性能优化

// 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");
}

常见迁移问题的故障排除

问题:未找到 HtmlLoadOptions

替换为ChromePdfRenderer

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

// Use this
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlString);

问题:未找到 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();

问题: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);

迁移后核对表

完成代码迁移后,请验证以下内容:

  • 删除 Aspose.PDF 许可证文件(.lic)
  • 验证 HTML 渲染质量(CSS Grid、Flexbox 现在应该可以正常工作)
  • 使用大型文档和复杂的 CSS 测试极端情况
  • 更新页面索引引用(从 1 开始到 0 开始)
  • 如果需要,更新 Docker 配置
  • 使用新的许可证密钥配置更新 CI/CD 流水线
  • 为你的团队记录新模式

其他资源


从 Aspose.PDF 迁移到IronPDF后,您的代码库从内部 HTML 引擎转移到了基于 Chromium 的渲染。 消除MemoryStream包装器、简化的文本提取以及更广泛的CSS3支持带来了即时的生产力提升,而IronPDF基于代码的密钥替代了.lic 文件处理。

{i:(Aspose 是其各自所有者的注册商标。 本网站与Aspose Pty Ltd无关联,未获得其认可或赞助。所有产品名称、徽标和品牌都是其各自所有者的财产。 比较仅供参考,反映撰写时公开可用的信息。)}]

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

...
阅读更多

相关文章

Key in blue circle

立即获取免费的 30 天试用版密钥

Your trial license will be sent to your email address

无任何限制。100% 解锁。无需信用卡。

bullet_checked无需信用卡或创建账户无任何限制。100% 解锁。无需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
预约您的免费现场演示
Booking Badge

深受全球数百万工程师信赖

Iron Software 的客户徽标
获取您的无义务咨询
填写下面的表格或通过sales@ironsoftware.com
您的资料将始终保密。
深受全球数百万工程师信赖
Iron Software 的客户徽标
立即获取您的免费30 天试用密钥
无需信用卡或创建账户