IRONSOFTWAREHOME
视频

如何在ASP.NET MVC视图中转换HTML为PDF

Curtis Chau
Curtis Chau
Updated: 2026年7月19日

从PDFsharp迁移到IronPDF将您的PDF生成工作流从手动基于坐标的绘图转换为现代HTML/CSS模板。 本指南提供了一个逐步迁移路径,用web技术替换GDI+风格的定位,缩短开发时间,通过标准HTML/CSS技能使PDF生成可维护。

为什么要从PDFsharp迁移到IronPDF

了解PDFsharp

PDFsharp是一个低级别的PDF创建库,允许开发人员以编程方式生成PDF文档。 在MIT许可证下发布并由PDFsharp-Team(最初为empira Software GmbH)维护,PDFsharp 6.x面向.NET 8/9/10和.NET Standard 2.0,通过Core版本跨平台运行于Windows、Linux和macOS。 PDFsharp主要用作从头绘制和编译PDF的工具,使用GDI+样式的API,这可以是有利的,也可能因项目性质而受限。

PDFsharp有时被错误地认为是HTML到PDF的转换器,实际上并不是。 其目的仅限于编程式 PDF 文档创建。 虽有一个社区插件HtmlRenderer.PdfSharp(由ArthurHub开发),旨在提供HTML渲染功能,但它仅覆盖HTML 4.01/CSS级别2——没有现代CSS特性如flexbox、grid或JavaScript。

坐标计算问题

PDFsharp的GDI+方法要求您:

  • 为每个元素计算精确的 X、Y 位置
  • 手动跟踪页面溢出的内容高度
  • 自行处理换行和文本测量
  • 通过边框计算逐格绘制表格
  • 使用手动分页功能管理多页文档

PDFsharp的架构需要深入理解使用坐标的位置定位,经常在创建复杂布局时带来挑战。

###PDFsharpvs IronPDF比较

特征PDFsharpIronPDF
许可麻省理工学院(免费)商业翻译
HTML 转 PDF 支持是(支持 HTML5/CSS3)
现代 CSS 支持不支持(通过HtmlRenderer插件支持HTML 4.01 / CSS 2)是(全 CSS3)
文档创建基于坐标的绘图HTML/CSS 模板
布局系统手动 X、Y 定位CSS Flow/Flexbox/Grid
分页符手工计算自动 + CSS 控制
表格单独绘制单元格HTML <table>
样式基于代码的字体/颜色CSS 样式表
文档应用程序接口低级(需要坐标)高级(简化 API)
更新活跃(6.x系列)常规翻译

IronPDF 在需要将 HTML 文档完全忠实地转换为 PDF 的场景中大显身手。 该 .NET 库支持 HTML5 和 CSS3,确保符合现代网络标准。 其本地 HTML 转 PDF 功能意味着开发人员可以利用现有的网页内容或使用当代网络工具设计的模板。

对于使用现代.NET的团队,IronPDF提供了一种消除坐标计算同时利用web开发技能的方法。


开始之前

前提条件

  1. .NET 环境: .NET Framework 4.6.2+ 或 .NET Core 3.1+ / .NET 5/6/7/8/9+
  2. **NuGet 访问权限:**能够安装 NuGet 包
  3. **IronPDF 许可证:**请从ironpdf.com获取您的许可证密钥。

NuGet 软件包变更

# RemovePDFsharp(official PDFsharp-Team package IDs; case-sensitive on case-sensitive feeds)
dotnet remove package PDFsharp
# dotnet remove package PDFsharp-WPF        # if you used the WPF build
# dotnet remove package PDFsharp-GDI        # if you used the GDI build
# dotnet remove package PDFsharp-MigraDoc   # if you used MigraDoc on top
# dotnet remove package PdfSharpCore        # community .NET Standard port

# Add IronPDF
dotnet add package IronPdf
SHELL

许可配置

// Add at application startup (Program.cs or Startup.cs)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";

识别PDFsharp的使用

# Find allPDFsharpusages in your codebase
grep -r "PdfSharp\|XGraphics\|XFont\|XBrush\|XPen" --include="*.cs" .
SHELL

完整的 API 参考

命名空间变更

// Before: PDFsharp
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using PdfSharp.Pdf.IO;

// After: IronPDF
using IronPdf;
using IronPdf.Editing;

核心 API 映射

PDFsharp APIIronPDF API
new PdfDocument()ChromePdfRenderer.RenderHtmlAsPdf()
document.AddPage()自动翻译
XGraphics.FromPdfPage()不需要
XGraphics.DrawString()HTML <p>, <h1>, 等等
XGraphics.DrawImage()HTML <img> 标签
XFontCSS font-family, font-size
XBrush, XPenCSS 颜色/边框
document.Save()pdf.SaveAs()
PdfReader.Open()PdfDocument.FromFile()

代码迁移示例

示例 1:HTML 到 PDF 的转换

此前(PDFsharp):

// NuGet: Install-PackagePDFsharp (official PDFsharp-Team package, MIT)
//PDFsharpdoes NOT support HTML-to-PDF natively. The community add-on
// HtmlRenderer.PdfSharp covers HTML 4.01 / CSS level 2 only (no flexbox, grid, JS).
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System;

