如何在 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
- 下載 C# 程式庫以將 HTML 轉換為 PDF
- 使用
RenderUrlAsPdf
將網頁網址轉換為 PDF - 使用
RenderHtmlAsPdf
將HTML Markdown字串轉換為PDF - 通過配置Model和Services類將MVC視圖轉換為PDF
- 修改 HTML 頁面以使用模型,並調用一個方法將 HTML 傳遞給
RenderHtmlAsPdf
概述
在本教程之後,您將能夠:
- 從不同來源轉換為PDF,例如URL、HTML、MVC視圖。
- 使用用於不同輸出 PDF 設定的高級選項
- 將您的專案部署到 Linux 和 Windows
- 使用 PDF 文檔操作功能
- 添加頁首和頁尾、合併文件、新增印章
-
使用 Dockers工作
這種廣泛的 .NET Core HTML 轉 PDF 功能將有助於滿足各種項目需求。
開始使用 IronPDF
立即在您的專案中使用IronPDF,並享受免費試用。
第一步
1. 安裝 IronPDF Library 免費版
IronPDF 可以安裝並用於所有的 .NET 專案類型,如 Windows 應用程式、ASP.NET MVC 和 .NET Core 應用程式。
要將IronPDF庫添加到我們的項目中,我們有兩種方法:一是通過Visual Studio編輯器使用NuGet進行安裝,二是使用命令行通過包控制台管理器進行安裝。
使用 NuGet 安裝
要使用 NuGet 將 IronPDF 庫添加到我們的項目中,我們可以使用可視化界面(NuGet 套件管理器)或透過使用套件管理器控制台輸入命令。
1.1.1 使用 NuGet 套件管理員
1- Right click on project name -> Select Manage NuGet Package
2- From browser tab -> search for IronPdf -> Install
3- 點擊確定
4- Done!
1.1.2 使用 NuGet 套件管理器控制台
1- From Tools -> NuGet Package Manager -> Package Manager Console
2- Run command -> Install-Package IronPdf
操作教程
2. 將網站轉換為 PDF
範例:ConvertUrlToPdf 控制台應用程式
按照以下步驟創建一個新的 Asp.NET MVC 專案
1- Open Visual Studio
2- 選擇建立新專案
3- Choose Console App (.NET Core)
4- Give our sample name “ConvertUrlToPdf” and click create
5- Now we have a console application created
6- Add IronPdf => click install
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");
8- Run and check created file wiki.pdf
3. 轉換.NET Core的HTML為PDF
Sample: ConvertHTMLToPdf Console application
To render HTML to PDF we have two ways:
1- Write HTML into string then render it
2- Write HTML into file and pass it path to IronPDF to render it
Rendering the HTML string sample code will look like this.
: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");
生成的 PDF 將如下所示。
4. 將 MVC 視圖轉換為 PDF
範例:TicketsApps .NET Core MVC 應用程式
讓我們實作一個真實生活中的例子。 我選擇了一個線上購票網站。打開網站,導航至「訂票」,填寫所需資訊,然後將你的副本下載為PDF文件。
我們將依照以下步驟進行:
建立專案
-
選擇「ASP.NET Core Web 應用程式 (Model-View-Controller)」專案。
-
將專案命名為“TicketsApps”。
-
讓我們使用啟用了 Linux Docker 的 .NET 8。 在 Dockerfile 中,將 "USER app" 更改為 "USER root"。 這將確保授予庫足夠的權限。
- 現在已準備好了。
添加客戶模型
-
右鍵點擊“Models”文件夾並添加類。
-
將模型命名為“ClientModel”,然後點擊新增。
- 向 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; }
}
添加客戶服務
-
創建一個文件夾並將其命名為“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;
}
}
設計訂票頁面
-
在方案總管中,右鍵點擊“Controllers”文件夾並添加一個控制器。
-
將其命名為 "BookTicketController"。
-
右鍵點擊索引函式(或我們稱之為動作),然後選擇「添加視圖」。
-
添加名為“index”的視圖。
- 將 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>
}
- 在我們的網站中添加導航連結,以便訪客前往我們的新預約頁面。 這可以通過更新現有路徑中的佈局來完成(Views -> Shared -> _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] 的另一個 index 動作,以告知 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);
}
錯誤訊息範例

