如何使用 Cookies 與 IronPDF
在網路技術的背景下,Cookies 是網站儲存在用戶電腦或設備上的小數據片段。它們用於多種目的,從會話管理(幫助使用者保持登入狀態),到跟踪和分析(收集用戶行為數據以改善網站)。 然而,使用 cookies 引發了有關隱私的討論,導致了像 GDPR 和 CCPA 這樣的法規出現,而現代網絡瀏覽器則提供用戶對 cookie 管理的控制以解決這些問題。
開始使用 IronPDF
立即在您的專案中使用IronPDF,並享受免費試用。
如何使用 Cookies 與 IronPDF
- 從NuGet下載IronPDF
- 準備 HTML 內容以使用自定義 cookies 呈現
- 配置 請求上下文 啟用使用 cookies 的屬性
- 使用
應用Cookies
應用 cookies 的方法 - 使用 自定義Cookies 屬性來實現自定義 Cookies
應用 Cookie 範例
在使用方法應用 cookies 之前,將 RequestContext 屬性設置為 RequestContexts.Global。 然後,創建 ChromeHttpLoginCredentials 類別並將其傳遞給 ApplyCookies
方法。 渲染器現在已準備好用於將帶有 cookies 的 HTML 內容渲染為 PDF。
:path=/static-assets/pdf/content-code-examples/how-to/cookies-apply-cookies.cs
using IronPdf;
// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.RequestContext = IronPdf.Rendering.RequestContexts.Global;
ChromeHttpLoginCredentials credentials = new ChromeHttpLoginCredentials() {
NetworkUsername = "testUser",
NetworkPassword = "testPassword"
};
string uri = "http://localhost:51169/Invoice";
// Apply cookies
renderer.ApplyCookies(uri, credentials);
Imports IronPdf
' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()
renderer.RenderingOptions.RequestContext = IronPdf.Rendering.RequestContexts.Global
Dim credentials As New ChromeHttpLoginCredentials() With {
.NetworkUsername = "testUser",
.NetworkPassword = "testPassword"
}
Dim uri As String = "http://localhost:51169/Invoice"
' Apply cookies
renderer.ApplyCookies(uri, credentials)
RequestContexts 枚舉:此枚舉定義了用於建立個別渲染之間關係的瀏覽器請求上下文。 管理Cookies和用戶偏好設定是必不可少的。
- 隔離:創建一個與先前或未來渲染隔離的新請求上下文。 建議確保當前渲染不受之前渲染的影響。
- 全局:使用全局請求上下文,這個上下文在所有渲染之間共享。 在某些情況下有助於在渲染間保持特定瀏覽器狀態。
- 自動:默認為 IronPdf.Rendering.RequestContexts.Isolated,但如果用戶曾經調用 IronPdf.ChromePdfRenderer.ApplyCookies,則切換到 IronPdf.Rendering.RequestContexts.Global。(System.String,IronPdf.ChromeHttpLoginCredentials).
套用自訂 Cookie 範例
在請求中使用自定義 cookie 需要設置 CustomCookies 屬性。 此屬性接受一個鍵值對字典,鍵和值都是字串。
:path=/static-assets/pdf/content-code-examples/how-to/cookies-apply-custom-cookies.cs
using IronPdf;
using System;
using System.Collections.Generic;
// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
Dictionary<string, string> customCookies = new Dictionary<string, string>();
// Apply custom cookies
renderer.RenderingOptions.CustomCookies = customCookies;
var uri = new Uri("https://localhost:44362/invoice");
PdfDocument pdf = renderer.RenderUrlAsPdf(uri);
Imports IronPdf
Imports System
Imports System.Collections.Generic
' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()
Private customCookies As New Dictionary(Of String, String)()
' Apply custom cookies
renderer.RenderingOptions.CustomCookies = customCookies
Dim uri As New Uri("https://localhost:44362/invoice")
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf(uri)