.NET Core HTML 轉 PDF 教程(逐步)

This article was translated from English: Does it need improvement?
Translated
View the article in English

.NET Core PDF 生成器

使用 .NET Core 創建 PDF 檔案是一項繁瑣的工作。 在 ASP.NET MVC 專案中處理 PDF 檔案,以及將 MVC 視圖、HTML 檔案和線上網頁轉換成 PDF 可能具有挑戰性。 本教程使用IronPDF工具解决这些问题,为您的许多PDF .NET需求提供指导性指南。

IronPDF 也支持使用 Chrome 僅進行 HTML 除錯以生成像素完美的 PDF。.


概述

在本教程之後,您將能夠:

  • 從不同來源轉換為PDF,例如URL、HTML、MVC視圖。
  • 使用用於不同輸出 PDF 設定的高級選項
  • 將您的專案部署到 Linux 和 Windows
  • 使用 PDF 文檔操作功能
  • 添加頁首和頁尾、合併文件、新增印章
  • 使用 Dockers工作

    這種廣泛的 .NET Core HTML 轉 PDF 功能將有助於滿足各種項目需求。

    開始使用 IronPDF

    立即在您的專案中使用IronPDF,並享受免費試用。

    第一步:
    green arrow pointer


第一步

1. 安裝 IronPDF Library 免費版

IronPDF 可以安裝並用於所有的 .NET 專案類型,如 Windows 應用程式、ASP.NET MVC 和 .NET Core 應用程式。

要將IronPDF庫添加到我們的項目中,我們有兩種方法:一是通過Visual Studio編輯器使用NuGet進行安裝,二是使用命令行通過包控制台管理器進行安裝。

使用 NuGet 安裝

要使用 NuGet 將 IronPDF 庫新增到我們的專案中,我們可以使用可視化介面。(NuGet 套件管理器)或者通過使用套件管理控制台來執行命令:

.1.1 使用 NuGet 套件管理員

- 右鍵點擊專案名稱 -> 選擇管理 NuGet 套件 1 related to 使用 NuGet 安裝- 從瀏覽器標籤 -> 搜尋 IronPDF -> 安裝 2 related to 使用 NuGet 安裝- 點擊確定 3 related to 使用 NuGet 安裝- 完成了! 4 related to 使用 NuGet 安裝

.1.2 使用 NuGet 套件管理器控制台

從工具 -> NuGet 套件管理器 -> 套件管理器控制台 5 related to 使用 NuGet 安裝- 執行命令 -> Install-Package IronPdf 6 related to 使用 NuGet 安裝


操作教程

2. 將網站轉換為 PDF

範例:ConvertUrlToPdf 控制台應用程式

請按照以下步驟建立一個新的 Asp.NET MVC 專案


- 打開 Visual Studio 7 related to 2. 將網站轉換為 PDF選擇「創建新專案」 8 related to 2. 將網站轉換為 PDF-選擇主控台應用程式(.NET Core) 9 related to 2. 將網站轉換為 PDF- 給我們的範例命名為 “ConvertUrlToPdf” 並點擊創建 10 related to 2. 將網站轉換為 PDF- 現在我們已經建立了一個主控台應用程式 11 related to 2. 將網站轉換為 PDF- 添加 IronPDF => 點擊安裝 12 related to 2. 將網站轉換為 PDF13 related to 2. 將網站轉換為 PDF

- 添加幾行代碼將維基百科首頁渲染為 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
VB   C#

- 執行並檢查所建立的文件 wiki.pdf 14 related to 2. 將網站轉換為 PDF


3. 轉換.NET Core的HTML為PDF

範例:將 HTML 轉換為 PDF 控制台應用程式

要將 HTML 渲染為 PDF,我們有兩種方式:
將 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
VB   C#

生成的 PDF 將如下所示。

15 related to 3. 轉換.NET Core的HTML為PDF


4. 將 MVC 視圖轉換為 PDF

範例:TicketsApps .NET Core MVC 應用程式

