使用IRON SUITE

如何在C#中將CSHTML轉換為PDF

將 CSHTML 轉換為 PDF 是許多應用程式中的常見需求。 使用 C# 中的 IronPDF 庫可以輕鬆完成此任務。

IronPDF 是一個流行的 .NET 程式庫,它使開發人員能夠以程式設計方式建立、讀取、編輯和轉換 PDF 文件。 在本文中,我們將指導您完成使用IronPDF在C#中將CSHTML轉換為PDF的步驟,並附有範例。

在開始之前,讓我們先討論一些本教程所必需的重要概念。

重要概念

PDF轉換器

PDF轉換器是一種可以將任何可列印文件或網頁轉換為PDF文件的工具。 它可以用來從 HTML、Word、Excel 或任何其他可列印文件產生 PDF 文件。 PDF轉換器有多種形式,包括線上工具、桌面軟體和函式庫。

剃刀視圖

Razor 視圖是 ASP.NET Core 中用於動態產生 HTML 頁面的視圖引擎。 它是一種將 HTML 標記與 C# 程式碼結合的標記語法。

如何在 C# 中將 CSHTML 轉換為 PDF,圖 1:Razor 視圖 剃刀視圖

Razor視圖透過將表現邏輯與業務邏輯分離,使開發人員能夠輕鬆建立動態網頁。

控制器類

控制器類別是一個 C# 類,用於處理 ASP.NET Core 應用程式中傳入的 HTTP 請求。 它包含與特定 HTTP 動詞(例如 GET、POST、PUT、DELETE)對應的方法,並傳回 HTTP 回應。

NuGet 套件管理器

NuGet 套件管理器是 Visual Studio 中用於管理 .NET 專案中的套件的工具。 它使開發人員能夠在其專案中輕鬆安裝、更新和卸載軟體包。 NuGet 套件是包含可重複使用程式碼的函式庫,並透過 NuGet 套件管理器分發。

依賴注入

依賴注入是一種設計模式,它允許開發人員透過將依賴項注入到應用程式元件的類別中來解耦應用程式元件。 它透過減少依賴項和使程式碼更加模組化,使應用程式的測試和維護變得容易。

現在我們已經了解了重要的概念,讓我們深入了解使用 IronPDF 將 CSHTML 轉換為 PDF 的過程。

什麼是CSHTML?

CSHTML 代表 C# Razor Syntax HTML。 它是一種同時包含 HTML 標記和 C# 程式碼的檔案類型。 這些檔案用於 ASP.NET Core MVC 應用程式中,以定義網頁的使用者介面。 Razor 視圖引擎用於解釋 CSHTML 檔案並產生可由 Web 瀏覽器呈現的 HTML 輸出。

如何在 C# 中將 CSHTML 轉換為 PDF,圖 2:CSHTML5 CSHTML5

什麼是 IronPDF?

IronPDF 是一個功能強大的 .NET 程式庫,可讓開發人員使用 C# 建立、讀取、編輯和轉換 PDF 文件。 它是 .NET 應用程式中用於以程式設計方式產生 PDF 文件的常用工具。 IronPDF 支援多種功能,包括 PDF 產生、PDF 操作、PDF 轉換和 PDF 渲染。

如何在 C# 中將 CSHTML 轉換為 PDF,圖 3:IronPDF for .NET IronPDF for .NET

如何使用 IronPDF 在 C# 中將 CSHTML HTML 字串轉換為 PDF 文件

使用 IronPDF 將 CSHTML 轉換為 PDF 是一個簡單的過程。 該庫提供了一個方便的 API,用於將 HTML 文件轉換為 PDF 文件。 以下是使用 IronPDF 在 C# 中將 CSHTML 轉換為 PDF 的步驟:

步驟 1 安裝 IronPDF

第一步是在 C# 專案中透過 NuGet 套件管理器安裝 IronPDF 。 您可以透過下載 IronPDF.dll 檔案並將其新增至專案引用來安裝 IronPDF。 若要使用 NuGet 套件管理員安裝 IronPDF,請開啟套件管理器控制台並執行下列命令:

步驟 2 建立 CSHTML 文件

