IRONSOFTWAREHOME

在C&#35中,在身份驗證後進行HTML轉PDF的轉換

Curtis Chau
Curtis Chau
Updated: 2026年6月4日

要在C#中進行身份驗證後的HTML轉PDF轉換,使用IronPDF的HttpClient下載HTML。 此方法有效處理網路身份驗證和HTML表單登錄。

快速入門:使用IronPDF在身份驗證後的HTML轉PDF

使用IronPDF的API轉換在登錄表單後的HTML頁面為PDF。 本指南演示了用於身份驗證和受保護內容檢索的ChromeHttpLoginCredentials。 通過簡單的程式碼範例處理網路身份驗證和HTML表單登錄。

  1. 1Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. 2Copy and run this code snippet.

    new ChromePdfRenderer { LoginCredentials = new ChromeHttpLoginCredentials("username","password") }
        .RenderUrlAsPdf("https://example.com/protected")
        .SaveAs("secure.pdf");
    C#
  3. 3Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer

處理登錄身份驗證的最佳實踐是什麼?

IronPDF通過ChromeHttpLoginCredentials API支持TLS網路身份驗證(使用者名和密碼)。 有關各種登錄場景的全面指南,請參閱TLS網站和系統登錄教程

建議的方法是使用HttpClient下載HTML和資源。 此方法支持標頭、登錄和其他要求。 下載到記憶體或磁碟後,IronPDF將HTML轉換為PDF。 使用System.Net.WebClient

// Your authentication token
string accessToken = "your-access-token";

// Download HTML content from a URL with authentication
using (WebClient client = new WebClient())
{
    // Add authentication headers if needed
    client.Headers.Add("Authorization", "Bearer " + accessToken);

    // Download the HTML string
    string html = client.DownloadString("http://www.example.com/protected-content");

    // Load the HTML into an HtmlDocument for parsing
    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(html);

    // Extract all image sources for downloading
    foreach(HtmlNode img in doc.DocumentNode.SelectNodes("//img"))
    {
        string imgSrc = img.GetAttributeValue("src", null);
        Console.WriteLine($"Found image: {imgSrc}");

        // Download each image asset
        if (!string.IsNullOrEmpty(imgSrc))
        {
            string fileName = Path.GetFileName(imgSrc);
            client.DownloadFile(imgSrc, fileName);
        }
    }

    // Convert the downloaded HTML to PDF
    var renderer = new ChromePdfRenderer();
    var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs("authenticated-content.pdf");
}
C#
Please note: 使用重載的System.Uri構造函式將相對URL重設為絕對URL。 要在HTML文件中重設所有的相對路徑,請使用HtmlAgilityPack將<base>標籤新增到標頭中。 Example. 有關處理URL和資產的更多資訊,請參閱基本URL和資產編碼指南

為什麼我應該先下載HTML內容?

在轉換之前下載HTML內容提供幾個好處:

  1. 完全控制:在轉換之前修改HTML、修復斷鏈或注入身份驗證令牌
  2. 資產管理:下載並快取外部資源,如圖像、CSS和JavaScript文件
  3. 身份驗證靈活性:使用任何.NET身份驗證機制,包括OAuth、JWT令牌或自定義標頭
  4. 性能:快取經常存取的內容以降低伺服器負載
  5. 除錯:檢查正在轉換的精確HTML,以排除故障

有關需要cookie和會話的複雜身份驗證場景,請參閱Cookies指南,該指南解釋了PDF轉換期間的身份驗證狀態管理。

我如何處理圖像和樣式表等資產?

在轉換經過身份驗證的頁面時,外部資產通常需要相同的身份驗證。 這是一個使用HttpClient的全面方法:

public async Task<string> DownloadAuthenticatedHtmlWithAssets(string url, string authToken)
{
    using (var client = new HttpClient())
    {
        // Set authentication header
        client.DefaultRequestHeaders.Authorization = 
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken);
        
        // Download the main HTML
        string html = await client.GetStringAsync(url);
        
        // Parse HTML to find assets
        var doc = new HtmlDocument();
        doc.LoadHtml(html);
        
        // Create a base URI for resolving relative paths
        var baseUri = new Uri(url);
        
        // Download CSS files
        var cssLinks = doc.DocumentNode.SelectNodes("//link[@rel='stylesheet']");
        if (cssLinks != null)
        {
            foreach (var link in cssLinks)
            {
                string href = link.GetAttributeValue("href", "");
                if (!string.IsNullOrEmpty(href))
                {
                    var cssUri = new Uri(baseUri, href);
                    string cssContent = await client.GetStringAsync(cssUri);
                    
                    // Embed CSS directly in the HTML
                    var styleNode = doc.CreateElement("style");
                    styleNode.InnerHtml = cssContent;
                    doc.DocumentNode.SelectSingleNode("//head").AppendChild(styleNode);
                    
                    // Remove the external link
                    link.Remove();
                }
            }
        }
        
        // Return the modified HTML with embedded assets
        return doc.DocumentNode.OuterHtml;
    }
}

