IRONSOFTWAREHOME
影片

如何在 ASP.NET MVC 視圖中將 HTML 轉換為 PDF

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

從PDFsharp遷移到IronPDF,可以將您的PDF生成工作流程從手動的基於座標的繪圖轉變為現代的HTML/CSS模板。 本指南提供了一個逐步遷移路徑,用網路技術取代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主要作為一個工具,從頭開始使用GDI+樣式API繪製和編輯PDF,這可以是有益的或限制的,這取決於專案的性質。

PDFsharp有時被誤認為是HTML至PDF轉換器,其實並不是。 其目的僅限於程式化的PDF文件建立。 雖然有一個社群附加元件HtmlRenderer.PdfSharp(由ArthurHub設計),旨在提供HTML呈現能力,但它僅覆蓋HTML 4.01 / CSS等級2,沒有現代CSS功能如flexbox、grid或JavaScript。

座標計算問題

PDFsharp的GDI+方法意味著您必須:

  • 為每個元素計算精確的X,Y位置
  • 手動追蹤頁面溢出的內容高度
  • 自行處理行包裹和文字測量
  • 通過邊框計算逐個單元格繪製表格
  • 使用手動頁面分頁管理多頁文件

PDFsharp的架構需要深刻了解使用座標的定位,經常在建立複雜佈局時帶來挑戰。

PDFsharp對比IronPDF

功能PDFsharpIronPDF
授權MIT(免費)商業
HTML轉PDF支援是(HTML5/CSS3支援)
現代CSS支援否(HTML 4.01 / CSS 2通過HtmlRenderer附加元件)是(完整CSS3)
文件建立基於座標的繪圖HTML/CSS模板
佈局系統手動X,Y定位CSS Flow/Flexbox/Grid
頁面分頁手動計算自動 + CSS控制
表格分別繪製單元格HTML <table>
樣式基於程式碼的字體/顏色CSS樣式表
文件API低階(需要座標)高階(簡化API)
更新活躍(6.x線)定期

IronPDF在需要將HTML文件轉換為PDF的情況下大放異彩,滿足全部保真度。 這個.NET程式庫支援HTML5和CSS3,確保符合現代網頁標準。 其原生的HTML到PDF功能意味著開發人員可以利用現有的網頁內容或使用當代網頁工具設計的模板。

對於現代.NET的團隊,IronPDF提供了一種消除座標計算的方式,同時利用網頁開發技能。


開始之前

前提條件

  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包變更

# Remove PDFsharp (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 all PDFsharp usages 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 APIIronPDFAPI
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-Package PDFsharp  (official PDFsharp-Team package, MIT)
// PDFsharp does 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()
    {
        // PDFsharp does 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#

之後(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-Package PDFsharp  (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: in PDFsharp 6.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#

之後(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使用Text, FontSize, FontFamily, IsBold, FontColor, VerticalAlignment, ApplyStamp()。 不需座標計算 - 只需指定對齊,IronPDF即可處理定位。 請注意,IronPdf.Editing命名空間是水印功能所需的。

範例3:建立帶有圖片的PDF

之前(PDFsharp):

// NuGet: Install-Package PDFsharp  (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#

之後(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使用帶有<img>標籤的標準HTML和CSS樣式(style='width:200px; height: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-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 XGraphics.DrawImage()
  • PdfReader.Open()
  • document.Save()
  • 將表格繪圖程式碼轉換為HTML表格

遷移後

  • 生成的PDF文件的視覺比較
  • 測試多頁文件
  • 驗證字體渲染
  • 根據需要新增新功能(HTML到PDF,合併,水印)

請注意: PDFsharp是其各自所有者的商標。 本網站不隸屬於、未獲PDFsharp-Team或empira Software GmbH支持或贊助。 所有產品名稱、標誌和品牌均為其各自所有者的財產。 比較僅供參考,反映撰寫時公開可用的資訊。
Curtis Chau
技術作家

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

...
閱讀更多

相關文章

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天試用金鑰
無需信用卡或帳戶建立