接下來,建立一個包含要轉換為 PDF 的內容的 CSHTML 檔案。 在這個範例中,我們將建立一個簡單的CSHTML 教學文件,其中顯示文字"Hello, World!"。

@{
    Layout = null;
}
Hello
Hello, World!
@{
    Layout = null;
}
Hello
Hello, World!
@
If True Then
	Layout = Nothing
End If
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Hello Hello, World!
$vbLabelText   $csharpLabel

將此檔案儲存為"Hello.cshtml"到您的專案目錄中。

如何在 C# 中將 CSHTML 轉換為 PDF,圖 4:C# 中的 PDF 文件 C# 中的 PDF 文件

步驟 3:將 CSHTML 轉換為 PDF 文檔

要將CSHTML 文件轉換為 PDF文件,我們將使用 C# 中的 IronPDF 庫。 以下是將"Hello.cshtml"轉換為PDF的程式碼:

using System.IO;
using IronPdf;
using Microsoft.AspNetCore.Mvc;

namespace CSHTMLtoPDF.Controllers
{
    public class HomeController : Controller
    {
        private readonly IRazorViewRenderer _viewRenderService;
        public HomeController(IRazorViewRenderer viewRenderService)
        {
            _viewRenderService = viewRenderService;
        }

        public IActionResult Index()
        {
            var items = new[] { "Item 1", "Item 2", "Item 3" };
            return View(items);
        }

        public IActionResult DownloadPDF()
        {
            var items = new[] { "Item 1", "Item 2", "Item 3" };

            // Initialize a new instance of ChromePdfRenderer from IronPDF
            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Render the specified Razor view to a PDF document
            PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Index.cshtml", items);

            // Set the headers to force the browser to download the PDF
            var contentDisposition = new System.Net.Mime.ContentDisposition
            {
                FileName = "Items.pdf",
                Inline = false,
            };
            Response.Headers.Add("Content-Disposition", contentDisposition.ToString());

            // Return the PDF document to the client
            return File(pdf.BinaryData, "application/pdf");
        }
    }
}
using System.IO;
using IronPdf;
using Microsoft.AspNetCore.Mvc;

namespace CSHTMLtoPDF.Controllers
{
    public class HomeController : Controller
    {
        private readonly IRazorViewRenderer _viewRenderService;
        public HomeController(IRazorViewRenderer viewRenderService)
        {
            _viewRenderService = viewRenderService;
        }

        public IActionResult Index()
        {
            var items = new[] { "Item 1", "Item 2", "Item 3" };
            return View(items);
        }

        public IActionResult DownloadPDF()
        {
            var items = new[] { "Item 1", "Item 2", "Item 3" };

            // Initialize a new instance of ChromePdfRenderer from IronPDF
            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Render the specified Razor view to a PDF document
            PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Index.cshtml", items);

            // Set the headers to force the browser to download the PDF
            var contentDisposition = new System.Net.Mime.ContentDisposition
            {
                FileName = "Items.pdf",
                Inline = false,
            };
            Response.Headers.Add("Content-Disposition", contentDisposition.ToString());

            // Return the PDF document to the client
            return File(pdf.BinaryData, "application/pdf");
        }
    }
}
Imports System.IO
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc

Namespace CSHTMLtoPDF.Controllers
	Public Class HomeController
		Inherits Controller

		Private ReadOnly _viewRenderService As IRazorViewRenderer
		Public Sub New(ByVal viewRenderService As IRazorViewRenderer)
			_viewRenderService = viewRenderService
		End Sub

		Public Function Index() As IActionResult
			Dim items = { "Item 1", "Item 2", "Item 3" }
			Return View(items)
		End Function

		Public Function DownloadPDF() As IActionResult
			Dim items = { "Item 1", "Item 2", "Item 3" }

			' Initialize a new instance of ChromePdfRenderer from IronPDF
			Dim renderer As New ChromePdfRenderer()

			' Render the specified Razor view to a PDF document
			Dim pdf As PdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Index.cshtml", items)

			' Set the headers to force the browser to download the PDF
			Dim contentDisposition = New System.Net.Mime.ContentDisposition With {
				.FileName = "Items.pdf",
				.Inline = False
			}
			Response.Headers.Add("Content-Disposition", contentDisposition.ToString())

			' Return the PDF document to the client
			Return File(pdf.BinaryData, "application/pdf")
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