有哪些工具可以幫助HTML解析?

HtmlAgilityPack是.NET中最流行的HTML解析程式庫,但也有其他選擇:

  1. HtmlAgilityPack:最佳一般HTML解析和操作
  2. AngleSharp:現代、標準相容的HTML解析器,支持CSS選擇器
  3. CsQuery:適合習慣jQuery的C#開發者的jQuery風格語法
  4. 正則表達式:適用於簡單的提取任務(不建議用於複雜HTML)

ChromeHttpLoginCredentials

我如何使用網路身份驗證登錄?

大多數ASP.NET應用程式支持網路身份驗證,比HTML表單提交更可靠。 IronPDF通過ChromeHttpLoginCredentials類提供對基本、摘要和NTLM身份驗證的內建支持。 有關額外標頭自定義,請參閱HTTP請求標頭指南

using IronPdf;
using System;

ChromePdfRenderer renderer = new ChromePdfRenderer
{
    // setting login credentials to bypass basic authentication
    LoginCredentials = new ChromeHttpLoginCredentials()
    {
        NetworkUsername = "testUser",
        NetworkPassword = "testPassword"
    }
};

var uri = new Uri("http://localhost:51169/Invoice");

// Render web URL to PDF
PdfDocument pdf = renderer.RenderUrlAsPdf(uri);

// Export PDF
pdf.SaveAs("UrlToPdfExample.Pdf");

為什麼網路身份驗證比表單提交更可靠?

網路身份驗證比HTML表單提交具有多個優勢:

  1. 標準化協議:使用依據RFC標準的HTTP身份驗證標頭
  2. 瀏覽器整合:Chrome渲染引擎無縫處理身份驗證
  3. 會話管理:自動處理身份驗證挑戰和會話持久性
  4. 安全性:憑據通過標頭而不是表單資料安全地傳輸
  5. 相容性:適用於大多數企業身份驗證系統 (Active Directory, LDAP)

進行網路身份驗證需要什麼憑據?

不同的身份驗證型別需要不同的憑據:

// Basic Authentication (most common)
var basicAuth = new ChromeHttpLoginCredentials
{
    NetworkUsername = "user@domain.com",
    NetworkPassword = "password123"
};

// NTLM/Windows Authentication
var ntlmAuth = new ChromeHttpLoginCredentials
{
    NetworkUsername = "DOMAIN\\username", // Include domain
    NetworkPassword = "password123"
};

// Custom authentication headers
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HttpRequestHeaders = new Dictionary<string, string>
{
    { "X-API-Key", "your-api-key" },
    { "Authorization", "Bearer " + jwtToken }
};
C#

我如何排除身份驗證失敗的故障?

常見的身份驗證問題及解決方案:

  1. 401 未授權:檢查憑據和身份驗證型別
  2. 403 禁止存取:使用者已驗證但缺乏權限
  3. 超時錯誤:為慢速身份驗證系統增加Timeout
  4. 證書錯誤:適當配置TLS/SSL設置

啟用除錯以診斷問題:

// Enable detailed logging
IronPdf.Logging.Logger.EnableDebugging = true;
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log";
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;

// Test authentication
try 
{
    var pdf = renderer.RenderUrlAsPdf("https://secure.example.com");
    pdf.SaveAs("authenticated.pdf");
}
catch (Exception ex)
{
    Console.WriteLine($"Authentication failed: {ex.Message}");
    // Check IronPdf.log for detailed error information
}

我最喜歡的程式庫是IronPDF。它允許快速高效地操作PDF文件。它還有許多有價值的功能,例如導出到PDF/A格式和數位簽署PDF文件。

Milan Jovanovic

Microsoft MVP

查看案例研究

IronOCR意味著我們每年可以從手動處理中節省$40,000,同時提高生產力,釋放資源以進行高影響的任務。我會強烈推薦它。

Brent Matzelle