class Program
{
    static void Main()
    {
        //PDFsharpdoes not have built-inHTML 至 PDFconversion
        // You need to manually parse HTML and render content
        PdfDocument document = new PdfDocument();
        PdfPage page = document.AddPage();
        XGraphics gfx = XGraphics.FromPdfPage(page);
        XFont font = new XFont("Arial", 12);
        
        // 手册 text rendering (no HTML support)
        gfx.DrawString("Hello from PDFsharp", font, XBrushes.Black,
            new XRect(0, 0, page.Width, page.Height),
            XStringFormats.TopLeft);
        
        document.Save("output.pdf");
    }
}
C#

After (IronPDF):

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

class Program
{
    static void Main()
    {
        //IronPDFhas nativeHTML 至 PDFrendering
        var renderer = new ChromePdfRenderer();
        
        string html = "<h1>Hello from IronPDF</h1><p>EasyHTML 至 PDFconversion</p>";
        var pdf = renderer.RenderHtmlAsPdf(html);
        
        pdf.SaveAs("output.pdf");
    }
}
C#

这个例子突出了两个库之间最显著的区别。 PDFsharp不提供内置的HTML到PDF转换——您必须手动创建一个XRect坐标。

IronPDF通过ChromePdfRenderer提供原生的HTML到PDF渲染。 RenderHtmlAsPdf()方法接受HTML字符串,并在内部使用一个Chromium引擎进行转换。IronPDF可轻松将 HTML 文件转换为 PDF,保留 HTML5 和 CSS3 中定义的所有样式,无需进行坐标计算。 请参阅 HTML 转 PDF 文档,了解全面的示例。

示例 2:在现有 PDF 中添加文本/水印

此前(PDFsharp):

// NuGet: Install-PackagePDFsharp (official PDFsharp-Team package, MIT)
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Drawing;
using System;

class Program
{
    static void Main()
    {
        // Open existing PDF
        PdfDocument document = PdfReader.Open("existing.pdf", PdfDocumentOpenMode.Modify);
        PdfPage page = document.Pages[0];
        
        // Get graphics object
        XGraphics gfx = XGraphics.FromPdfPage(page);
        // Note: inPDFsharp6.x, XFontStyle was renamed to XFontStyleEx
        XFont font = new XFont("Arial", 20, XFontStyleEx.Bold);
        
        // Draw text at specific position
        gfx.DrawString("Watermark Text", font, XBrushes.Red,
            new XPoint(200, 400));
        
        document.Save("modified.pdf");
    }
}
C#

After (IronPDF):

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

class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";

        // Open existing PDF
        var pdf = PdfDocument.FromFile("existing.pdf");
        
        // Add text stamp/watermark
        var textStamper = new TextStamper()
        {
            Text = "Watermark Text",
            FontSize = 20,
            FontFamily = "Arial",
            IsBold = true,
            FontColor = IronSoftware.Drawing.Color.Red,
            VerticalAlignment = VerticalAlignment.Middle,
            HorizontalAlignment = HorizontalAlignment.Center
        };
        
        pdf.ApplyStamp(textStamper);
        pdf.SaveAs("modified.pdf");
    }
}
C#

PDFsharp需要使用XPoint来指定精确的X,Y坐标(200, 400)。

IronPDF通过TextStamper, Text, FontSize, FontFamily, IsBold, FontColor, VerticalAlignment, HorizontalAlignment, ApplyStamp())的PdfDocument对象。 无需坐标计算--只需指定对齐方式,IronPDF 即可处理定位。 注意需要IronPdf.Editing命名空间以实现印章功能。

示例 3:使用图像创建 PDF.

此前(PDFsharp):

// NuGet: Install-PackagePDFsharp (official PDFsharp-Team package, MIT)
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System;

class Program
{
    static void Main()
    {
        // Create new PDF document
        PdfDocument document = new PdfDocument();
        PdfPage page = document.AddPage();
        XGraphics gfx = XGraphics.FromPdfPage(page);
        
        // Load and draw image
        XImage image = XImage.FromFile("image.jpg");
        
        // Calculate size to fit page
        double width = 200;
        double height = 200;
        
        gfx.DrawImage(image, 50, 50, width, height);
        
        // Add text
        XFont font = new XFont("Arial", 16);
        gfx.DrawString("Image in PDF", font, XBrushes.Black,
            new XPoint(50, 270));
        
        document.Save("output.pdf");
    }
}
C#

After (IronPDF):

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

class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";

        // Create PDF from HTML with image
        var renderer = new ChromePdfRenderer();
        
        string html = @"
            <h1>Image in PDF</h1>
            <img src='image.jpg' style='width:200px; height:200px;' />
            <p>Easy image embedding with HTML</p>";
        
        var pdf = renderer.RenderHtmlAsPdf(html);
        pdf.SaveAs("output.pdf");
        
        // Alternative: Add image to existing PDF
        var existingPdf = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Document</h1>");
        var imageStamper = new IronPdf.Editing.ImageStamper(new Uri("image.jpg"))
        {
            VerticalAlignment = IronPdf.Editing.VerticalAlignment.Top
        };
        existingPdf.ApplyStamp(imageStamper);
    }
}
C#