讓我們一步一步地分析這段程式碼:

  • 我們首先匯入必要的命名空間,包括 IronPDF 命名空間,其中包含 HTML 到 PDF 的轉換功能。 然後我們定義Index方法,該方法只是簡單地向 Razor 視圖傳回一個項目清單。
  • 我們定義了DownloadPDF方法,該方法負責產生 PDF 文件。
  • 我們先建立一個渲染器ChromePdfRenderer 。 然後使用RenderRazorViewToPdf擴充方法產生包含 PDF 檔案中資料的 Razor 視圖。 然後,我們設定Content-Disposition標頭,強制將 PDF 下載而不是在瀏覽器中顯示。 最後,我們使用 File 方法將 PDF 文件作為文件傳回。

這是使用 IronPDF 在 C# 中將 CSHTML 轉換為 PDF 的基本程式碼。 但是,您可以使用許多選項和設定來自訂 PDF 輸出。 讓我們來看看其中的一些選項。

自訂 PDF 輸出返回文件

IronPDF 提供了許多自訂 PDF 文件輸出的選項。 您可以設定頁面大小邊距、方向、頁首和頁尾等選項。 以下是如何自訂 PDF 輸出的範例:

using IronPdf;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize a new instance of ChromePdfRenderer
            var renderer = new ChromePdfRenderer();

            // Customize rendering options for the PDF
            renderer.RenderingOptions.MarginTop = 10;    // Set top margin in millimeters
            renderer.RenderingOptions.MarginBottom = 10; // Set bottom margin in millimeters
            renderer.RenderingOptions.MarginLeft = 20;   // Set left margin in millimeters
            renderer.RenderingOptions.MarginRight = 20;  // Set right margin in millimeters

            // Set HTML header for the PDF with a logo
            renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
            {
                MaxHeight = 20, // Height of header in millimeters
                HtmlFragment = "<img src='logo.png'>",
                BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri
            };

            // Set HTML footer for the PDF with page numbers
            renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
            {
                MaxHeight = 15, // Height of footer in millimeters
                HtmlFragment = "<center><i>{page} of {total-pages}</i></center>",
                DrawDividerLine = true // Draw a line above the footer
            };

            // Convert HTML content to PDF
            var pdf = renderer.RenderHtmlAsPdf("<div>Hello, World!</div>");

            // Save the PDF to the file system
            pdf.SaveAs("Hello.PDF");
        }
    }
}
using IronPdf;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize a new instance of ChromePdfRenderer
            var renderer = new ChromePdfRenderer();

            // Customize rendering options for the PDF
            renderer.RenderingOptions.MarginTop = 10;    // Set top margin in millimeters
            renderer.RenderingOptions.MarginBottom = 10; // Set bottom margin in millimeters
            renderer.RenderingOptions.MarginLeft = 20;   // Set left margin in millimeters
            renderer.RenderingOptions.MarginRight = 20;  // Set right margin in millimeters

            // Set HTML header for the PDF with a logo
            renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
            {
                MaxHeight = 20, // Height of header in millimeters
                HtmlFragment = "<img src='logo.png'>",
                BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri
            };

            // Set HTML footer for the PDF with page numbers
            renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
            {
                MaxHeight = 15, // Height of footer in millimeters
                HtmlFragment = "<center><i>{page} of {total-pages}</i></center>",
                DrawDividerLine = true // Draw a line above the footer
            };

            // Convert HTML content to PDF
            var pdf = renderer.RenderHtmlAsPdf("<div>Hello, World!</div>");

            // Save the PDF to the file system
            pdf.SaveAs("Hello.PDF");
        }
    }
}
Imports IronPdf