首席技術官,OPYN

查看案例研究

IronSuite在我們的運營中扮演著至關重要的角色。這些工具增加了包括建立平面圖和改善庫存管理在內的業務效率。

David Jones

首席軟體工程師,Agorus Build

查看案例研究

我如何使用HTML表單登錄?

要通過將資料發送到HTML表單進行登錄,使用ChromeHttpLoginCredentials類。 See IronPDF's ChromeHttpLoginCredentials API.

考慮以下幾點:

  • 將登錄資料發送到HTML表單的ACTION屬性中指定的URL。 將此設為HttpLoginCredentials。 這可能與您想要渲染為PDF的URL不同。
  • 發送表示HTML表單中每個輸入和textarea的資料。 name屬性定義每個變數名(而不是id)。
  • 一些網站會主動防止機器登錄。
// Configure form-based login
var formLogin = new ChromeHttpLoginCredentials
{
    LoginFormUrl = "https://example.com/login",
    LoginFormData = new Dictionary<string, string>
    {
        {"username", "user@example.com"},
        {"password", "securePassword123"},
        {"rememberMe", "true"},
        {"csrf_token", "abc123"} // Include any hidden fields
    }
};

var renderer = new ChromePdfRenderer
{
    LoginCredentials = formLogin,
    RenderingOptions = new ChromePdfRenderOptions
    {
        RenderDelay = 3000, // Allow time for login redirect
        EnableJavaScript = true
    }
};

// The actual page you want to convert (after login)
var pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard");
pdf.SaveAs("dashboard.pdf");

我需要捕獲什麼表單資料?

要通過HTML表單成功進行身份驗證,請捕獲所有表單輸入:

// Use this helper method to extract form fields
public Dictionary<string, string> ExtractFormFields(string loginPageHtml)
{
    var formData = new Dictionary<string, string>();
    var doc = new HtmlDocument();
    doc.LoadHtml(loginPageHtml);
    
    // Find all input fields
    var inputs = doc.DocumentNode.SelectNodes("//input");
    if (inputs != null)
    {
        foreach (var input in inputs)
        {
            string name = input.GetAttributeValue("name", "");
            string value = input.GetAttributeValue("value", "");
            string type = input.GetAttributeValue("type", "text");
            
            if (!string.IsNullOrEmpty(name))
            {
                // Handle different input types
                switch (type.ToLower())
                {
                    case "checkbox":
                        if (input.Attributes["checked"] != null)
                            formData[name] = "on";
                        break;
                    case "radio":
                        if (input.Attributes["checked"] != null)
                            formData[name] = value;
                        break;
                    default:
                        formData[name] = value;
                        break;
                }
            }
        }
    }
    
    // Don't forget select elements
    var selects = doc.DocumentNode.SelectNodes("//select");
    if (selects != null)
    {
        foreach (var select in selects)
        {
            string name = select.GetAttributeValue("name", "");
            var selected = select.SelectSingleNode(".//option[@selected]");
            if (selected != null && !string.IsNullOrEmpty(name))
            {
                formData[name] = selected.GetAttributeValue("value", "");
            }
        }
    }
    
    return formData;
}

如何找到正確的表單動作URL?

表單動作URL對於成功身份驗證至關重要:

public string ExtractFormAction(string loginPageUrl, string loginPageHtml)
{
    var doc = new HtmlDocument();
    doc.LoadHtml(loginPageHtml);
    
    // Find the login form
    var form = doc.DocumentNode.SelectSingleNode("//form[contains(@action, 'login') or contains(@id, 'login') or contains(@class, 'login')]");
    
    if (form == null)
    {
        // Try finding any form with password field
        form = doc.DocumentNode.SelectSingleNode("//form[.//input[@type='password']]");
    }
    
    if (form != null)
    {
        string action = form.GetAttributeValue("action", "");
        
        // Resolve relative URLs
        if (!string.IsNullOrEmpty(action))
        {
            var baseUri = new Uri(loginPageUrl);
            var actionUri = new Uri(baseUri, action);
            return actionUri.ToString();
        }
    }
    
    // Default to the login page URL if no action found
    return loginPageUrl;
}

表單身份驗證的常見問題是什麼?

  1. CSRF令牌:許多表單包括會過期的防篡改令牌
  2. JavaScript驗證:某些表單需要JavaScript執行
  3. 多步身份驗證:需要多個頁面的表單
  4. CAPTCHA保護:人類驗證挑戰
  5. 會話超時:快速到期的登錄會話

