IRONSOFTWAREHOME
CSHTML 轉 PDF(MVC 框架)

// PM > Install-Package IronPdf.Extensions.Mvc.Framework

public ActionResult Persons()
{
    var persons = new List<Person>
    {
    new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
    new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
    new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
    };
    if (HttpContext.Request.HttpMethod == "POST")
    {
        // Provide the path to your view file
        var viewPath = "~/Views/Home/Persons.cshtml";
        ChromePdfRenderer renderer = new ChromePdfRenderer();

        // Render Razor view to PDF document
        PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
        Response.Headers.Add("Content-Disposition", "inline");

        // View the PDF
        return File(pdf.BinaryData, "application/pdf");
    }
    return View(persons);
}
Public Function Persons() As ActionResult
    Dim persons = New List(Of Person) From {
        New Person With {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"},
        New Person With {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"},
        New Person With {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"}
    }

    If HttpContext.Request.HttpMethod = "POST" Then
        ' Provide the path to your view file
        Dim viewPath = "~/Views/Home/Persons.cshtml"
        Dim renderer As New ChromePdfRenderer()

        ' Render Razor view to PDF document
        Dim pdf As PdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons)
        Response.Headers.Add("Content-Disposition", "inline")

        ' View the PDF
        Return File(pdf.BinaryData, "application/pdf")
    End If

    Return View(persons)
End Function
NuGet Download
PM > Install-Package IronPdf
CSHTML 轉 PDF(MVC 框架)

CSHTML 轉 PDF(MVC 框架)

此程式碼範例說明如何將視圖轉換為PDF文件。

為了實現這一點,我們利用兩個程式包:IronPdf,這些包協助將視圖呈現為PDF。 IronPdf的功能,特別是讓視圖渲染為PDF。

要進行轉換,請使用RenderView方法。 該方法需要一些關鍵輸入:一個HttpContext,".cshtml"文件的路徑以及填充".cshtml"模板所需的資料。 透過調用Persons操作,您可以無縫地將當前視圖呈現為PDF文件。

此外,您還可以使用RenderingOptions類提供的完整功能集。 這些功能包括新增IronPDF的頁碼,插入使用IronPDF的文字和HTML頁眉和頁腳,以及自定義PDF紙張尺寸以滿足您的需求。 您可以靈活地進一步修改或根據需要導出生成的PDF文件。

探索CSHTML到PDF轉換指南
在 GitHub 上查看

準備開始了嗎?

Nuget Downloads 20,809,720版本:2026.9剛剛發布

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