Namespace ConsoleApp
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Initialize a new instance of ChromePdfRenderer
			Dim renderer = New ChromePdfRenderer()

			' Customize rendering options for the PDF
			renderer.RenderingOptions.MarginTop = 10 ' Set top margin in millimeters
			renderer.RenderingOptions.MarginBottom = 10 ' Set bottom margin in millimeters
			renderer.RenderingOptions.MarginLeft = 20 ' Set left margin in millimeters
			renderer.RenderingOptions.MarginRight = 20 ' Set right margin in millimeters

			' Set HTML header for the PDF with a logo
			renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
				.MaxHeight = 20,
				.HtmlFragment = "<img src='logo.png'>",
				.BaseUrl = (New Uri("C:\assets\images\")).AbsoluteUri
			}

			' Set HTML footer for the PDF with page numbers
			renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {
				.MaxHeight = 15,
				.HtmlFragment = "<center><i>{page} of {total-pages}</i></center>",
				.DrawDividerLine = True
			}

			' Convert HTML content to PDF
			Dim pdf = renderer.RenderHtmlAsPdf("<div>Hello, World!</div>")

			' Save the PDF to the file system
			pdf.SaveAs("Hello.PDF")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

在這個例子中,我們首先建立一個ChromePdfRenderer類別的實例。 然後,我們使用ChromePdfRenderer類別的RenderingOptions屬性來設定各種選項。 以下是我們設定的一些選項:

  • MarginTopMarginBottomMarginLeftMarginRight :設定 PDF 文件的邊距。
  • HtmlHeader :設定 PDF 文件的頁首以顯示標誌。
  • HtmlFooter :設定 PDF 文件的頁尾以顯示頁碼和總頁數。

設定好選項後,我們呼叫RenderHtmlAsPdf方法並傳入 HTML 內容。 最後,我們將 PDF 文件儲存為名為"Hello.PDF"的檔案。

測試應用程式

所有必要的程式碼都已就緒,我們現在可以測試應用程式了。 請遵循以下步驟:

  • 按 F5 鍵或按一下 Visual Studio 中的綠色"播放"按鈕來執行應用程式。
  • 在您的 Web 瀏覽器中,導覽至http://localhost:/Home/Index ,其中 是 Visual Studio 指派的連接埠號碼。
  • 確認商品清單顯示正確。
  • 點擊"下載 PDF"連結產生並下載 PDF 文件。

如果一切正常,您應該會看到一個 PDF 文檔,其中包含您先前定義的項目清單。

使用 IronPDF 將 PDF 文件轉換為 CSHTML 文件

如何在 C# 中將 CSHTML 轉換為 PDF,圖 7:PDF 轉 CSHTML PDF 轉 CSHTML

為了示範如何使用 IronPDF 將 PDF 文件轉換為 CSHTML 文件,我們將在 Visual Studio 中建立一個新的控制台應用程序,並使用 IronPDF 將範例 PDF 文件轉換為 CSHTML 文件。請依照以下步驟操作:

步驟 1 建立一個新的控制台應用程式

開啟 Visual Studio,從選單中選擇"檔案 > 新建 > 專案",然後從專案範本清單中選擇"控制台應用程式 (.NET Framework)"或"控制台應用程式 (.NET Core)",建立一個新的控制台應用程式。

步驟 2:安裝 IronPDF NuGet 套件

接下來,我們需要在控制台應用程式中安裝IronPDF NuGet 套件。 為此,請在解決方案資源管理器中右鍵單擊項目,然後從上下文功能表中選擇"管理 NuGet 套件"。

在 NuGet 套件管理員中,搜尋"IronPDF",然後從搜尋結果中選擇"IronPDF"套件。 點選"安裝"按鈕安裝該軟體套件及其相依性。

步驟 3:將 PDF 和 CSHTML 檔案新增至專案中

在這個例子中,我們將使用一個範例 PDF 文件,並將其轉換為 CSHTML 文件。您可以使用任何您喜歡的 PDF 檔案來完成此步驟。

在解決方案資源管理器中右鍵單擊項目,然後從上下文選單中選擇"新增 > 現有項",將 PDF 檔案新增至項目。

我們還需要建立一個空的 CSHTML 文件,用於儲存轉換後的 HTML 字串。 為此,請在解決方案資源管理器中右鍵單擊項目,然後從上下文功能表中選擇"新增 > 新項目"。 從範本清單中選擇"HTML頁面",然後為檔案命名(例如"converted.cshtml"),然後按一下"新增"。

步驟 4:將 PDF 文件轉換為 CSHTML 文件

文件準備好後,我們現在可以使用 IronPDF 編寫程式碼,將 PDF 文件轉換為 CSHTML 文件。 將以下程式碼新增至控制台應用程式的 Main 方法:

using IronPdf;

namespace PdfToHtml
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the PDF file
            PdfDocument pdf = PdfDocument.FromFile("sample.PDF");

            // Convert the PDF to an HTML string
            string html = pdf.ToHtml();

            // Save the HTML string to the CSHTML file
            System.IO.File.WriteAllText("converted.cshtml", html);
        }
    }
}
using IronPdf;