ViewBag TempData Html

有關HTML到PDF轉換的全面指南,包括複雜的身份驗證場景,請存取HTML to PDF教程

我如何處理MVC身份驗證?

以下解決方案將.Net MVC視圖程式化為字串,避免MVC登錄同時忠實地渲染視圖。 此方法在轉換CSHTML到MVC Core的PDFMVC Framework時運行良好。

// Converts an MVC partial view to a string
public static string RenderPartialViewToString(this Controller controller, string viewPath, object model = null)
{
    try
    {
        // Set the model
        var context = controller.ControllerContext;
        controller.ViewData.Model = model;

        using (var sw = new StringWriter())
        {
            // Find the partial view
            var viewResult = ViewEngines.Engines.FindPartialView(context, viewPath);

            if (viewResult.View == null)
            {
                throw new Exception($"Partial view {viewPath} could not be found.");
            }

            // Create a view context
            var viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw);

            // Render the view
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(context, viewResult.View);

            return sw.GetStringBuilder().ToString();
        }
    }
    catch (Exception ex)
    {
        // Return error message if there is an exception
        return ex.Message;
    }
}

// Usage in an MVC Controller
public ActionResult GeneratePdf()
{
    // Render authenticated view to string
    var model = new InvoiceViewModel { /* populate model */ };
    string html = this.RenderPartialViewToString("~/Views/Invoice/Details.cshtml", model);
    
    // Convert to PDF
    var renderer = new ChromePdfRenderer();
    var pdf = renderer.RenderHtmlAsPdf(html);
    
    // Return PDF file
    return File(pdf.BinaryData, "application/pdf", "invoice.pdf");
}

為什麼將視圖渲染為字串而不是直接轉換?

將MVC視圖渲染為字串提供了幾個主要優勢:

  1. 身份驗證上下文:視圖在已驗證使用者上下文中渲染
  2. 完整的MVC管道:所有MVC功能正常工作,包括HtmlHelper, ViewBag助手
  3. 佈局支持:主頁面和佈局正確渲染
  4. 模型綁定:復雜視圖模型無縫運行
  5. 動作過濾器:安全和日誌過濾器正常執行

這個MVC解決方法的好處是什麼?

MVC字串渲染方法提供:

  • 安全性:無需暴露內部URL或繞過身份驗證
  • 性能:避免額外的HTTP請求
  • 一致性:與使用者在瀏覽器中看到的輸出相同
  • 靈活性:在PDF轉換之前修改HTML
  • 測試:輕鬆單元測試HTML生成

我如何將模型傳遞到渲染的視圖中?

這是一個包含複雜模型的全面範例:

public class InvoiceController : Controller
{
    private readonly IInvoiceService _invoiceService;
    
