如何在 ASP .NET Core 中将 HTML 转换为 PDF
.NET Core PDF生成器
创建 .NET Core PDF文件是一项繁琐的任务。 在ASP.NET MVC项目中处理PDF文件,以及将MVC视图、HTML文件和在线网页转换为PDF可能具有挑战性。 本教程使用IronPDF工具来解决这些问题,为您的许多PDF .NET需求提供指导性指南。
IronPDF 还支持使用 Chrome 浏览器调试您的 HTML,实现完美像素 PDF.
如何在 .NET Core 中将 HTML 转换为 PDF
- 下载将 HTML 转换为 PDF 的 C# 库
- 使用
将URL渲染为PDF
将网页 URL 转换为 PDF - 将 HTML 标记字符串转换为 PDF 文件
将Html渲染为Pdf
- 将 MVC 视图转换为 PDF,方法是配置模型和服务类
- 修改 HTML 页面以使用模型,并调用一个方法将 HTML 传递给
将Html渲染为Pdf
概述
完成本教程后,您将能够:
- 从不同的来源(如URL、HTML、MVC视图)转换为PDF
- 使用用于不同输出 PDF 设置的高级选项进行交互
- 将您的项目部署到 Linux 和 Windows 上
- 使用 PDF 文档操作功能
- 添加页眉和页脚、合并文件、添加印章
-
使用Docker
这种广泛的.NET Core HTML转PDF功能将有助于满足各种项目需求。
开始使用IronPDF
立即在您的项目中开始使用IronPDF,并享受免费试用。
步骤 1
1. 免费安装 IronPDF 库
IronPDF可以安装并用于所有.NET项目类型,如Windows应用程序、ASP.NET MVC和.NET Core应用程序。
要将 IronPDF 库添加到我们的项目中有两种方式,一种是通过 Visual Studio 编辑器使用 NuGet 进行安装,另一种是使用包管理控制台通过命令行进行安装。
使用 NuGet 安装
要使用 NuGet 将 IronPDF 库添加到我们的项目中,我们可以使用可视化界面(NuGet 软件包管理器)或使用软件包管理器控制台的命令:
1.1.1 使用 NuGet 软件包管理器
1- 右键点击项目名称 -> 选择管理 NuGet 包
2- 从浏览器选项卡 -> 搜索 IronPdf -> 安装
3- 单击确定
4- 完成!
1.1.2 使用 NuGet 软件包控制台管理器
1- 从工具 -> NuGet 软件包管理器 -> 软件包管理器控制台
2- 运行命令 -> 安装软件包 IronPdf
教程
2.将网站转换为 PDF
样本ConvertUrlToPdf 控制台应用程序
按照以下步骤创建新的 Asp.NET MVC 项目
1- 打开 Visual Studio
2- 选择创建新项目
3- 选择控制台应用程序(.NET Core)
4- 将样本命名为 "ConvertUrlToPdf",然后点击创建
5- 现在我们创建了一个控制台应用程序
6- 添加 IronPdf => 点击安装
7- 添加前几行,将维基百科网站主页渲染为 PDF 格式
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-1.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderUrlAsPdf("https://www.wikipedia.org/");
pdf.SaveAs("wiki.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
3.将 .NET Core HTML 转换为 PDF
样本ConvertHTMLToPdf 控制台应用程序
要将 HTML 转换为 PDF,我们有两种方法:
1- 将 HTML 写入字符串,然后进行渲染
2- 将 HTML 写入文件并将其路径传递给 IronPDF 以进行渲染
渲染 HTML 字符串的示例代码将如下所示。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-2.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
pdf.SaveAs("HtmlString.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
生成的 PDF 将是这样的
4. 将MVC视图转换为PDF
示例:TicketsApps .NET Core MVC 应用程序
让我们实施一个现实生活中的例子。 我选择了一个在线购票网站。打开网站,导航至“预订票务”页面,填写所需信息,然后将您的票据下载为PDF文件。
我们将遵循以下步骤:
创建项目
-
选择 "ASP.NET Core Web应用程序(模型-视图-控制器)"项目。
-
将项目命名为 "TicketsApps"。
-
让我们使用启用了 Linux Docker 的 .NET 8。 在Dockerfile中,将“USER app”更改为“USER root”。 这将确保库获得足够的权限。
- 现在可以了。
添加客户端模型
-
右键单击“Models”文件夹并添加类。
-
将模型命名为 "ClientModel",然后点击添加。
- 将属性'name'、'phone'和'email'添加到ClientModel类中。 通过在每一个上添加“Required”属性,使它们全部成为必填项,如下所示:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-3.cs
public class ClientModel
{
[Required]
public string Name { get; set; }
[Required]
public string Phone { get; set; }
[Required]
public string Email { get; set; }
}
Public Class ClientModel
<Required>
Public Property Name() As String
<Required>
Public Property Phone() As String
<Required>
Public Property Email() As String
End Class
添加客户服务
-
创建一个文件夹并将其命名为“services”。
-
添加一个名为“ClientServices”的类。
-
添加一个类型为“ClientModel”的静态对象,用作存储库。
- 添加两个功能:一个用于将客户保存到仓库中,另一个用于检索已保存的客户。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-4.cs
public class ClientServices
{
private static ClientModel _clientModel;
public static void AddClient(ClientModel clientModel)
{
_clientModel = clientModel;
}
public static ClientModel GetClient()
{
return _clientModel;
}
}
Public Class ClientServices
Private Shared _clientModel As ClientModel
Public Shared Sub AddClient(ByVal clientModel As ClientModel)
_clientModel = clientModel
End Sub
Public Shared Function GetClient() As ClientModel
Return _clientModel
End Function
End Class
设计订票页面
-
在解决方案资源管理器中,右键单击“Controllers”文件夹并添加一个控制器。
-
将其命名为 "BookTicketController"。
-
右击索引功能(我们称之为行动)并选择 "添加视图"。
-
添加名为 "索引 "的视图。
- 更新 HTML 如下
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-5.cs
@model IronPdfMVCHelloWorld.Models.ClientModel
@{
ViewBag.Title = "Book Ticket";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-10 pull-right">
<button type="submit" value="Save" class="btn btn-sm">
<i class="fa fa-plus"></i>
<span>
Save
</span>
</button>
</div>
</div>
</div>
}
model ReadOnly Property () As IronPdfMVCHelloWorld.Models.ClientModel
ViewBag.Title = "Book Ticket"
End Property
'INSTANT VB TODO TASK: The following line could not be converted:
(Of h2) Index</h2> [using](Html.BeginForm())
If True Then
'INSTANT VB TODO TASK: The following line uses invalid syntax:
' <div class="form-horizontal"> @Html.ValidationSummary(True, "", New { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Name, htmlAttributes: New { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Name, New { htmlAttributes = New { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", New { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Phone, htmlAttributes: New { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Phone, New { htmlAttributes = New { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Phone, "", New { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Email, htmlAttributes: New { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Email, New { htmlAttributes = New { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email, "", New { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-10 pull-right"> <button type="submit" value="Save" class="btn btn-sm"> <i class="fa fa-plus"></i> <span> Save </span> </button> </div> </div> </div> }
- 添加一个导航链接,以便我们的网站访客能够导航到我们的新预定页面。 可以通过更新现有路径中的布局来完成此操作。(视图 -> 共享 -> _Layout.cshtml). 添加以下代码:
<li class="nav-item">
<a
class="nav-link text-dark"
asp-area=""
asp-controller="BookTicket"
asp-action="Index"
>Book Ticket</a
>
</li>
<li class="nav-item">
<a
class="nav-link text-dark"
asp-area=""
asp-controller="BookTicket"
asp-action="Index"
>Book Ticket</a
>
</li>
-
结果应该是这样的
- 导航至“预订票务”页面。 您应该会发现它看起来是这样的:
验证并保存预订信息
- 添加另一个带有属性的索引操作[HttpPost]通知MVC引擎此操作用于提交数据。 验证发送的模型,如果有效,代码将重定向访问者到TicketView页面。 如果无效,访客将在屏幕上收到错误验证消息。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-7.cs
[HttpPost]
public ActionResult Index(ClientModel model)
{
if (ModelState.IsValid)
{
ClientServices.AddClient(model);
return RedirectToAction("TicketView");
}
return View(model);
}
<HttpPost>
Public Function Index(ByVal model As ClientModel) As ActionResult
If ModelState.IsValid Then
ClientServices.AddClient(model)
Return RedirectToAction("TicketView")
End If
Return View(model)
End Function
错误信息示例
- 在 "模型 "文件中创建一个票据模型,并添加如下代码
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-9.cs
public class TicketModel : ClientModel
{
public int TicketNumber { get; set; }
public DateTime TicketDate { get; set; }
}
Public Class TicketModel
Inherits ClientModel
Public Property TicketNumber() As Integer
Public Property TicketDate() As DateTime
End Class
- 将TicketView添加到我们的票证显示。 此视图将托管一个Ticket局部视图,该视图负责显示票据,并将用于稍后打印票据。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-8.cs
public ActionResult TicketView()
{
var rand = new Random();
var client = ClientServices.GetClient();
var ticket = new TicketModel()
{
TicketNumber = rand.Next(100000, 999999),
TicketDate = DateTime.Now,
Email = client.Email,
Name = client.Name,
Phone = client.Phone
};
return View(ticket);
}
Public Function TicketView() As ActionResult
Dim rand = New Random()
Dim client = ClientServices.GetClient()
Dim ticket = New TicketModel() With {
.TicketNumber = rand.Next(100000, 999999),
.TicketDate = DateTime.Now,
.Email = client.Email,
.Name = client.Name,
.Phone = client.Phone
}
Return View(ticket)
End Function
- 右键单击 TicketView 函数,选择“添加视图”,并将其命名为“TicketView”。 添加以下代码:
@model TicketsApps.Models.TicketModel @{ ViewData["Title"] = "TicketView"; }
@Html.Partial("_TicketPdf", Model) @using (Html.BeginForm()) { @Html.HiddenFor(c
=> c.Email) @Html.HiddenFor(c => c.Name) @Html.HiddenFor(c => c.Phone)
@Html.HiddenFor(c => c.TicketDate) @Html.HiddenFor(c => c.TicketNumber)
<div class="form-group">
<div class="col-md-10 pull-right">
<button type="submit" value="Save" class="btn btn-sm">
<i class="fa fa-plus"></i>
<span> Download Pdf </span>
</button>
</div>
</div>
}
@model TicketsApps.Models.TicketModel @{ ViewData["Title"] = "TicketView"; }
@Html.Partial("_TicketPdf", Model) @using (Html.BeginForm()) { @Html.HiddenFor(c
=> c.Email) @Html.HiddenFor(c => c.Name) @Html.HiddenFor(c => c.Phone)
@Html.HiddenFor(c => c.TicketDate) @Html.HiddenFor(c => c.TicketNumber)
<div class="form-group">
<div class="col-md-10 pull-right">
<button type="submit" value="Save" class="btn btn-sm">
<i class="fa fa-plus"></i>
<span> Download Pdf </span>
</button>
</div>
</div>
}
- 右键单击 BookTicket 文件,添加另一个视图并命名为"_TicketPdf"。添加以下代码
@model TicketsApps.Models.TicketModel @{ Layout = null; }
<link href="../css/ticket.css" rel="stylesheet" />
<div class="ticket">
<div class="stub">
<div class="top">
<span class="admit">VIP</span>
<span class="line"></span>
<span class="num">
@Model.TicketNumber
<span> Ticket</span>
</span>
</div>
<div class="number">1</div>
<div class="invite">Room Number</div>
</div>
<div class="check">
<div class="big">
Your <br />
Ticket
</div>
<div class="number">VIP</div>
<div class="info">
<section>
<div class="title">Date</div>
<div>@Model.TicketDate.ToShortDateString()</div>
</section>
<section>
<div class="title">Issued By</div>
<div>Admin</div>
</section>
<section>
<div class="title">Invite Number</div>
<div>@Model.TicketNumber</div>
</section>
</div>
</div>
</div>
@model TicketsApps.Models.TicketModel @{ Layout = null; }
<link href="../css/ticket.css" rel="stylesheet" />
<div class="ticket">
<div class="stub">
<div class="top">
<span class="admit">VIP</span>
<span class="line"></span>
<span class="num">
@Model.TicketNumber
<span> Ticket</span>
</span>
</div>
<div class="number">1</div>
<div class="invite">Room Number</div>
</div>
<div class="check">
<div class="big">
Your <br />
Ticket
</div>
<div class="number">VIP</div>
<div class="info">
<section>
<div class="title">Date</div>
<div>@Model.TicketDate.ToShortDateString()</div>
</section>
<section>
<div class="title">Issued By</div>
<div>Admin</div>
</section>
<section>
<div class="title">Invite Number</div>
<div>@Model.TicketNumber</div>
</section>
</div>
</div>
</div>
-
添加以下内容:"ticket.css"wwwroot/css"文件中的文件。
-
将 IronPDF 添加到项目中并同意许可协议。
- 添加将处理下载按钮的 TicketView post 方法。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-10.cs
[HttpPost]
public ActionResult TicketView(TicketModel model)
{
IronPdf.Installation.TempFolderPath = $@"{Directory.GetParent}/irontemp/";
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
var html = this.RenderViewAsync("_TicketPdf", model);
var renderer = new IronPdf.ChromePdfRenderer();
using var pdf = renderer.RenderHtmlAsPdf(html.Result, @"wwwroot/css");
return File(pdf.Stream.ToArray(), "application/pdf");
}
<HttpPost>
Public Function TicketView(ByVal model As TicketModel) As ActionResult
IronPdf.Installation.TempFolderPath = $"{AddressOf Directory.GetParent}/irontemp/"
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = True
Dim html = Me.RenderViewAsync("_TicketPdf", model)
Dim renderer = New IronPdf.ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(html.Result, "wwwroot/css")
Return File(pdf.Stream.ToArray(), "application/pdf")
End Function
- 在“Controller”文件中创建一个控制器,并将其命名为“ControllerExtensions”。 此控制器将部分视图渲染为字符串。 如下使用扩展代码:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-11.cs
using System.IO;
using System.Threading.Tasks;
public static class ControllerExtensions
{
public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
{
if (string.IsNullOrEmpty(viewName))
{
viewName = controller.ControllerContext.ActionDescriptor.ActionName;
}
controller.ViewData.Model = model;
using (var writer = new StringWriter())
{
IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);
if (viewResult.Success == false)
{
return $"A view with the name {viewName} could not be found";
}
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, new HtmlHelperOptions());
await viewResult.View.RenderAsync(viewContext);
return writer.GetStringBuilder().ToString();
}
}
}
Imports System.IO
Imports System.Threading.Tasks
Public Module ControllerExtensions
<System.Runtime.CompilerServices.Extension> _
Public Async Function RenderViewAsync(Of TModel)(ByVal controller As Controller, ByVal viewName As String, ByVal model As TModel, Optional ByVal As Boolean = False) As Task(Of String)
If String.IsNullOrEmpty(viewName) Then
viewName = controller.ControllerContext.ActionDescriptor.ActionName
End If
controller.ViewData.Model = model
Using writer = New StringWriter()
Dim viewEngine As IViewEngine = TryCast(controller.HttpContext.RequestServices.GetService(GetType(ICompositeViewEngine)), ICompositeViewEngine)
Dim viewResult As ViewEngineResult = viewEngine.FindView(controller.ControllerContext, viewName, Not partial)
If viewResult.Success = False Then
Return $"A view with the name {viewName} could not be found"
End If
Dim viewContext As New ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, New HtmlHelperOptions())
Await viewResult.View.RenderAsync(viewContext)
Return writer.GetStringBuilder().ToString()
End Using
End Function
End Module
-
运行申请并填写机票信息,然后点击 "保存"。
- 查看生成的票据
下载 PDF 文件
要将票证下载为PDF格式,请点击“下载PDF”。 您将收到一份包含门票的PDF文件。
您可以下载本指南的完整代码。它是一个压缩文件,您可以在Visual Studio中打开。 点击此处下载项目。
5. .NET PDF 渲染选项图表
我们有一些高级选项可以定义PDF呈现选项,例如调整页边距,
纸张方向、纸张尺寸等。
下表展示了多种不同的选项。
班级 | ChromePdfRenderer | |
---|---|---|
说明 | 用于定义 PDF 打印选项,如纸张大小、DPI、页眉和页脚 | |
属性/功能 | 类型 | 说明 |
自定义 Cookies | Dictionary<string, string>; | 用于 HTML 渲染的自定义 Cookie。Cookie 不会在两次渲染之间持续存在,每次都必须设置。 |
PaperFit | 虚拟纸张布局管理器 | 这是一款用于设置虚拟纸张布局的管理器,可控制 PDF "纸张 "页面的内容布局。包括默认 Chrome 浏览器行为、缩放、响应式 CSS3 布局、缩放至页面 & 连续进纸式 PDF 页面设置等选项。 |
在页眉和页脚使用边距 | 使用边距 | 在渲染页眉和页脚时,使用主文档中的页边距值。 |
从 HTML 创建 PDFFormsFromHtml | bool | 将所有 HTML 表单元素转化为可编辑的 PDF 表单。默认值为 true。 |
CssMediaType | PdfCssMediaType | 启用 Media="screen" CSS 样式和样式表。默认值为 PdfCssMediaType.Screen。 |
自定义 CSSUrl | 字符串 | 允许在呈现之前将自定义 CSS 样式表应用于 HTML。可以是本地文件路径或远程 URL。仅适用于将 HTML 呈现为 PDF 时。 |
启用 JavaScript | bool | 可在页面渲染前执行 JavaScript 和 JSON。非常适合从 Ajax / Angular 应用程序打印。默认值为 false。 |
启用数学语言版本 | bool | 启用数学 LaTeX 元素的渲染。 |
Javascript | 字符串 | 自定义 JavaScript 字符串,将在加载所有 HTML 之后、PDF 渲染之前执行。 |
JavascriptMessageListener | StringDelegate | 浏览器 JavaScript 控制台消息可用时调用的方法回调。 |
首页编号 | int | PDF 页眉和页脚中使用的第一个页码。默认值为 1。 |
目录 | 内容表类型 | 在 HTML 文档中找到 id 为 "ironpdf-toc "元素的位置生成目录。 |
灰度 | bool | 输出黑白 PDF。默认值为假。 |
文本标题 | ITextHeaderFooter | 将每个 PDF 页面的页脚内容设置为文本,支持 "邮件合并 "并自动将 URL 转变为超链接。 |
文本页脚 | ||
标题 | HtmlHeaderFooter | 将每个 PDF 页面的页眉内容设置为 HTML。支持 "邮件合并"。 |
HtmlFooter | ||
输入编码 | 编码 | 字符串形式的输入字符编码。默认值为 Encoding.UTF8。 |
边距顶部 | 双人 | PDF 顶部 "纸张 "页边距,单位为毫米。对于无边框和商业印刷应用,设置为零。默认值为 25。 |
右边距 | 双人 | PDF 右 "纸 "边距,单位为毫米。对于无边框和商业印刷应用,设置为零。默认值为 25。 |
底部边距 | 双人 | PDF 底部 "纸张 "边距,单位为毫米。对于无边框和商业印刷应用,设置为零。默认值为 25。 |
左侧边距 | 双人 | PDF 左 "纸 "边距,单位为毫米。对于无边框和商业印刷应用,设置为零。默认值为 25。 |
纸张方向 | PdfPaperOrientation | PDF 纸张方向,如纵向或横向。默认值为纵向。 |
纸张尺寸 | PdfPaperSize | 设置纸张大小 |
设置自定义纸张大小(以厘米为单位 | 双人 | 以厘米为单位设置纸张大小。 |
设置自定义纸张尺寸(英寸 | 以英寸为单位设置纸张大小。 | |
设置自定义纸张尺寸(以毫米为单位 | 以毫米为单位设置纸张大小。 | |
以像素或点为单位设置自定义纸张尺寸 | 以屏幕像素或打印机点为单位设置纸张大小。 | |
打印 HTML 背景 | 布尔型 | 表示是否从 HTML 打印背景颜色和图像。默认值为 true。 |
请求上下文 | 请求上下文 | 该呈现的请求上下文,决定某些资源(如 cookie)的隔离。 |
超时 | 整数 | 渲染超时(秒)。默认值为 60。 |
标题 | 字符串 | PDF 文档名称和标题元数据,在 IronPdf MVC 和 Razor 扩展中用于邮件合并和自动文件命名。 |
强制纸张大小 | 布尔型 | 在从 HTML 生成 PDF 后,通过调整页面大小,强制页面大小与通过 IronPdf.ChromePdfRenderOptions.PaperSize 指定的完全一致。在将 HTML 渲染为 PDF 时,有助于纠正页面大小的微小错误。 |
等待 | 等待 | 封装对象,用于保存等待机制的配置,以便用户在渲染前等待特定事件。默认情况下,它不会等待任何事件。 |
6. .NET PDF 页眉页脚选项图表
班级 | 文本页眉页脚 | |
---|---|---|
说明 | 用于定义文本页眉和页脚显示选项 | |
特性 (函数 | 类型 | 说明 |
居中文本 | 字符串 | 设置 PDF 页眉或页脚文本的居中/靠左/靠右位置。还可以使用字符串占位符合并元数据:{page}, {total-pages}, {url}, {date}, {time}, {html-title}, {pdf-title} |
左侧文本 | ||
右侧文本 | ||
绘制分割线 | 布尔型 | 在 PDF 文档的每一页页眉/页脚和页面内容之间添加水平线分隔线。 |
绘制分割线颜色 | 颜色 | 为 IronPdf.TextHeaderFooter.DrawDividerLine 指定的分隔线颜色。 |
字体 | PdfFont | PDF 文档使用的字体系列。默认为 IronSoftware.Drawing.FontTypes.Helvetica。 |
字体大小 | 双人 | 字体大小(以像素为单位)。 |
7. 应用PDF打印(渲染)选项
让我们尝试配置我们的PDF渲染选项。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-12.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Set rendering options
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;
renderer.RenderHtmlFileAsPdf(@"testFile.html").SaveAs("GeneratedFile.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
8.Docker .NET Core 应用程序
8.1. 什么是Docker?
Docker 是一套平台即服务产品,它使用操作系统级虚拟化技术来交付称为容器的软件包。 容器相互隔离,并打包它们自己的软件、库和配置文件; 他们可以通过明确的渠道相互沟通。
You can learn more aboutDocker 和 ASP.NET Core 应用程序这里。
我们将直接跳到使用Docker的部分,但如果您想了解更多信息,这里有一个很好的介绍这里是 .NET 和 Docker。以及更多关于如何为 .NET core 应用程序构建容器.
让我们一起开始使用Docker吧。
8.2. 安装 Docker
访问这里的Docker网站安装 Docker。
点击开始。
点击下载 Mac 和 Windows 版。
免费注册,然后登录。
下载 Windows 版 Docker
开始安装 Docker
它需要重新启动。 重新启动计算机后,登录到 Docker。
现在您可以通过打开Windows命令行或PowerShell脚本运行Docker“hello world”,然后输入:
Docker运行hello-world
这是一份最重要的命令行列表,可以帮助您:
- Docker 镜像 => 列出此机器上的所有可用镜像
- Docker ps => 列出所有运行中的容器
- Docker ps –a => 列出所有容器
8.3.运行到 Linux 容器中
9.处理现有 PDF 文档
9.1. 打开现有PDF
您可以从URL和HTML创建PDF(文本或文件), 您也可以处理现有的PDF文档。
以下是一个示例,用于打开普通PDF或带密码的加密PDF。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-13.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
// Open an unencrypted pdf
PdfDocument unencryptedPdf = PdfDocument.FromFile("testFile.pdf");
// Open an encrypted pdf
PdfDocument encryptedPdf = PdfDocument.FromFile("testFile2.pdf", "MyPassword");
IronPdf.License.LicenseKey = "YourLicenseKey"
' Open an unencrypted pdf
Dim unencryptedPdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
' Open an encrypted pdf
Dim encryptedPdf As PdfDocument = PdfDocument.FromFile("testFile2.pdf", "MyPassword")
9.2. 合并多个PDF文件
您可以按以下方式将多个PDF合并为一个PDF:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-14.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
List<PdfDocument> PDFs = new List<PdfDocument>();
PDFs.Add(PdfDocument.FromFile("1.pdf"));
PDFs.Add(PdfDocument.FromFile("2.pdf"));
PDFs.Add(PdfDocument.FromFile("3.pdf"));
using PdfDocument PDF = PdfDocument.Merge(PDFs);
PDF.SaveAs("mergedFile.pdf");
foreach (PdfDocument pdf in PDFs)
{
pdf.Dispose();
}
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim PDFs As New List(Of PdfDocument)()
PDFs.Add(PdfDocument.FromFile("1.pdf"))
PDFs.Add(PdfDocument.FromFile("2.pdf"))
PDFs.Add(PdfDocument.FromFile("3.pdf"))
Using PDF As PdfDocument = PdfDocument.Merge(PDFs)
PDF.SaveAs("mergedFile.pdf")
'INSTANT VB NOTE: The variable pdf was renamed since Visual Basic will not allow local variables with the same name as parameters or other local variables:
For Each Me.pdf_Conflict As PdfDocument In PDFs
Me.pdf_Conflict.Dispose()
Next pdf_Conflict
End Using
在当前 PDF 的末尾添加另一个 PDF,如下所示:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-15.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("1.pdf");
PdfDocument pdf2 = PdfDocument.FromFile("2.pdf");
pdf.AppendPdf(pdf2);
pdf.SaveAs("appendedFile.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("1.pdf")
Dim pdf2 As PdfDocument = PdfDocument.FromFile("2.pdf")
pdf.AppendPdf(pdf2)
pdf.SaveAs("appendedFile.pdf")
从给定的索引开始,将 PDF 插入另一个 PDF:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-16.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("1.pdf");
PdfDocument pdf2 = PdfDocument.FromFile("2.pdf");
pdf.InsertPdf(pdf2, 0);
pdf.SaveAs("InsertIntoSpecificIndex.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("1.pdf")
Dim pdf2 As PdfDocument = PdfDocument.FromFile("2.pdf")
pdf.InsertPdf(pdf2, 0)
pdf.SaveAs("InsertIntoSpecificIndex.pdf")
9.3 添加页眉或页脚
您可以在现有的PDF中添加页眉和页脚,或者在从HTML或URL渲染PDF时添加。
可以使用两个类在PDF中添加页眉或页脚:
- TextHeaderFooter:在页眉或页脚添加简单文本。
-
HtmlHeaderFooter:添加包含丰富HTML内容和图片的页眉或页脚。
现在让我们看两个例子,展示如何使用这两个类为现有的pdf添加页眉/页脚或在渲染时添加页眉/页脚。
9.3.1 向现有pdf添加页眉
下面是一个示例,加载一个现有的PDF,然后使用
AddTextHeaders
和AddHtmlFooters
方法添加页眉和页脚。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-17.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
TextHeaderFooter header = new TextHeaderFooter()
{
CenterText = "Pdf Header",
LeftText = "{date} {time}",
RightText = "{page} of {total-pages}",
DrawDividerLine = true,
FontSize = 10
};
pdf.AddTextHeaders(header);
pdf.SaveAs("withHeader.pdf");
HtmlHeaderFooter Footer = new HtmlHeaderFooter()
{
HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
DrawDividerLine = true,
MaxHeight = 10 //mm
};
pdf.AddHtmlFooters(Footer);
pdf.SaveAs("withHeaderAndFooters.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Dim header As New TextHeaderFooter() With {
.CenterText = "Pdf Header",
.LeftText = "{date} {time}",
.RightText = "{page} of {total-pages}",
.DrawDividerLine = True,
.FontSize = 10
}
pdf.AddTextHeaders(header)
pdf.SaveAs("withHeader.pdf")
Dim Footer As New HtmlHeaderFooter() With {
.HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
.DrawDividerLine = True,
.MaxHeight = 10
}
pdf.AddHtmlFooters(Footer)
pdf.SaveAs("withHeaderAndFooters.pdf")
9.3.2 为新PDF添加页眉和页脚
以下是使用渲染选项从HTML文件创建PDF并为其添加页眉和页脚的示例。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-18.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.TextHeader = new TextHeaderFooter()
{
CenterText = "Pdf Header",
LeftText = "{date} {time}",
RightText = "{page} of {total-pages}",
DrawDividerLine = true,
FontSize = 10
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
DrawDividerLine = true,
MaxHeight = 10
};
PdfDocument pdf = renderer.RenderHtmlFileAsPdf("test.html");
pdf.SaveAs("generatedFile.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.TextHeader = New TextHeaderFooter() With {
.CenterText = "Pdf Header",
.LeftText = "{date} {time}",
.RightText = "{page} of {total-pages}",
.DrawDividerLine = True,
.FontSize = 10
}
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {
.HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
.DrawDividerLine = True,
.MaxHeight = 10
}
Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("test.html")
pdf.SaveAs("generatedFile.pdf")
10. 添加PDF密码和安全性
您可以为您的PDF文件设置密码并编辑文件安全设置,如防止复制和打印。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-19.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
// Edit file metadata
pdf.MetaData.Author = "john smith";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = DateTime.Now;
// Edit file security settings
// The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption();
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key"); //secret-key is a owner password
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;
// Change or set the document ecrpytion password
pdf.Password = "123";
pdf.SaveAs("secured.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
' Edit file metadata
pdf.MetaData.Author = "john smith"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = DateTime.Now
' Edit file security settings
' The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key") 'secret-key is a owner password
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights
' Change or set the document ecrpytion password
pdf.Password = "123"
pdf.SaveAs("secured.pdf")
11. 数字签名 PDFs
您也可以按如下方式对PDF文件进行数字签名:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-20.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
pdf.Sign(new PdfSignature("cert123.pfx", "password"));
pdf.SaveAs("signed.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
pdf.Sign(New PdfSignature("cert123.pfx", "password"))
pdf.SaveAs("signed.pdf")
高级示例可实现更多控制:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-21.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
IronPdf.Signing.PdfSignature signature = new IronPdf.Signing.PdfSignature("cert123.pfx", "123");
// Optional signing options
signature.SigningContact = "support@ironsoftware.com";
signature.SigningLocation = "Chicago, USA";
signature.SigningReason = "To show how to sign a PDF";
// Sign the PDF with the PdfSignature. Multiple signing certificates may be used
pdf.Sign(signature);
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Dim signature As New IronPdf.Signing.PdfSignature("cert123.pfx", "123")
' Optional signing options
signature.SigningContact = "support@ironsoftware.com"
signature.SigningLocation = "Chicago, USA"
signature.SigningReason = "To show how to sign a PDF"
' Sign the PDF with the PdfSignature. Multiple signing certificates may be used
pdf.Sign(signature)
12.从 PDF 中提取文本和图像
提取文本和图像 使用 IronPdf,您可以从 PDF 中提取文本和图像,具体方法如下:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-22.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
pdf.ExtractAllText(); // Extract all text in the pdf
pdf.ExtractTextFromPage(0); // Read text from specific page
// Extract all images in the pdf
var AllImages = pdf.ExtractAllImages();
// Extract images from specific page
var ImagesOfAPage = pdf.ExtractImagesFromPage(0);
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
pdf.ExtractAllText() ' Extract all text in the pdf
pdf.ExtractTextFromPage(0) ' Read text from specific page
' Extract all images in the pdf
Dim AllImages = pdf.ExtractAllImages()
' Extract images from specific page
Dim ImagesOfAPage = pdf.ExtractImagesFromPage(0)
12.1. 将PDF光栅化为图像
您也可以按以下方式将PDF页面转换为图像:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-23.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
List<int> pageList = new List<int>() { 1, 2 };
pdf.RasterizeToImageFiles("*.png", pageList);
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Dim pageList As New List(Of Integer)() From {1, 2}
pdf.RasterizeToImageFiles("*.png", pageList)
13. 添加PDF水印
The following is an example of how to watermark PDF pages.
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-24.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
// Apply watermark
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs("Watermarked.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
' Apply watermark
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center)
pdf.SaveAs("Watermarked.pdf")
水印有一套受限的选项和功能。 为了更好的控制,您可以使用 HTMLStamper 类。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-25.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<div>test text </div>");
// Configure HTML stamper
HtmlStamper backgroundStamp = new HtmlStamper()
{
Html = "<h2 style='color:red'>copyright 2018 ironpdf.com",
MaxWidth = new Length(20),
MaxHeight = new Length(20),
Opacity = 50,
Rotation = -45,
IsStampBehindContent = true,
VerticalAlignment = VerticalAlignment.Middle
};
pdf.ApplyStamp(backgroundStamp);
pdf.SaveAs("stamped.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<div>test text </div>")
' Configure HTML stamper
Dim backgroundStamp As New HtmlStamper() With {
.Html = "<h2 style='color:red'>copyright 2018 ironpdf.com",
.MaxWidth = New Length(20),
.MaxHeight = New Length(20),
.Opacity = 50,
.Rotation = -45,
.IsStampBehindContent = True,
.VerticalAlignment = VerticalAlignment.Middle
}
pdf.ApplyStamp(backgroundStamp)
pdf.SaveAs("stamped.pdf")
教程快速访问
访问 GitHub 教程
通过 GitHub 探索本教程和更多内容。使用项目和源代码是学习并将其应用于您自己的 PDF .NET Core 需求和用例的最佳方式。
在 .NET Core 中生成 PDF 教程保留 PDF CSharp Cheat Sheet
使用我们方便的参考文档在您的 .NET 应用程序中开发 PDFS。通过快速访问常用函数和示例来在 C# 和 VB.NET 中生成和编辑 PDF,这个可共享的工具可帮助您节省开始使用 IronPDF 和项目中常见 PDF 需求所需的时间和精力。
保存小抄