如何在登錄驗證後將 HTML 轉換為 PDF
應對登錄的最佳方式是在可能的情況下避免登錄,直接從文件或字符串渲染 HTML。
如何在登錄驗證後將 HTML 轉換為 PDF
立即開始在您的專案中使用IronPDF,並享受免費試用。
查看 IronPDF 上 Nuget 快速安裝和部署。已被下載超過800萬次,它正用C#改變PDF。
Install-Package IronPdf
請考慮安裝 IronPDF DLL 直接下載並手動安裝到您的專案或GAC表單: IronPdf.zip
手動安裝到您的項目中
下載DLL最佳實踐
IronPDF 支援 TLS 網路認證 (使用者名稱和密碼) 這是極其安全的,.NET 網頁應用程式可以輕鬆支援它: ChromeHttpLoginCredentials API
最佳做法是使用System.Net.WebClient
或HttpClient
下載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
請注意
System.Uri
類的重載構造函數轉換為絕對 URL。要在整個 HTML 文檔中重新設定任何相對路徑,請添加使用網絡身份驗證登錄
大多數 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")
使用 HTML 表單登入
透過將資料傳送到 HTML 表單進行登入也可以使用 ChromeHttpLoginCredentials 類別來實現,如前例所示。參見 IronPDF 的 ChromeHttpLoginCredentials API.
請考慮:
- 登錄數據必須發送到HTML表單中指定的ACTION屬性中的URL。 這應設定為*登入表單網址* 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