讓我們實作一個真實生活中的例子。 我選擇了一個線上購票網站。打開網站,導航至「訂票」,填寫所需資訊,然後將你的副本下載為PDF文件。

我們將依照以下步驟進行:

-建立專案

-建立客戶端物件模型

-建立客戶服務(添加、查看)

-設計訂票頁面

-驗證並保存預訂信息

-下載 PDF 票券

建立專案

  1. 選擇 "ASP.NET Core Web 應用程序(模型-視圖-控制器)專案。

    16 related to 建立專案
  2. 將專案命名為“TicketsApps”。

    17 related to 建立專案
  3. 讓我們使用啟用了 Linux Docker 的 .NET 8。 在 Dockerfile 中,將 "USER app" 更改為 "USER root"。 這將確保授予庫足夠的權限。

    18 related to 建立專案
  4. 現在已準備好了。 19 related to 建立專案

添加客戶模型

  1. 右鍵點擊“Models”文件夾並添加類。

    20 related to 添加客戶模型
  2. 將模型命名為“ClientModel”,然後點擊新增。

    21 related to 添加客戶模型
  3. 向 ClientModel 類別添加屬性 'name'、'phone' 和 'email'。 通過在每個上添加 '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
VB   C#

添加客戶服務

  1. 創建一個文件夾並將其命名為“services”。

  2. 新增一個名為「ClientServices」的類別。

  3. 將類型為“ClientModel”的靜態物件添加到其中,用作存儲庫。

  4. 添加兩個功能:一個用於將客戶保存到存儲庫中,另一個用於檢索已保存的客戶。
: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
VB   C#

設計訂票頁面

  1. 在方案總管中,右鍵點擊“Controllers”文件夾並添加一個控制器。

    22 related to 設計訂票頁面
  2. 將其命名為 "BookTicketController"。

    23 related to 設計訂票頁面
  3. 右鍵點擊索引函數(或者正如我們所說的行動)並選擇「新增檢視」。

    24 related to 設計訂票頁面
  4. 添加名為“index”的視圖。

    25 related to 設計訂票頁面
  5. 將 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> }