- 在「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; }
}
- 將 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);
}
- 右鍵單擊 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 文件,添加另一個 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>
-
在「wwwroot/css」資料夾中新增以下「ticket.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");
}
- 在 "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();
}
}
}
- 運行應用程式並填寫票務資訊,然後點擊「保存」。
- View the generated ticket
下載 PDF 票券
要將票證下載為PDF格式,請點擊「下載PDF」。 您將收到一份包含門票的PDF文件。
您可以下載本指南的完整代碼。它以壓縮檔的形式提供,您可以在Visual Studio中打開。 點擊此處下載項目。
5. .NET PDF 渲染選項圖表
我們有一些高級選項,可定義 PDF 渲染選項,如調整邊距,
紙張方向、紙張大小等。
以下是一個表格,用於說明多種不同選項。
Class | ChromePdfRenderer | |
---|---|---|
Description | Used to define PDF print out options, like paper size, DPI, headers and footers | |
Properties / functions | Type | Description |
CustomCookies | Dictionary<string, string> | Custom cookies for the HTML render. Cookies do not persist between renders and must be set each time. |
PaperFit | VirtualPaperLayoutManager | A manager for setting up virtual paper layouts, controlling how content will be laid out on PDF "paper" pages. Includes options for Default Chrome Behavior, Zoomed, Responsive CSS3 Layouts, Scale-To-Page & Continuous Feed style PDF page setups. |
UseMarginsOnHeaderAndFooter | UseMargins | Use margin values from the main document when rendering headers and footers. |
CreatePdfFormsFromHtml | bool | Turns all HTML form elements into editable PDF forms. Default value is true. |
CssMediaType | PdfCssMediaType | Enables Media="screen" CSS Styles and StyleSheets. Default value is PdfCssMediaType.Screen. |
CustomCssUrl | string | Allows a custom CSS style-sheet to be applied to HTML before rendering. May be a local file path or a remote URL. Only applicable when rendering HTML to PDF. |
EnableJavaScript | bool | Enables JavaScript and JSON to be executed before the page is rendered. Ideal for printing from Ajax / Angular Applications. Default value is false. |
EnableMathematicalLaTex | bool | Enables rendering of Mathematical LaTeX Elements. |
Javascript | string | A custom JavaScript string to be executed after all HTML has loaded but before PDF rendering. |
JavascriptMessageListener | StringDelegate | A method callback to be invoked whenever a browser JavaScript console message becomes available. |
FirstPageNumber | int | First page number to be used in PDF Headers and Footers. Default value is 1. |
TableOfContents | TableOfContentsTypes | Generates a table of contents at the location in the HTML document where an element is found with id "ironpdf-toc". |
GrayScale | bool | Outputs a black-and-white PDF. Default value is false. |
TextHeader | ITextHeaderFooter | Sets the footer content for every PDF page as text, supporting 'mail-merge' and automatically turning URLs into hyperlinks. |
TextFooter | ||
HtmlHeader | HtmlHeaderFooter | Sets the header content for every PDF page as HTML. Supports 'mail-merge'. |
HtmlFooter | ||
InputEncoding | Encoding | The input character encoding as a string. Default value is Encoding.UTF8. |
MarginTop | double | Top PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25. |
MarginRight | double | Right PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25. |
MarginBottom | double | Bottom PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25. |
MarginLeft | double | Left PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25. |
PaperOrientation | PdfPaperOrientation | The PDF paper orientation, such as Portrait or Landscape. Default value is Portrait. |
PaperSize | PdfPaperSize | Sets the paper size |
SetCustomPaperSizeinCentimeters | double | Sets the paper size in centimeters. |
SetCustomPaperSizeInInches | Sets the paper size in inches. | |
SetCustomPaperSizeinMilimeters | Sets the paper size in millimeters. | |
SetCustomPaperSizeinPixelsOrPoints | Sets the paper size in screen pixels or printer points. | |
PrintHtmlBackgrounds | Boolean | Indicates whether to print background-colors and images from HTML. Default value is true. |
RequestContext | RequestContexts | Request context for this render, determining isolation of certain resources such as cookies. |
Timeout | Integer | Render timeout in seconds. Default value is 60. |
Title | String | PDF Document Name and Title metadata, useful for mail-merge and automatic file naming in the IronPdf MVC and Razor extensions. |
ForcePaperSize | Boolean | Force page sizes to be exactly what is specified via IronPdf.ChromePdfRenderOptions.PaperSize by resizing the page after generating a PDF from HTML. Helps correct small errors in page size when rendering HTML to PDF. |
WaitFor | WaitFor | A wrapper object that holds configuration for wait-for mechanism for users to wait for certain events before rendering. By default, it will wait for nothing. |
6. .NET PDF 頁首頁尾選項圖表
Class | TextHeaderFooter | |
---|---|---|
Description | Used to define text header and footer display options | |
Properties \ functions | Type | Description |
CenterText | string | Set the text in centered/left/right of PDF header or footer. Can also merge metadata using strings placeholders: {page}, {total-pages}, {url}, {date}, {time}, {html-title}, {pdf-title} |
LeftText | ||
RightText | ||
DrawDividerLine | Boolean | Adds a horizontal line divider between the header/footer and the page content on every page of the PDF document. |
DrawDividerLineColor | Color | The color of the divider line specified for IronPdf.TextHeaderFooter.DrawDividerLine. |
Font | PdfFont | Font family used for the PDF document. Default is IronSoftware.Drawing.FontTypes.Helvetica. |
FontSize | Double | Font size in pixels. |
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");
8. Docker .NET Core 應用程序
8.1. 什麼是 Docker?
Docker 是一套平台即服務產品,利用作業系統層級的虛擬化技術來交付名為容器的軟件包。 容器彼此隔離,並捆綁它們自己的軟體、庫和配置文件; 他們可以通過明確定義的通道相互溝通。
您可以在這裡了解更多關於 Docker 和 ASP.NET Core 應用程式。
我們將直接進入使用 Docker 的工作,但如果您想了解更多資訊,這裡有一個很棒的 .NET 和 Docker 的介紹,以及更多關於如何 為 .NET 核心應用程式構建容器 的資訊。
讓我們一起開始使用 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");
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();
}
將另一個 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");
將 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");
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");
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");
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");
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");
進階範例以獲得更多控制:
: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);
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);
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);
13. 添加 PDF 水印
以下是如何給 PDF 頁面添加水印的範例。
: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");
浮水印具有有限的選項和功能集。 為了更大的控制,您可以使用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");
快速指南
GitHub 教程访问
通過 GitHub 探索此教程和更多內容。使用項目和源代碼是學習和應用到您自己的 PDF .NET Core 需求和用例的最佳方式。
在 .NET Core 中生成 PDF 教程保留 PDF CSharp 速查表
使用我們便捷的參考文件,在您的 .NET 應用程式中開發 PDF。 提供快速訪問常見功能和範例,以便在 C# 和 VB.NET 中生成和編輯 PDF,這個可以分享的工具幫助您節省時間和精力,以便在您的項目中開始使用 IronPDF 和常見的 PDF 要求。
保留速查表