從HTML文件在C#中建立PDF
將CSHTML轉換為PDF是許多應用程式中的常見要求。 使用IronPDF程式庫在C#中可以輕鬆完成此任務。
IronPDF是.NET的一個受歡迎的程式庫,使開發者能夠以程式方式建立、讀取、編輯和轉換PDF文件。 在本文中,我們將引導您完成使用IronPDF在C#中將CSHTML轉換為PDF的步驟,並附上範例。
在開始之前,讓我們討論一些在這個教程中必要的重要概念。
重要概念
PDF轉換器
PDF轉換器是一種將任何可列印的文件或網頁轉換為PDF文件的工具。 它可以用於從HTML、Word、Excel或任何其他可列印文件生成PDF文件。 PDF轉換器有多種形式,包括線上工具、桌面軟體和程式庫。
Razor視圖
Razor視圖是一種在ASP.NET Core中用於動態生成HTML頁面的視圖引擎。 它是一種將HTML標記和C#程式碼結合的標記語法。
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語法HTML。 它是一種型別的文件,包含HTML標記和C#程式碼。 這些文件在ASP.NET Core MVC應用程式中用於定義網頁的使用者介面。 Razor視圖引擎用於解釋CSHTML文件並生成可以由網路瀏覽器渲染的HTML輸出。
CSHTML5
什麼是IronPDF?
IronPDF是一個強大的.NET程式庫,允許開發者在C#中建立、讀取、編輯和轉換PDF文件。 它是.NET應用程式中程式生成PDF文件的受歡迎工具。 IronPDF支持廣泛的功能,包括PDF生成、PDF操作、PDF轉換和PDF渲染。
IronPDF for .NET
How to Convert CSHTML HTML string to PDF files with IronPDF in C
使用IronPDF將CSHTML轉換為PDF是一個簡單的過程。 該程式庫提供了一個方便的API,用於將HTML文件轉換為PDF文件。 以下是在C#中使用IronPDF將CSHTML轉換為PDF的步驟:
步驟1 安裝IronPDF
第一步是在您的C#項目中從NuGet封裝管理器安裝IronPDF。 您可以通過下載IronPDF.dll文件並將其新增到項目引用中來安裝IronPDF。 要使用NuGet封裝管理器安裝IronPDF,打開封裝管理器控制台並運行以下命令:
步驟2 建立CSHTML文件
接下來,建立一個CSHTML文件,其中包含您想要轉換為PDF的內容。 在此範例中,我們將建立一個簡單的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!將此文件保存為"Hello.cshtml",放在項目目錄中。
在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讓我們逐步解析此程式碼:
- 我們首先導入必要的命名空間,包括包含HTML到PDF轉換功能的IronPDF命名空間。
- 接著,我們定義
Index方法,該方法僅向Razor視圖返回一個項目列表。 - 我們定義
DownloadPDF方法,負責生成PDF文件。 - 我們首先建立一個
ChromePdfRenderer渲染器。 - 然後使用
RenderRazorViewToPdf擴展方法將包含資料的Razor視圖生成為PDF文件。 - 接著,我們設置
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在此範例中,我們首先建立ChromePdfRenderer類的實例。 然後,我們使用ChromePdfRenderer類的各種選項。 以下是我們設置的部分選項:
MarginTop,MarginBottom,MarginLeft,MarginRight:設置PDF文件的邊距。HtmlHeader:設置顯示logo的PDF文件的頁眉。HtmlFooter:設置顯示頁碼和總頁數的PDF文件的頁腳。
設置選項後,使用HTML內容調用RenderHtmlAsPdf方法。 最後,我們將PDF文件保存為名稱為"Hello.PDF"的文件。
測試應用程式
所有必要的程式碼都就位後,我們可以現在測試應用程式。 請按照以下步驟操作:
- 按下F5或在Visual Studio中點擊綠色"播放"按鈕運行應用程式。
- 在瀏覽器中,導航到
http://localhost:/Home/Index,這是Visual Studio分配的埠號。 - 驗證項目列表是否正確顯示。
- 點擊"下載PDF"連結以生成並下載PDF文件。
如果一切正常,您應該會看到一個PDF文件,其中包含您之前定義的項目列表。
使用IronPDF將PDF轉換為CSHTML文件
PDF To 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 Page",然後給文件命名(例如,"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為什麼應該使用IronPDF?
IronPDF在.NET開發者中因以下幾個關鍵原因而很受歡迎:
強大的PDF生成能力:IronPDF提供了廣泛的功能和選項,用於程式生成和操作PDF文件,包括新增文字、圖像和其他內容到PDF頁面,以及合併和分割現有的PDF文件。
多功能的PDF轉換能力:IronPDF不僅允許開發者生成PDF文件,還提供了將PDF轉換為HTML字串或CSHTML文件的功能。 這在您需要在Web應用程式中顯示PDF內容,或從PDF文件中提取資料並在基於網路的工作流程中使用時非常有用。
易於使用的API:IronPDF的API設計直觀且易於使用,配備了廣泛的輔助方法和屬性,讓開發者能夠輕鬆地程式生成和操作PDF文件。
強大的社群支援:IronPDF擁有一個龐大和活躍的.NET開發者社群,貢獻其發展並為使用該程式庫的其他開發者提供支援。
良好的文件記錄:IronPDF的文件既全面又組織良好,具有詳細的API參考文件、教程和範例,讓開發者能夠輕鬆上手並學會如何使用此程式庫。
IronPDF強大的PDF生成和轉換功能、易於使用的API、強大的社群支援,以及良好的文件,使其成為.NET開發者在應用程式中需要處理PDF文件時的流行選擇。
結論
將CSHTML轉換為PDF是許多應用程式中的常見要求。 使用IronPDF,這項任務可以在C#中輕鬆完成。 在本文中,我們向您介紹了使用IronPDF將CSHTML轉換為PDF的步驟,並附上範例。
我們還向您展示了如何通過設置不同的選項,例如紙張大小、邊距、頁眉和頁腳等,來自定義PDF輸出。 使用IronPDF,您可以快速輕鬆地從CSHTML文件建立高質量的PDF文件。
無論您需要從頭開始建立PDF文件、將PDF轉換為HTML字串或CSHTML文件,還是從PDF文件中提取資料,IronPDF提供了一個靈活且直觀的API,使您能夠輕鬆完成工作。
憑藉其強大的社群支援和豐富的文件記錄,IronPDF是一個受到.NET開發者歡迎的選擇,適用於需要在其應用程式中處理PDF的情況。 通過購買Iron Software套件,開發者可以以折扣的價格獲得一套全面的.NET程式庫,用於處理常見文件格式,這使其對任何.NET開發團隊來說都是一個極好的價值。
如果您需要在.NET應用程式中處理PDF文件,IronPDF絕對值得考慮。 憑藉其強大的功能、易用性和多種授權選項,它是一個多用途且可靠的工具,可以幫助您快速高效地完成工作。
