如何在登錄驗證後將 HTML 轉換為 PDF

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

如果可能的話,處理登入的最佳方式是避免登入,並直接從檔案或字串渲染 HTML。

開始使用 IronPDF

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

第一步:
green arrow pointer



最佳實踐

IronPDF 支持 TLS 網絡認證。(使用者名稱和密碼)非常安全,且 .NET 網頁應用程式可以輕鬆支援:ChromeHttpLoginCredentials API

最佳做法是使用System.Net.WebClientHttpClient來下載HTML和任何資產。 這完全支持標頭、登入以及您可能需要的其他所有功能。一旦下載到記憶體或磁碟,IronPDF 可以將您的 HTML 轉換為 PDF。 可以使用 HtmlAgilityPack 發現諸如樣式表和圖片之類的資產,然後也可以使用 System.Net.WebClient 進行下載。

string html;
using (WebClient client = new WebClient()) {
    html = client.DownloadString("http://www.google.com");
}
HtmlDocument doc = new HtmlDocument();        
doc.LoadHtml(html);
foreach(HtmlNode img in doc.DocumentNode.SelectNodes("//img")) {
    Console.WriteLine(img.GetAttributeValue("src", null));
}
string html;
using (WebClient client = new WebClient()) {
    html = client.DownloadString("http://www.google.com");
}
HtmlDocument doc = new HtmlDocument();        
doc.LoadHtml(html);
foreach(HtmlNode img in doc.DocumentNode.SelectNodes("//img")) {
    Console.WriteLine(img.GetAttributeValue("src", null));
}
Dim html As String
Using client As New WebClient()
	html = client.DownloadString("http://www.google.com")
End Using
Dim doc As New HtmlDocument()
doc.LoadHtml(html)
For Each img As HtmlNode In doc.DocumentNode.SelectNodes("//img")
	Console.WriteLine(img.GetAttributeValue("src", Nothing))
Next img
VB   C#

[{我(任何相對 URL 都可以使用 System.Uri 類的重載構造函數重新設定為絕對 URL。 若要重新定位整個 HTML 文件中的相對路徑,請添加一個

使用 HtmlAgilityPack 添加標籤到頭部。 範例.)}]

使用網絡認證登入

大多數 ASP.NET 應用程式支援網路驗證,比 HTML 表單提交更可靠。

:path=/static-assets/pdf/content-code-examples/how-to/logins-username-password.cs
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");
Imports IronPdf
Imports System

Private renderer As New ChromePdfRenderer With {
	.LoginCredentials = New ChromeHttpLoginCredentials() With {
		.NetworkUsername = "testUser",
		.NetworkPassword = "testPassword"
	}
}

Private uri = New Uri("http://localhost:51169/Invoice")

' Render web URL to PDF
Private pdf As PdfDocument = renderer.RenderUrlAsPdf(uri)

' Export PDF
pdf.SaveAs("UrlToPdfExample.Pdf")
VB   C#

使用 HTML 表單登入

要透過將資料發送到 HTML 表單來登入,也可以使用 ChromeHttpLoginCredentials 類別,就像前面的例子一樣。 請參閱IronPDF的ChromeHttpLoginCredentials API.

請考慮:

  • 登入資料必須發送至 HTML 表單的 ACTION 屬性中指定的 URL。 This should be set as the *登入表單網址* 屬性的 HttpLoginCredentials。 這可能與您實際想要轉換為 PDF 的 URL 不同。
  • 要發送的數據應該代表 HTML 表單中的每一個輸入和文本域。 name 屬性定義每個變數的名稱(不是常被誤解的 ID).
  • 某些網站可能會積極防範這種機器登入。

MVC

以下變通方法允許將 .NET MVC 視圖以程式方式呈現為字串,這在避免 MVC 登錄同時忠實呈現視圖時非常有用。

public static string RenderPartialViewToString(this Controller controller, string viewPath, object model = null)
{
    try
    {
        var context = controller.ControllerContext;

        controller.ViewData.Model = model;

        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(context, viewPath);

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

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

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

            return sw.GetStringBuilder().ToString();
        }
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}
public static string RenderPartialViewToString(this Controller controller, string viewPath, object model = null)
{
    try
    {
        var context = controller.ControllerContext;

        controller.ViewData.Model = model;

        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(context, viewPath);

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

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

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

            return sw.GetStringBuilder().ToString();
        }
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}
<System.Runtime.CompilerServices.Extension> _
Public Function RenderPartialViewToString(ByVal controller As Controller, ByVal viewPath As String, Optional ByVal model As Object = Nothing) As String
	Try
		Dim context = controller.ControllerContext

		controller.ViewData.Model = model

		Using sw = New StringWriter()
			Dim viewResult = ViewEngines.Engines.FindPartialView(context, viewPath)

			If viewResult.View Is Nothing Then
				Throw New Exception($"Partial view {viewPath} could not be found.")
			End If

			Dim viewContext As New ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw)

			viewResult.View.Render(viewContext, sw)
			viewResult.ViewEngine.ReleaseView(context, viewResult.View)

			Return sw.GetStringBuilder().ToString()
		End Using
	Catch ex As Exception
		Return ex.Message
	End Try
End Function
VB   C#