namespace PdfToHtml
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the PDF file
            PdfDocument pdf = PdfDocument.FromFile("sample.PDF");

            // Convert the PDF to an HTML string
            string html = pdf.ToHtml();

            // Save the HTML string to the CSHTML file
            System.IO.File.WriteAllText("converted.cshtml", html);
        }
    }
}
Imports IronPdf

Namespace PdfToHtml
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Load the PDF file
			Dim pdf As PdfDocument = PdfDocument.FromFile("sample.PDF")

			' Convert the PDF to an HTML string
			Dim html As String = pdf.ToHtml()

			' Save the HTML string to the CSHTML file
			System.IO.File.WriteAllText("converted.cshtml", html)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

為什麼要使用 IronPDF?

IronPDF之所以受到.NET開發人員的青睞,主要有以下幾個原因:

強大的 PDF 生成功能:IronPDF 提供廣泛的功能和選項,用於以程式設計方式建立和操作 PDF 文檔,包括向 PDF 頁面添加文字、圖像和其他內容,以及合併和拆分現有 PDF 文件。

多功能的 PDF 轉換功能:IronPDF 不僅允許開發人員產生 PDF 文檔,還提供了將 PDF 轉換為 HTML 字串或 CSHTML 文件的功能。 在需要將 PDF 內容顯示在 Web 應用程式中,或從 PDF 文件中提取資料並在基於 Web 的工作流程中使用它的情況下,這會非常有用。

易於使用的 API :IronPDF 的 API 設計直觀易用,提供各種輔助方法和屬性,使開發人員能夠輕鬆地以程式方式產生和操作 PDF 文件。

強大的社區支援:IronPDF 擁有龐大且活躍的 .NET 開發人員社區,他們為 IronPDF 的開發做出貢獻,並為使用該程式庫的其他開發人員提供支援。

良好的文件:IronPDF 的文檔內容豐富且組織良好,包含詳細的 API 參考文件、教學課程和範例,使開發人員能夠輕鬆上手並學習如何使用該程式庫。

IronPDF 結合了強大的 PDF 生成和轉換功能、易於使用的 API、強大的社群支援和良好的文檔,使其成為需要在應用程式中處理 PDF 文件的 .NET 開發人員的熱門選擇。

結論

將 CSHTML 轉換為 PDF 是許多應用程式中的常見需求。 使用 IronPDF,可以用 C# 輕鬆完成這項任務。 本文透過範例,逐步介紹如何使用 IronPDF 將 CSHTML 轉換為 PDF。

我們也向您展示如何透過設定紙張大小、邊距、頁首和頁尾等各種選項來自訂 PDF 輸出。 使用 IronPDF,您可以快速輕鬆地從 CSHTML 檔案建立高品質的 PDF 文件。

無論您是需要從頭開始建立 PDF 文件、將 PDF 轉換為 HTML 字串或 CSHTML 文件,還是從 PDF 文件中提取數據,IronPDF 都提供了一個靈活直觀的 API,讓您輕鬆完成工作。

憑藉強大的社群支援和豐富的文檔,IronPDF 成為需要在應用程式中處理 PDF 的 .NET 開發人員的熱門選擇。 透過購買 Iron 軟體套裝,開發人員可以以折扣價獲得一套全面的 .NET 庫,用於處理常見的文件格式,這對於任何 .NET 開發團隊來說都極具價值。

如果你需要在 .NET 應用程式中處理 PDF 文檔,那麼 IronPDF 絕對值得考慮。 憑藉其強大的功能、易用性和多種授權選項,它是一款用途廣泛且可靠的工具,可幫助您快速有效地完成工作。