VB   C#
  1. 在我們的網站中添加導航連結,以便訪客前往我們的新預約頁面。 這可以通過更新現有路徑中的佈局來完成。(視圖 -> 共享 -> _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>
HTML
  1. 結果應該看起來像這樣。

    26 related to 設計訂票頁面
  2. 導航至「訂票」頁面。 您應該會發現它看起來像這樣: 27 related to 設計訂票頁面

驗證並保存預訂信息

  1. 添加另一個索引操作和屬性[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
VB   C#

錯誤訊息範例 28 related to 驗證並保存預訂信息

  1. 在「Models」文件中創建一個 Ticket 模型,並添加如下代碼
: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
VB   C#
  1. 將 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
VB   C#
  1. 右鍵單擊 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>
}
HTML
  1. 右鍵點擊 BookTicket 文件,添加另一個 View 並命名為 "_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>
HTML
  1. 請添加下列"ticket.css"wwwroot/css" 文件中的文件。

  2. 將IronPDF添加到項目並同意許可協議。

    31 related to 驗證並保存預訂信息
  3. 添加將處理下載按鈕的 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
VB   C#
  1. 在 "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
VB   C#
  1. 運行應用程式並填寫票務資訊,然後點擊「保存」。

    32 related to 驗證並保存預訂信息
  2. 查看生成的票券 33 related to 驗證並保存預訂信息

下載 PDF 票券

要將票證下載為PDF格式,請點擊「下載PDF」。 您將收到一份包含門票的PDF文件。

您可以下載本指南的完整代碼。它以壓縮檔的形式提供,您可以在Visual Studio中打開。 點擊這裡下載專案。


5. .NET PDF 渲染選項圖表

我們有一些高級選項,可定義 PDF 渲染選項,如調整邊距,

紙張方向、紙張大小等。

以下是一個表格,用於說明多種不同選項。

類別ChromePdfRenderer
描述用於定義PDF列印選項,例如紙張大小、DPI、頁首和頁尾
屬性 / 函數類型描述
自定義CookiesDictionary<string, string>HTML渲染的自訂Cookie。Cookie不會在渲染之間持續,必須每次都設置。
紙適虛擬紙張佈局管理器一個用於設置虛擬紙張佈局的管理器,控制內容在 PDF「紙張」頁面上的佈局方式。包括默認的 Chrome 行為、縮放、響應式 CSS3 佈局、按頁比例縮放和連續輸送樣式的 PDF 頁面設置選項。
使用頁首和頁腳的邊距使用邊距在渲染頁眉和頁腳時使用主文檔的邊距值。
從Html創建Pdf表單布林值將所有 HTML 表單元素轉換為可編輯的 PDF 表單。默認值為 true。
CssMediaTypePdfCssMediaType啟用媒體="螢幕" CSS 樣式和樣式表。預設值為 PdfCssMediaType.Screen。
自訂Css網址字串允許在渲染之前將自定義 CSS 樣式表應用於 HTML。可以是本地檔案路徑或遠端 URL。僅在將 HTML 渲染為 PDF 時適用。
啟用JavaScript布林值在頁面渲染之前允許執行 JavaScript 和 JSON。非常適合從 Ajax / Angular 應用程式列印。預設值為 false。
啟用數學LaTex布林值啟用渲染數學 LaTeX 元素。
JavaScript字串在所有 HTML 加載完成但在 PDF 渲染之前執行的自定義 JavaScript 字串。
JavaScript訊息監聽器字串委派當瀏覽器的 JavaScript 控制台訊息變為可用時,將調用的方法回調。
第一頁號碼整數PDF 頁眉和頁腳中使用的第一頁頁碼。預設值為 1。
目錄目錄類型在 HTML 文件中找到 id 為 "ironpdf-toc" 的元素所在位置生成目錄。
灰度布林值輸出黑白 PDF。預設值為 false。
文本標題ITextHeaderFooter設定每個PDF頁面的頁腳內容為文字,支持「郵件合併」並自動將URL變為超連結。
文本頁腳
HtmlHeaderHtmlHeaderFooter將每個 PDF 頁面的標題內容設置為 HTML。支援「郵件合併」。
HtmlFooter
輸入編碼編碼輸入字符編碼為字串。默認值為Encoding.UTF8。
上邊距雙精度頂部 PDF「紙張」邊距(以毫米為單位)。設置為零以便無邊界和商業打印應用。默認值為 25。
右邊邊距雙精度右側PDF「紙張」邊距(以毫米計算)。設置為零則無邊框,適用於商業列印應用。預設值為25。
底邊距雙精度底部 PDF「紙張」邊距,單位為毫米。設置為零以實現無邊距和商業印刷應用。默認值為 25。
左邊距雙精度左側 PDF 「紙張」邊距(以毫米計)。設置為零適用於無邊距和商業印刷應用。預設值為 25。
紙張方向PdfPaperOrientationPDF文件的紙張方向,例如縱向或橫向。默認值為縱向。
紙張大小PdfPaperSize設定紙張大小
以公分設定自訂紙張大小雙精度設置紙張大小為公分。
設置自定義紙張尺寸(英寸)設置紙張大小(單位:英寸)。
設置自訂紙張大小(毫米)以毫米設置紙張尺寸。
在像素或點中設置自定義紙張大小設定紙張尺寸為螢幕像素或印表機點數。
打印Html背景布林值指示是否打印來自 HTML 的背景顏色和圖片。預設值為 true。
請求上下文請求上下文請求此渲染的上下文,確定某些資源如 Cookie 的隔離。
超時整數呈現超時(單位:秒)。預設值為 60。
標題字串PDF 文件名稱和標題元數據,用於 IronPDF MVC 和 Razor 擴展中的郵件合併和自動文件命名。
強制紙張尺寸布林值透過IronPdf.ChromePdfRenderOptions.PaperSize指定的強制頁面大小,在從HTML生成PDF後調整頁面大小。幫助修正將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
VB   C#

8. Docker .NET Core 應用程序

8.1. 什麼是 Docker?

Docker 是一套平台即服務產品,利用作業系統層級的虛擬化技術來交付名為容器的軟件包。 容器彼此隔離,並捆綁它們自己的軟體、庫和配置文件; 他們可以通過明確定義的通道相互溝通。

您可以了解更多關於Docker 和 ASP.NET Core 應用程式這裡。

我們將直接跳到使用 Docker 的部分,但如果你想了解更多,有一個很好的介绍可以参考。.NET和Docker在這裡。甚至更多有關如何為 .NET core 應用程式構建容器.

讓我們一起開始使用 Docker 吧。

8.2 安裝 Docker

訪問 Docker 網站,點擊這裡。安裝 Docker。 40 related to 8.2 安裝 Docker點擊開始。 41 related to 8.2 安裝 Docker點擊下載適用於 Mac 和 Windows 的版本。 42 related to 8.2 安裝 Docker免費註冊,然後登入。 43 related to 8.2 安裝 Docker下載適用於 Windows 的 Docker。 44 related to 8.2 安裝 Docker開始安裝 Docker。 45 related to 8.2 安裝 Docker需要重新啟動。 重新啟動您的機器後,登入 Docker。 46 related to 8.2 安裝 Docker現在您可以通過開啟Windows命令行或PowerShell腳本來運行Docker "hello world",並寫入:

Docker 執行 hello-world 47 related to 8.2 安裝 Docker以下是一些最重要的命令行列表,可供您参考:

  • Docker 映像檔 => 列出此機器上的所有可用映像檔
  • Docker ps => 列出所有運行中的容器
  • Docker ps –a => 列出所有容器

8.3. 運行於 Linux 容器

38 related to 8.3. 運行於 Linux 容器39 related to 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")
VB   C#

9.2. 合併多個PDFs

您可以按照以下方法將多個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
VB   C#

將另一個 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")
VB   C#

將 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")
VB   C#

9.3 添加頁首或頁尾

您可以在現有的PDF中添加頁首和頁尾,或者在從HTML或URL渲染PDF時添加。

您可以使用兩個類來添加PDF的頁首或頁尾:

  • TextHeaderFooter:在頁首或頁尾添加簡單文字。
  • HtmlHeaderFooter:添加具有豐富HTML內容和圖像的頁首或頁尾。

    現在讓我們看兩個例子,說明如何在現有的pdf中添加頁眉/頁腳,或在使用這兩個類別時渲染它們。

    9.3.1 為現有的 PDF 添加頁首

    以下是使用 AddTextHeadersAddHtmlFooters 方法加载现有 PDF,然后添加页眉和页脚的示例。

: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")
VB   C#

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")
VB   C#

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")
VB   C#

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")
VB   C#

進階範例以獲得更多控制:

: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)
VB   C#

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)
VB   C#

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)
VB   C#

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")
VB   C#

浮水印具有有限的選項和功能集。 為了更好的控制,您可以使用 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")
VB   C#

快速指南

Brand Visual Studio related to 快速指南

取得原始碼

在此教程中找到的所有源代碼均可作為Visual Studio項目ZIP文件訪問,易於使用和分享給您的項目。

取得程式碼

GitHub 教程访问

通過 GitHub 探索這個教程和更多内容。使用這些項目和源代碼是學習的最佳方式,並將其應用於您自己的 PDF .NET Core 需求和用例。

在 .NET Core 中生成 PDF 教程
Github Icon related to 快速指南
Html To Pdf Icon related to 快速指南

保留 PDF CSharp 速查表

在您的 .NET 應用程式中使用我們方便的參考文件開發 PDF。提供對常見功能和生成及編輯 PDF 的 C# 和 VB.NET 範例的快速訪問,這個可共享的工具幫助您節省時間和精力,快速入門使用 IronPDF 完成項目中的常見 PDF 需求。

保留備忘單

更多文件

請參閱 IronPDF API 參考資料,該參考資料詳細介紹了 IronPDF 所有功能的細節,包括命名空間、類別、方法欄位和枚舉。

API參考文件
Documentation related to 快速指南