How to Convert Razor Views to PDFs Headlessly in C
通過使用RenderHtmlAsPdf方法生成PDF文件,無需GUI或瀏覽器窗口。
無頭渲染在沒有圖形使用者介面的情況下處理網頁內容。 雖然IronPdf.Extensions.Razor很有用,但它缺乏無頭渲染能力。 本指南解決了這一缺口。
我們將使用cshtml轉換為HTML,然後使用IronPDF生成PDF。
快速開始:在幾秒內將Razor視圖轉換為PDF
使用IronPDF的無頭轉換將Razor視圖轉換為PDF。 使用IronPdf.HtmlToPdf.StaticRender.RenderHtmlAsPdf將Razor視圖中的HTML渲染為PDF。 這種方法在ASP.NET Core環境中無縫運作。
最小工作流程 (5步)
- 下載C#庫以在ASP.NET Core Web App中將Razor視圖轉換為PDF
- 建立一個新的Razor視圖並編輯文件以顯示資料
- 使用
RenderAsync方法從Razor視圖轉換為HTML - 使用
RenderHtmlAsPdf方法將HTML轉換為PDF - 下載範例項目以快速入門
安裝Razor.Templating.Core以在ASP.NET Core Web App中將Razor視圖轉換為HTML。
# Install the Razor.Templating.Core package using NuGet Package Manager
Install-Package Razor.Templating.Core
# Install the Razor.Templating.Core package using NuGet Package Manager
Install-Package Razor.Templating.Core
如何設置我的ASP.NET Core項目以進行Razor到PDF的轉換?
您需要一個ASP.NET Core Web App(Model-View-Controller)項目來將視圖轉換為PDF。 設置過程包括在Visual Studio中建立項目、安裝NuGet包,以及配置項目結構。 對於類似的技術,請參閱在MVC Core中將CSHTML轉換為PDF或使用Razor Pages將CSHTML轉換為PDF。
為什麼需要Razor.Templating.Core而不是IronPdf.Extensions.Razor?
Razor.Templating.Core提供真正的無頭渲染——在沒有網路上下文或瀏覽器窗口的情況下將Razor視圖轉換為HTML。 這適用於後台服務、控制台應用程式或無UI的環境。 IronPdf.Extensions.Razor需要網路上下文才能運作。
哪種型別的項目最適合無頭PDF生成?
ASP.NET Core Web App(Model-View-Controller)項目提供必要的Razor視圖基礎結構以及靈活的部署選項。 在後台服務、Azure Functions或控制台應用程式中使用此方法。 請參閱將IronPDF部署到Azure以進行基於雲的生成。
如何安裝所需的NuGet包?
使用NuGet包管理器安裝包。 您需要Razor.Templating.Core:
// Install via Package Manager Console
Install-Package IronPdf
Install-Package Razor.Templating.Core
// Or add to your .csproj file
// <PackageReference Include="IronPdf" Version="2024.x.x" />
// <PackageReference Include="Razor.Templating.Core" Version="1.x.x" />
// Install via Package Manager Console
Install-Package IronPdf
Install-Package Razor.Templating.Core
// Or add to your .csproj file
// <PackageReference Include="IronPdf" Version="2024.x.x" />
// <PackageReference Include="Razor.Templating.Core" Version="1.x.x" />
如何建立和配置Razor視圖以進行PDF生成?
- 右鍵單擊"首頁"文件夾。 選擇"新增",然後選擇"新增視圖"。
- 建立一個名為"Data.cshtml"的空Razor視圖。
我應該在Razor視圖中新增什麼HTML內容?
新增您想要呈現為PDF的HTML:
<table class="table">
<tr>
<th>Name</th>
<th>Title</th>
<th>Description</th>
</tr>
<tr>
<td>John Doe</td>
<td>Software Engineer</td>
<td>Experienced software engineer specializing in web development.</td>
</tr>
<tr>
<td>Alice Smith</td>
<td>Project Manager</td>
<td>Seasoned project manager with expertise in agile methodologies.</td>
</tr>
<tr>
<td>Michael Johnson</td>
<td>Data Analyst</td>
<td>Skilled data analyst proficient in statistical analysis and data visualization.</td>
</tr>
</table>
<table class="table">
<tr>
<th>Name</th>
<th>Title</th>
<th>Description</th>
</tr>
<tr>
<td>John Doe</td>
<td>Software Engineer</td>
<td>Experienced software engineer specializing in web development.</td>
</tr>
<tr>
<td>Alice Smith</td>
<td>Project Manager</td>
<td>Seasoned project manager with expertise in agile methodologies.</td>
</tr>
<tr>
<td>Michael Johnson</td>
<td>Data Analyst</td>
<td>Skilled data analyst proficient in statistical analysis and data visualization.</td>
</tr>
</table>
對於複雜的布局,使用CSS和列印樣式來確保完美的PDF渲染。 IronPDF支持現代CSS3功能,用於複雜的文件布局。
為什麼要使用表格來顯示PDF資料?
表格提供結構化的、有組織的資訊,能夠很好地轉化為列印文件。 在不同平台上保持一致的格式,並在PDF格式中可讀。 IronPDF的渲染引擎良好地處理表格布局,保留邊框、間距和對齊。 對於高級格式,請探索自定義邊距以優化布局。
PDF輸出的常見樣式考量有哪些?
對於PDF輸出,使用列印特定的CSS媒體查詢,固定像素值而非相對單位,以及嵌入式字體以實現一致的渲染。 IronPDF支持網頁字體和圖標字體,以保持品牌一致性。 考慮頁面分隔符以生成多頁文件,並使用合適的邊距以達到專業的外觀。
如何配置Program.cs以進行無頭PDF渲染?
在Program.cs中,新增此程式碼。 它使用RenderHtmlAsPdf。 使用RenderingOptions來自定義文字、標題、頁腳、邊距和頁碼。
:path=/static-assets/pdf/content-code-examples/how-to/cshtml-to-pdf-razor-headlessly-5.cs
app.MapGet("/PrintPdf", async () =>
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Enable detailed logging for troubleshooting
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
// Render the Razor view to an HTML string
string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Configure rendering options for professional output
renderer.RenderingOptions.PaperSize = IronPdf.PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
// Render the HTML string as a PDF document
PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");
// Return the PDF file as a response
return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});
Imports IronPdf
Imports Microsoft.AspNetCore.Http
app.MapGet("/PrintPdf", Async Function() As Task(Of IResult)
' Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
' Enable detailed logging for troubleshooting
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All
' Render the Razor view to an HTML string
Dim html As String = Await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml")
' Create a new instance of ChromePdfRenderer
Dim renderer As New ChromePdfRenderer()
' Configure rendering options for professional output
renderer.RenderingOptions.PaperSize = IronPdf.PdfPaperSize.A4
renderer.RenderingOptions.MarginTop = 25
renderer.RenderingOptions.MarginBottom = 25
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20
' Render the HTML string as a PDF document
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html, "./wwwroot")
' Return the PDF file as a response
Return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf")
End Function)
我可以為PDF應用哪些渲染選項?
IronPDF提供了豐富的渲染選項。 新增頭和腳,設置自定義紙張大小,控制頁面方向,以及新增水印。 ChromePdfRenderer提供超過50個屬性來自定義PDF生成。
如何處理PDF生成過程中的錯誤?
實施錯誤處理以進行穩健的PDF生成:
:path=/static-assets/pdf/content-code-examples/how-to/cshtml-to-pdf-razor-headlessly-6.cs
try
{
var html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");
return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
}
catch (Exception ex)
{
// Log the error details
IronPdf.Logging.Logger.Log($"PDF generation failed: {ex.Message}");
return Results.Problem("Failed to generate PDF", statusCode: 500);
}
Imports IronPdf
Imports System.Threading.Tasks
Try
Dim html = Await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml")
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot")
Return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf")
Catch ex As Exception
' Log the error details
IronPdf.Logging.Logger.Log($"PDF generation failed: {ex.Message}")
Return Results.Problem("Failed to generate PDF", statusCode:=500)
End Try
什麼時候應啟用詳細日誌記錄?
在開發和故障排除過程中啟用詳細日誌記錄。 IronPDF的日誌記錄提供渲染見解,幫助定位HTML解析、資源載入或配置問題。 對於生產環境,使用自定義日誌記錄與應用程式的日誌記錄結構整合。
為什麼我需要修改資源連結路徑?
導航至Views > Shared > _Layout.cshtml。 在連結標籤中,將"~/"與IronPDF一起使用效果不佳。
還需要注意哪些其他路徑相關問題?
除了波浪號 (~) 路徑問題,確保圖像來源使用絕對路徑或正確的相對引用。 對於外部資源,使用基本URL以確保資源載入正確。 對於Azure Blob Storage圖像,請參閱從Azure Blob Storage嵌入圖像。
靜態資源如何影響PDF生成?
靜態資源(CSS、JavaScript、圖像)影響PDF生成的性能和質量。 確保資源在渲染期間可存取,使用優化的圖像,並考慮內嵌關鍵的CSS以加速渲染。 了解對於JavaScript密集內容的渲染延遲和超時。
如何測試我的無頭PDF生成?
運行項目以生成PDF文件。
輸出PDF
我的最終PDF應該是什麼樣的?
您的PDF應該保持所有Razor視圖格式——表格結構、字體、顏色和布局。 它應該有適合的大小、整潔的邊距和專業的外觀。 為了驗證輸出質量,使用IronPDF的光柵化功能以圖像的形式預覽頁面。
如何解決常見的PDF渲染問題?
常見問題包括樣式缺失、佈局問題或內容不完整。 啟用詳細日誌記錄,驗證資源路徑,並確保HTML驗證正常。 對於複雜的布局,使用Chrome除錯工具在轉換之前預覽HTML。 對於特定的渲染問題,使用等待延遲確保內容在渲染前載入。
我可以在哪裡下載完整的工作範例?
下載完整程式碼作為壓縮的Visual Studio ASP.NET Core Web App(Model-View-Controller)項目。
運行範例項目需要哪些先決條件?
您需要Visual Studio 2019或更高版本以及.NET 6.0 SDK或更高版本。 該項目需要互聯網連接以進行NuGet包還原。 在運行之前,更新您的IronPDF授權金鑰在Program.cs中。 對於部署,請查閱Windows安裝指南了解其他要求。
如何根據我的需求自定義範例?
該範例為您的具體需求提供了一個基礎。 新增動態資料模型,實施快取以應對經常生成的PDF,或與現有的認證系統整合。 對於進階場景,探索異步PDF生成以提高性能,或實施PDF壓縮以減少文件大小。 新增數位簽名以確保文件真實性,或對於敏感文件進行密碼保護。
常見問題
我如何在C#中無頭地將Razor視圖轉換為PDF?
使用Razor.Templating.Core將cshtml檔案轉換為HTML,然後使用IronPDF的RenderHtmlAsPdf方法無頭地生成PDF。這個兩步驟的過程允許您將Razor視圖轉換為PDF文件,無需圖形使用者介面或瀏覽器窗口。
將Razor視圖無頭渲染為PDF的最快方法是什麼?
最快的方法是使用兩行程式碼:首先使用RazorTemplateEngine.RenderAsync將您的Razor視圖轉換為HTML,然後使用IronPDF的ChromePdfRenderer().RenderHtmlAsPdf(html).SaveAs()方法建立並保存PDF文件。
為什麼我應該使用Razor.Templating.Core而不是IronPdf.Extensions.Razor?
Razor.Templating.Core提供真正的無頭渲染功能,允許您將Razor視圖轉換為HTML,無需網路上下文或瀏覽器窗口。雖然IronPdf.Extensions.Razor很有用,但它需要網路上下文才能工作,這使得Razor.Templating.Core更適合於後台服務和控制台應用程式。
我需要哪種型別的ASP.NET Core項目來進行無頭PDF生成?
使用ASP.NET Core網頁應用(模型-視圖-控制器)項目,這裡提供必要的Razor視圖基礎設施,並具有靈活的部署選項。這種設置適合IronPDF用於後台服務、Azure Functions或控制台應用程式。
如何安裝Razor到PDF轉換所需的套件?
使用NuGet包管理器安裝Razor.Templating.Core,命令為 'Install-Package Razor.Templating.Core'。您還需要在項目中安裝IronPDF,以處理HTML到PDF的轉換步驟。
我可以在雲環境中使用這種無頭PDF生成方法嗎?
是的,IronPDF的無頭Razor到PDF轉換在包括Azure Functions、AWS Lambda和容器化應用程式的雲環境中效果極佳,使其成為可擴展文件生成服務的理想選擇。