PDFsharp需要创建一个新的DrawImage()与精确坐标(50, 50, 200, 200),然后单独使用DrawString()添加文本。

IronPDF 使用标准HTML与一个<img>标签和CSS样式(style='width:200px;') 高度:200px;')。 无需进行坐标计算--由 CSS 处理布局。IronPDF还提供ImageStamper`用于将图像添加到现有的PDF中,并具有声明性对齐属性。 在我们的教程中了解更多信息。


关键迁移说明

范式转换:坐标到 HTML/CSS.

最大的变化是从基于坐标的绘图转向 HTML/CSS:

// PDFsharp: manual positioning
gfx.DrawString("Invoice", titleFont, XBrushes.Black, new XPoint(50, 50));
gfx.DrawString("Customer: John", bodyFont, XBrushes.Black, new XPoint(50, 80));

// IronPDF: let CSS handle layout
var html = @"
<div style='padding: 50px;'>
    <h1>Invoice</h1>
    <p>Customer: John</p>
</div>";
var pdf = renderer.RenderHtmlAsPdf(html);

字体迁移

// PDFsharp: XFont objects (PDFsharp 6.x renamed XFontStyle to XFontStyleEx)
var titleFont = new XFont("Arial", 24, XFontStyleEx.Bold);
var bodyFont = new XFont("Times New Roman", 12);

// IronPDF: CSS font properties
var html = @"
<style>
    h1 { font-family: Arial, sans-serif; font-size: 24px; font-weight: bold; }
    p { font-family: 'Times New Roman', serif; font-size: 12px; }
</style>";

文档加载更改

// PDFsharp: PdfReader.Open()
PdfDocument document = PdfReader.Open("existing.pdf", PdfDocumentOpenMode.Modify);

// IronPDF: PdfDocument.FromFile()
var pdf = PdfDocument.FromFile("existing.pdf");

保存方法更改

// PDFsharp: document.Save()
document.Save("output.pdf");

// IronPDF: pdf.SaveAs()
pdf.SaveAs("output.pdf");

页面访问更改

// PDFsharp: document.Pages[0]
PdfPage page = document.Pages[0];

// IronPDF:自动翻译page handling or pdf.Pages[0]
// Pages are created automatically from HTML content
C#

迁移后的新功能

迁移到IronPDF后,您将获得PDFsharp无法提供的功能:

将原生 HTML 转换为 PDF.

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Modern Web Content</h1>");

URL到PDF

var pdf = renderer.RenderUrlAsPdf("https://example.com");

PDF 合并

var pdf1 = PdfDocument.FromFile("document1.pdf");
var pdf2 = PdfDocument.FromFile("document2.pdf");
var merged = PdfDocument.Merge(pdf1, pdf2);

使用 HTML 的水印

pdf.ApplyWatermark("<h2 style='color:red;'>CONFIDENTIAL</h2>");

功能对比摘要

特征PDFsharpIronPDF
基于坐标的绘图✗(使用 HTML)
HTML 至 PDF
CSS3 支持
Flexbox/Grid 布局
文本冲压手册 XGraphicsTextStamper
图像冲压手册 XImageImageStamper
合并 PDF手册
URL 至 PDF
现代网络渲染Chromium 引擎
自动分页

迁移清单

迁移前

  • 检查代码库中的所有PDFsharp用例
  • 识别正在生成的文档类型(报告、发票、证书)
  • 注意任何自定义图形或绘图操作
  • 规划IronPDF许可证密钥存储(建议使用环境变量)
  • 先使用IronPDF试用许可证进行测试

软件包变更

  • 移除PDFsharp NuGet包(官方PDFsharp-Team包)
  • 移除PDFsharp-WPF, PDFsharp-GDI, 或PDFsharp-MigraDoc(如已使用)
  • 移除PdfSharpCore如果您使用了社区的.NET Standard移植版
  • 安装IronPdf NuGet包: dotnet add package IronPdf

代码更改

  • 更新命名空间导入(using PdfSharp.Pdf;using IronPdf;
  • 添加using IronPdf.Editing;以实现印章功能
  • 将基于坐标的布局转换为 HTML/CSS
  • 使用CSS字体属性替换XFont
  • 使用CSS颜色/边框替换XPen
  • 使用HTML文本元素替换XGraphics.DrawString()
  • 使用HTML <img> 标签替换XGraphics.DrawImage()
  • 使用PdfReader.Open()
  • 使用document.Save() 将表格绘制代码转换为 HTML 表格

后迁移

  • 生成PDF文件的可视化比较
  • 测试多页文档
  • 验证字体渲染
  • 根据需要添加新功能(HTML 转 PDF、合并、水印)

请注意: PDFsharp是其相应所有者的商标。 本网站与PDFsharp-Team或empira Software GmbH无关联、未获认可或赞助。 所有产品名称、徽标和品牌均为各自所有者的财产。 比较仅供参考,反映撰写时公开可用的信息。
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 天试用密钥
无需信用卡或创建账户