    public async Task<ActionResult> DownloadInvoicePdf(int invoiceId)
    {
        // Load data within authenticated context
        var invoice = await _invoiceService.GetInvoiceAsync(invoiceId);
        
        if (invoice == null || invoice.UserId != User.Identity.GetUserId())
        {
            return HttpNotFound();
        }
        
        // Create view model
        var viewModel = new InvoiceDetailsViewModel
        {
            Invoice = invoice,
            Company = await _invoiceService.GetCompanyDetailsAsync(),
            LineItems = await _invoiceService.GetLineItemsAsync(invoiceId),
            TaxDetails = await _invoiceService.GetTaxDetailsAsync(invoiceId)
        };
        
        // Render to HTML string
        string html = this.RenderPartialViewToString("~/Views/Invoice/DetailsPdf.cshtml", viewModel);
        
        // Add custom styling for PDF
        html = $@"
            <html>
            <head>
                <style>
                    body {{font-family: Arial, sans-serif;}}
                    .invoice-header {{background-color: #f0f0f0; padding: 20px;}}
                    .line-items {{width: 100%; border-collapse: collapse;}}
                    .line-items th, .line-items td {{border: 1px solid #ddd; padding: 8px;}}
                </style>
            </head>
            <body>
                {html}
            </body>
            </html>";
        
        // Convert to PDF with options
        var renderer = new ChromePdfRenderer
        {
            RenderingOptions = new ChromePdfRenderOptions
            {
                MarginTop = 20,
                MarginBottom = 20,
                MarginLeft = 10,
                MarginRight = 10,
                PrintHtmlBackgrounds = true
            }
        };
        
        var pdf = renderer.RenderHtmlAsPdf(html);
        
        // Add metadata
        pdf.MetaData.Author = "Invoice System";
        pdf.MetaData.Title = $"Invoice #{invoice.Number}";
        pdf.MetaData.CreationDate = DateTime.Now;
        
        return File(pdf.BinaryData, "application/pdf", $"Invoice-{invoice.Number}.pdf");
    }
}
C#

在實施任何身份驗證解決方案之前,請確保您已正確安裝IronPDF並配置您的授權密匙。

準備好看看您還能做什麼嗎? 存取我們的教程頁面:轉換PDFsRenderDelay

Frequently Asked Questions

當內容在登入表單後面時,我如何將 HTML 轉換為 PDF?

IronPDF 提供多種方法來將帶有登入身份驗證的 HTML 轉換為 PDF。您可以使用 ChromeHttpLoginCredentials API 進行 TLS 網路身份驗證,或者使用 System.Net.WebClient 或 HttpClient 下載 HTML 內容並帶有適當的身份驗證標頭,然後再使用 IronPDF 將其轉換為 PDF。

什麼是 ChromeHttpLoginCredentials,我該如何使用?

ChromeHttpLoginCredentials 是 IronPDF 用於處理網路身份驗證的 API。您可以通過在 ChromePdfRenderer 上設置 LoginCredentials 屬性並輸入您的使用者名和密碼來使用它,允許 IronPDF 在渲染受密碼保護的 URL 成為 PDF 時自動進行身份驗證。

我可以處理基於 HTML 表單的登入進行 PDF 轉換嗎?

是的,IronPDF 支持基於 HTML 表單的登入。建議的方法是使用 System.Net.WebClient 或 HttpClient 來處理登入過程,下載已驗證的 HTML 內容,然後使用 IronPDF 的 RenderHtmlAsPdf 方法將下載的 HTML 轉換為 PDF。

如何下載經過身份驗證頁面上的 HTML 資產,如圖片和樣式表?

您可以使用 HtmlAgilityPack 解析已下載的 HTML 並提取圖片和樣式表等資產的 URL。然後使用 System.Net.WebClient,以相同的身份驗證標頭下載每個資產,然後使用 IronPDF 將完整的 HTML 包轉換為 PDF。

處理身份驗證令牌或標頭的最佳實踐是什麼?

當使用 IronPDF 搭配身份驗證令牌時,使用 HttpClient 或 WebClient 搭配您的身份驗證標頭(如承載令牌)下載 HTML 。一旦將經過身份驗證的 HTML 內容儲存至記憶體或磁盤時,使用 IronPDF 的 ChromePdfRenderer 進行轉換為 PDF。

有沒有 MVC 登入身份驗證的解決方法?

有的,IronPDF 提供 MVC 登入身份驗證場景的解決方法。建議的方法是,首先使用標準 .NET HTTP 客戶端進行身份驗證並下載 HTML 內容,然後將經過身份驗證的 HTML 直接傳遞給 IronPDF 的渲染引擎,而非讓 IronPDF 處理身份驗證。

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...
Read More

準備開始了嗎?

Nuget Downloads 20,389,208版本:2026.7剛剛發布

立即獲取免費

立即獲取 30天試用金鑰

bullet_checked無需信用卡或註冊帳號
bullet_test在生產
環境中進行測試,且不顯示浮水印
bullet_calendar30 天全
功能產品
bullet_support試用期間提供 24/5 技術
支援
立即獲取您的免費30天試用密鑰
不需要信用卡或建立賬戶

免費試用IronPDF

5分鐘內設定完成

C# PDF DLL

下載DLL

立即下載

或者點擊此處下載Windows安裝程式。

  1. 下載並解壓IronPDF到類似~/Libs的位置,位於您的解決方案目錄中
  2. 在Visual Studio解決方案資源管理器,右鍵點選參考。選擇瀏覽,"IronPdf.dll"
C# 用於PDF的NuGet程式庫

使用NuGet安裝

                  Install-Package IronPdf
                
nuget.org/packages/IronPdf/
  1. 在解決方案資源管理器,右鍵點選參考,管理NuGet包
  2. 選擇瀏覽並搜尋"IronPdf"
  3. 選擇套件並安裝

授權從$999

有問題嗎?聯絡我們的開發團隊。

Key in blue circle

立即免費取得 30 天試用金鑰

bullet_checked無需信用卡或建立帳號
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費現場演示
Booking Badge related to IronPDF Product Demo

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立