使用 IRON SUITE

如何在 C# 中将 CSHTML 转换为 PDF

将CSHTML转换为PDF是许多应用程序中的常见要求。 使用IronPDF库在C#中可以轻松完成此任务。

IronPDF是一个流行的.NET库,使开发人员可以通过编程方式创建、读取、编辑和转换PDF文档。 在本文中,我们将引导您完成使用 IronPDF 在 C# 中将 CSHTML 转换为 PDF 的步骤,并附有示例。

在我们开始之前,让我们讨论一些本教程中必要的重要概念。

重要概念

PDF Converter

PDF转换器是一个将任何可打印文档或网页转换为PDF文档的工具。 它可以用于从HTML、Word、Excel或任何其他可打印文档生成PDF文件。 PDF转换器有多种形式,包括在线工具、桌面软件和库。

Razor 视图

Razor视图是一个视图引擎,在ASP.NET Core中用于动态生成HTML页面。 它是一种将HTML标记与C#代码结合的标记语法。

如何在C#中将CSHTML转换为PDF,图1:Razor视图 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文件并生成可由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文档。 以下是在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!
$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

让我们逐步解读这段代码:

  • 首先,我们导入了必要的命名空间,包括包含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
$vbLabelText   $csharpLabel

在此示例中,我们首先创建了一个ChromePdfRenderer类的实例。 然后,我们使用ChromePdfRenderer类的RenderingOptions属性设置各种选项。 以下是我们设置的一些选项:

  • MarginTop, MarginBottom, MarginLeft, MarginRight:设置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 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
$vbLabelText   $csharpLabel

为什么选择使用IronPDF?

IronPDF是.NET开发人员的流行选择,有几个关键原因:

强大的PDF生成功能:IronPDF提供了一系列功能和选项,可以通过编程方式创建和操作PDF文档,包括添加文本、图像和其他内容到PDF页面的能力,以及合并和拆分现有PDF文档的能力。

多功能的PDF转换功能:IronPDF不仅允许开发人员生成PDF文档,还提供了将PDF转换为HTML字符串或CSHTML文件的功能。 这在需要在Web应用程序中显示PDF内容或从PDF文档中提取数据并在基于Web的工作流中使用时很有用。

易于使用的API:IronPDF的API设计直观且易于使用,提供了广泛的辅助方法和属性,使开发人员可以通过编程方式轻松生成和操作PDF文档。

强大的社区支持:IronPDF拥有一个庞大且活跃的.NET开发者社区,他们为其开发做出贡献,并向其他正在使用该库的开发者提供支持。

良好的文档: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 Software包,开发人员可以以折扣价访问一整套用于处理常见文件格式的.NET库,使其成为任何.NET开发团队的绝佳选择。

如果您需要在.NET应用程序中处理PDF文档,IronPDF确实值得考虑。 凭借其强大的功能、易用性和许可选项,IronPDF是一种多功能且可靠的工具,可以帮助您快速高效地完成任务。