ログイン認証をバックにしてHTMLをPDFに変換するC#
C#でログイン認証を通じてHTMLをPDFに変換するには、IronPDFのChromeHttpLoginCredentialsを使用してネットワーク認証するか、変換前にSystem.Net.WebClient/HttpClientを使用してHTMLをダウンロードします。 このアプローチでは、ネットワーク認証とHTMLフォームログインの両方を効果的に処理します。
IronPDFのAPIを使ってログインフォームの後ろにあるHTMLページをPDFに変換します。 このガイドでは、認証と保護されたコンテンツの取得のためのChromeHttpLoginCredentialsを示します。 ネットワーク認証とHTMLフォームログインの両方を、わかりやすいコード例で扱います。
-
1IronPDF を NuGet Package Manager でインストールします
-
2このコード スニペットをコピーして実行します。
new ChromePdfRenderer { LoginCredentials = new ChromeHttpLoginCredentials { NetworkUsername = "username", NetworkPassword = "password" } } .RenderUrlAsPdf("https://example.com/protected") .SaveAs("secure.pdf");New ChromePdfRenderer With { .LoginCredentials = New ChromeHttpLoginCredentials With { .NetworkUsername = "username", .NetworkPassword = "password" } }.RenderUrlAsPdf("https://example.com/protected").SaveAs("secure.pdf")New ChromePdfRenderer With { .LoginCredentials = New ChromeHttpLoginCredentials With { .NetworkUsername = "username", .NetworkPassword = "password" } }.RenderUrlAsPdf("https://example.com/protected").SaveAs("secure.pdf") -
3実際の環境でテストするためにデプロイする
今日からご自身のプロジェクトでIronPDFを使い始めるには、無料トライアルをお試しください。
最小限のワークフロー(5ステップ)
- C# IronPDFライブラリをダウンロード
- HTMLをダウンロードしてログインを回避
- LoginCredentialsプロパティでネットワーク認証を使用してログインする
- 認証用にHTMLフォームを使用
- MVCログイン認証の回避策
ログイン認証を取り扱うためのベストプラクティスとは?
IronPDFは、ChromeHttpLoginCredentials APIを介してTLSネットワーク認証(ユーザー名とパスワード)をサポートしています。 さまざまなログインシナリオに関する包括的なガイダンスについては、TLSウェブサイト&システムログインチュートリアルを参照してください。
推奨アプローチは、System.Net.WebClientまたはHttpClientを使用してHTMLとアセットをダウンロードすることです。 この方法では、ヘッダー、ログイン、その他の要件をサポートします。 メモリやディスクにダウンロードした後、IronPDFはHTMLをPDFに変換します。 スタイルシートや画像のようなアセットをHtmlAgilityPackを使用して抽出し、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");
}// 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");
}' Your authentication token
Dim accessToken As String = "your-access-token"
' Download HTML content from a URL with authentication
Using client As New WebClient()
' Add authentication headers if needed
client.Headers.Add("Authorization", "Bearer " & accessToken)
' Download the HTML string
Dim html As String = client.DownloadString("http://www.example.com/protected-content")
' Load the HTML into an HtmlDocument for parsing
Dim doc As New HtmlDocument()
doc.LoadHtml(html)
' Extract all image sources for downloading
For Each img As HtmlNode In doc.DocumentNode.SelectNodes("//img")
Dim imgSrc As String = img.GetAttributeValue("src", Nothing)
Console.WriteLine($"Found image: {imgSrc}")
' Download each image asset
If Not String.IsNullOrEmpty(imgSrc) Then
Dim fileName As String = Path.GetFileName(imgSrc)
client.DownloadFile(imgSrc, fileName)
End If
Next
' Convert the downloaded HTML to PDF
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("authenticated-content.pdf")
End Using' Your authentication token
Dim accessToken As String = "your-access-token"
' Download HTML content from a URL with authentication
Using client As New WebClient()
' Add authentication headers if needed
client.Headers.Add("Authorization", "Bearer " & accessToken)
' Download the HTML string
Dim html As String = client.DownloadString("http://www.example.com/protected-content")
' Load the HTML into an HtmlDocument for parsing
Dim doc As New HtmlDocument()
doc.LoadHtml(html)
' Extract all image sources for downloading
For Each img As HtmlNode In doc.DocumentNode.SelectNodes("//img")
Dim imgSrc As String = img.GetAttributeValue("src", Nothing)
Console.WriteLine($"Found image: {imgSrc}")
' Download each image asset
If Not String.IsNullOrEmpty(imgSrc) Then
Dim fileName As String = Path.GetFileName(imgSrc)
client.DownloadFile(imgSrc, fileName)
End If
Next
' Convert the downloaded HTML to PDF
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("authenticated-content.pdf")
End UsingSystem.Uriコンストラクタを使用してください。 HTMLドキュメント内のすべての相対パスをリベースするために、HtmlAgilityPackを使用してヘッダーに<base>タグを追加します。 例。 URLとアセットの処理に関する詳細は、基本URLとアセットエンコーディングガイドをご覧ください。なぜHTMLコンテンツを先にダウンロードすべきですか?
変換前にHTMLコンテンツをダウンロードすることで、いくつかの利点が得られます:
- 完全な制御: 変換前にHTMLの修正、リンクの修正、または認証トークンの注入
- アセット管理: 画像、CSS、JavaScriptファイルなどの外部リソースをダウンロードしてキャッシュ
- 認証の柔軟性: OAuth、JWTトークン、カスタムヘッダーなど、あらゆる.NET認証メカニズムを使用可能
- パフォーマンス: よくアクセスするコンテンツをキャッシュし、サーバーロードを軽減
- デバッグ: 問題を解決するために変換される正確なHTMLを検査
クッキーとセッションを含む複雑な認証シナリオについては、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;
}
}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;
}
}Public Async Function DownloadAuthenticatedHtmlWithAssets(url As String, authToken As String) As Task(Of String)
Using client As New HttpClient()
' Set authentication header
client.DefaultRequestHeaders.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken)
' Download the main HTML
Dim html As String = Await client.GetStringAsync(url)
' Parse HTML to find assets
Dim doc As New HtmlDocument()
doc.LoadHtml(html)
' Create a base URI for resolving relative paths
Dim baseUri As New Uri(url)
' Download CSS files
Dim cssLinks = doc.DocumentNode.SelectNodes("//link[@rel='stylesheet']")
If cssLinks IsNot Nothing Then
For Each link In cssLinks
Dim href As String = link.GetAttributeValue("href", "")
If Not String.IsNullOrEmpty(href) Then
Dim cssUri As New Uri(baseUri, href)
Dim cssContent As String = Await client.GetStringAsync(cssUri)
' Embed CSS directly in the HTML
Dim styleNode = doc.CreateElement("style")
styleNode.InnerHtml = cssContent
doc.DocumentNode.SelectSingleNode("//head").AppendChild(styleNode)
' Remove the external link
link.Remove()
End If
Next
End If
' Return the modified HTML with embedded assets
Return doc.DocumentNode.OuterHtml
End Using
End FunctionPublic Async Function DownloadAuthenticatedHtmlWithAssets(url As String, authToken As String) As Task(Of String)
Using client As New HttpClient()
' Set authentication header
client.DefaultRequestHeaders.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken)
' Download the main HTML
Dim html As String = Await client.GetStringAsync(url)
' Parse HTML to find assets
Dim doc As New HtmlDocument()
doc.LoadHtml(html)
' Create a base URI for resolving relative paths
Dim baseUri As New Uri(url)
' Download CSS files
Dim cssLinks = doc.DocumentNode.SelectNodes("//link[@rel='stylesheet']")
If cssLinks IsNot Nothing Then
For Each link In cssLinks
Dim href As String = link.GetAttributeValue("href", "")
If Not String.IsNullOrEmpty(href) Then
Dim cssUri As New Uri(baseUri, href)
Dim cssContent As String = Await client.GetStringAsync(cssUri)
' Embed CSS directly in the HTML
Dim styleNode = doc.CreateElement("style")
styleNode.InnerHtml = cssContent
doc.DocumentNode.SelectSingleNode("//head").AppendChild(styleNode)
' Remove the external link
link.Remove()
End If
Next
End If
' Return the modified HTML with embedded assets
Return doc.DocumentNode.OuterHtml
End Using
End FunctionHTML解析に役立つツールは何ですか?
最も人気のある.NET用のHTML解析ライブラリはHtmlAgilityPackですが、他にも選択肢が存在します。
- HtmlAgilityPack: 一般的なHTML解析と操作に最適
- AngleSharp: モダンで標準準拠のHTMLパーサーで、CSSセレクターのサポートあり
- CsQuery: jQueryに精通したC#開発者向けのjQueryライクな構文
- 正規表現: 簡単な抽出作業向け(複雑な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");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")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フォーム投稿に比べていくつかの利点があります:
- 標準化されたプロトコル: RFC標準に従ったHTTP認証ヘッダーを使用
- ブラウザ統合: Chromeレンダリングエンジンが認証を処理
- セッション管理: 認証の課題とセッション持続を自動的に処理
- セキュリティ: クレデンシャルはフォームデータではなくヘッダーを介して安全に送信
- 互換性: ほとんどのエンタープライズ認証システムと動作します (
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 }
};// 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 }
};' Basic Authentication (most common)
Dim basicAuth = New ChromeHttpLoginCredentials With {
.NetworkUsername = "user@domain.com",
.NetworkPassword = "password123"
}
' NTLM/Windows Authentication
Dim ntlmAuth = New ChromeHttpLoginCredentials With {
.NetworkUsername = "DOMAIN\username", ' Include domain
.NetworkPassword = "password123"
}
' Custom authentication headers
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.HttpRequestHeaders = New Dictionary(Of String, String) From {
{"X-API-Key", "your-api-key"},
{"Authorization", "Bearer " & jwtToken}
}' Basic Authentication (most common)
Dim basicAuth = New ChromeHttpLoginCredentials With {
.NetworkUsername = "user@domain.com",
.NetworkPassword = "password123"
}
' NTLM/Windows Authentication
Dim ntlmAuth = New ChromeHttpLoginCredentials With {
.NetworkUsername = "DOMAIN\username", ' Include domain
.NetworkPassword = "password123"
}
' Custom authentication headers
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.HttpRequestHeaders = New Dictionary(Of String, String) From {
{"X-API-Key", "your-api-key"},
{"Authorization", "Bearer " & jwtToken}
}認証失敗をどのようにトラブルシューティングしますか?
よくある認証の問題と解決策
- 401 Unauthorized: 資格情報と認証タイプを確認
- 403 Forbidden: 認証済みのユーザーが権限を持っていません
- タイムアウトエラー: 認証システムが遅い場合に
Timeoutを増加させる - 証明書エラー: TLS/SSL設定を適切に構成
問題を診断するためのデバッグを可能にします:
using IronPdf;
using System;
// Enable detailed logging
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log";
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
// Test authentication
var renderer = new ChromePdfRenderer();
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
}using IronPdf;
using System;
// Enable detailed logging
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log";
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
// Test authentication
var renderer = new ChromePdfRenderer();
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
}Imports IronPdf
Imports System
' Enable detailed logging
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log"
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All
' Test authentication
Dim renderer = New ChromePdfRenderer()
Try
Dim pdf = renderer.RenderUrlAsPdf("https://secure.example.com")
pdf.SaveAs("authenticated.pdf")
Catch ex As Exception
Console.WriteLine($"Authentication failed: {ex.Message}")
' Check IronPdf.log for detailed error information
End TryImports IronPdf
Imports System
' Enable detailed logging
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log"
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All
' Test authentication
Dim renderer = New ChromePdfRenderer()
Try
Dim pdf = renderer.RenderUrlAsPdf("https://secure.example.com")
pdf.SaveAs("authenticated.pdf")
Catch ex As Exception
Console.WriteLine($"Authentication failed: {ex.Message}")
' Check IronPdf.log for detailed error information
End TryHTMLフォームを使用してどのようにログインしますか?
HTMLフォームにデータを送信してログインするには、ChromeHttpLoginCredentialsクラスを使用してください。 IronPDFのChromeHttpLoginCredentials APIを参照してください。
これらの点を考慮してください:
- HTMLフォームのACTION属性で指定されたURLにログインデータを投稿します。 これを
HttpLoginCredentialsのLoginFormUrl属性として設定します。 これは、PDFとしてレンダリングしたいURLとは異なる場合があります。 - HTMLフォームのすべての入力とテキストエリアを表すデータを送信します。 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");// 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");Imports System.Collections.Generic
' Configure form-based login
Dim formLogin As New ChromeHttpLoginCredentials With {
.LoginFormUrl = "https://example.com/login",
.LoginFormData = New Dictionary(Of String, String) From {
{"username", "user@example.com"},
{"password", "securePassword123"},
{"rememberMe", "true"},
{"csrf_token", "abc123"} ' Include any hidden fields
}
}
Dim renderer As New ChromePdfRenderer With {
.LoginCredentials = formLogin,
.RenderingOptions = New ChromePdfRenderOptions With {
.RenderDelay = 3000, ' Allow time for login redirect
.EnableJavaScript = True
}
}
' The actual page you want to convert (after login)
Dim pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard")
pdf.SaveAs("dashboard.pdf")Imports System.Collections.Generic
' Configure form-based login
Dim formLogin As New ChromeHttpLoginCredentials With {
.LoginFormUrl = "https://example.com/login",
.LoginFormData = New Dictionary(Of String, String) From {
{"username", "user@example.com"},
{"password", "securePassword123"},
{"rememberMe", "true"},
{"csrf_token", "abc123"} ' Include any hidden fields
}
}
Dim renderer As New ChromePdfRenderer With {
.LoginCredentials = formLogin,
.RenderingOptions = New ChromePdfRenderOptions With {
.RenderDelay = 3000, ' Allow time for login redirect
.EnableJavaScript = True
}
}
' The actual page you want to convert (after login)
Dim 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;
}// 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;
}' Use this helper method to extract form fields
Public Function ExtractFormFields(loginPageHtml As String) As Dictionary(Of String, String)
Dim formData As New Dictionary(Of String, String)()
Dim doc As New HtmlDocument()
doc.LoadHtml(loginPageHtml)
' Find all input fields
Dim inputs = doc.DocumentNode.SelectNodes("//input")
If inputs IsNot Nothing Then
For Each input In inputs
Dim name As String = input.GetAttributeValue("name", "")
Dim value As String = input.GetAttributeValue("value", "")
Dim type As String = input.GetAttributeValue("type", "text")
If Not String.IsNullOrEmpty(name) Then
' Handle different input types
Select Case type.ToLower()
Case "checkbox"
If input.Attributes("checked") IsNot Nothing Then
formData(name) = "on"
End If
Case "radio"
If input.Attributes("checked") IsNot Nothing Then
formData(name) = value
End If
Case Else
formData(name) = value
End Select
End If
Next
End If
' Don't forget select elements
Dim selects = doc.DocumentNode.SelectNodes("//select")
If selects IsNot Nothing Then
For Each selectNode In selects
Dim name As String = selectNode.GetAttributeValue("name", "")
Dim selected = selectNode.SelectSingleNode(".//option[@selected]")
If selected IsNot Nothing AndAlso Not String.IsNullOrEmpty(name) Then
formData(name) = selected.GetAttributeValue("value", "")
End If
Next
End If
Return formData
End Function' Use this helper method to extract form fields
Public Function ExtractFormFields(loginPageHtml As String) As Dictionary(Of String, String)
Dim formData As New Dictionary(Of String, String)()
Dim doc As New HtmlDocument()
doc.LoadHtml(loginPageHtml)
' Find all input fields
Dim inputs = doc.DocumentNode.SelectNodes("//input")
If inputs IsNot Nothing Then
For Each input In inputs
Dim name As String = input.GetAttributeValue("name", "")
Dim value As String = input.GetAttributeValue("value", "")
Dim type As String = input.GetAttributeValue("type", "text")
If Not String.IsNullOrEmpty(name) Then
' Handle different input types
Select Case type.ToLower()
Case "checkbox"
If input.Attributes("checked") IsNot Nothing Then
formData(name) = "on"
End If
Case "radio"
If input.Attributes("checked") IsNot Nothing Then
formData(name) = value
End If
Case Else
formData(name) = value
End Select
End If
Next
End If
' Don't forget select elements
Dim selects = doc.DocumentNode.SelectNodes("//select")
If selects IsNot Nothing Then
For Each selectNode In selects
Dim name As String = selectNode.GetAttributeValue("name", "")
Dim selected = selectNode.SelectSingleNode(".//option[@selected]")
If selected IsNot Nothing AndAlso Not String.IsNullOrEmpty(name) Then
formData(name) = selected.GetAttributeValue("value", "")
End If
Next
End If
Return formData
End Function正しいフォームアクション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;
}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;
}Public Function ExtractFormAction(loginPageUrl As String, loginPageHtml As String) As String
Dim doc As New HtmlDocument()
doc.LoadHtml(loginPageHtml)
' Find the login form
Dim form As HtmlNode = doc.DocumentNode.SelectSingleNode("//form[contains(@action, 'login') or contains(@id, 'login') or contains(@class, 'login')]")
If form Is Nothing Then
' Try finding any form with password field
form = doc.DocumentNode.SelectSingleNode("//form[.//input[@type='password']]")
End If
If form IsNot Nothing Then
Dim action As String = form.GetAttributeValue("action", "")
' Resolve relative URLs
If Not String.IsNullOrEmpty(action) Then
Dim baseUri As New Uri(loginPageUrl)
Dim actionUri As New Uri(baseUri, action)
Return actionUri.ToString()
End If
End If
' Default to the login page URL if no action found
Return loginPageUrl
End FunctionPublic Function ExtractFormAction(loginPageUrl As String, loginPageHtml As String) As String
Dim doc As New HtmlDocument()
doc.LoadHtml(loginPageHtml)
' Find the login form
Dim form As HtmlNode = doc.DocumentNode.SelectSingleNode("//form[contains(@action, 'login') or contains(@id, 'login') or contains(@class, 'login')]")
If form Is Nothing Then
' Try finding any form with password field
form = doc.DocumentNode.SelectSingleNode("//form[.//input[@type='password']]")
End If
If form IsNot Nothing Then
Dim action As String = form.GetAttributeValue("action", "")
' Resolve relative URLs
If Not String.IsNullOrEmpty(action) Then
Dim baseUri As New Uri(loginPageUrl)
Dim actionUri As New Uri(baseUri, action)
Return actionUri.ToString()
End If
End If
' Default to the login page URL if no action found
Return loginPageUrl
End Functionフォームベースの認証の一般的な問題は何ですか?
- CSRFトークン: 多くのフォームには期限切れの不正防止トークンが含まれる
- JavaScript検証: 一部のフォームはJavaScriptの実行を必要とする
- 多段階認証: 複数ページを必要とするフォーム
- CAPTCHA保護: 人間検証チャレンジ
- セッションタイムアウト: ログインセッションがすぐに期限切れになる
ViewBag
TempData
Html
複雑な認証シナリオを含む、HTMLからPDFへの変換についての総合的なガイダンスについては、HTMLからPDFへのチュートリアルをご覧ください。
MVC認証をどのように扱いますか?
次の回避策は、.NET MVCビューをプログラムで文字列にレンダリングし、ビューを忠実にレンダリングしながらMVCログインを回避します。 このアプローチは、MVC CoreでCSHTMLをPDFに変換、もしくはMVC 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");
}// 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");
}' Converts an MVC partial view to a string
<Extension()>
Public Shared Function RenderPartialViewToString(ByVal controller As Controller, ByVal viewPath As String, Optional ByVal model As Object = Nothing) As String
Try
' Set the model
Dim context = controller.ControllerContext
controller.ViewData.Model = model
Using sw As New StringWriter()
' Find the partial view
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
' Create a view context
Dim viewContext As 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()
End Using
Catch ex As Exception
' Return error message if there is an exception
Return ex.Message
End Try
End Function
' Usage in an MVC Controller
Public Function GeneratePdf() As ActionResult
' Render authenticated view to string
Dim model As New InvoiceViewModel() ' populate model
Dim html As String = Me.RenderPartialViewToString("~/Views/Invoice/Details.cshtml", model)
' Convert to PDF
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(html)
' Return PDF file
Return File(pdf.BinaryData, "application/pdf", "invoice.pdf")
End Function' Converts an MVC partial view to a string
<Extension()>
Public Shared Function RenderPartialViewToString(ByVal controller As Controller, ByVal viewPath As String, Optional ByVal model As Object = Nothing) As String
Try
' Set the model
Dim context = controller.ControllerContext
controller.ViewData.Model = model
Using sw As New StringWriter()
' Find the partial view
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
' Create a view context
Dim viewContext As 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()
End Using
Catch ex As Exception
' Return error message if there is an exception
Return ex.Message
End Try
End Function
' Usage in an MVC Controller
Public Function GeneratePdf() As ActionResult
' Render authenticated view to string
Dim model As New InvoiceViewModel() ' populate model
Dim html As String = Me.RenderPartialViewToString("~/Views/Invoice/Details.cshtml", model)
' Convert to PDF
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(html)
' Return PDF file
Return File(pdf.BinaryData, "application/pdf", "invoice.pdf")
End Functionなぜビューを直接変換するのではなく文字列へレンダリングするのですか?
MVCビューを文字列にレンダリングすると、いくつかの重要な利点があります:
- 認証コンテキスト: ビューは認証されたユーザーのコンテキストでレンダリング
- フルMVCパイプライン:
HtmlHelper、UrlHelper、およびViewBagヘルパーを含むすべてのMVC機能が動作します。 - レイアウトサポート: マスターページとレイアウトが正しくレンダリングされます
- モデルバインディング: 複雑なビューモデルが動作
- アクションフィルター: セキュリティとログのフィルターが通常通り実行
この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");
}
}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");
}
}Public Class InvoiceController
Inherits Controller
Private ReadOnly _invoiceService As IInvoiceService
Public Async Function DownloadInvoicePdf(invoiceId As Integer) As Task(Of ActionResult)
' Load data within authenticated context
Dim invoice = Await _invoiceService.GetInvoiceAsync(invoiceId)
If invoice Is Nothing OrElse invoice.UserId <> User.Identity.GetUserId() Then
Return HttpNotFound()
End If
' Create view model
Dim viewModel = New InvoiceDetailsViewModel With {
.Invoice = invoice,
.Company = Await _invoiceService.GetCompanyDetailsAsync(),
.LineItems = Await _invoiceService.GetLineItemsAsync(invoiceId),
.TaxDetails = Await _invoiceService.GetTaxDetailsAsync(invoiceId)
}
' Render to HTML string
Dim html As String = Me.RenderPartialViewToString("~/Views/Invoice/DetailsPdf.vbhtml", 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
Dim renderer = New ChromePdfRenderer With {
.RenderingOptions = New ChromePdfRenderOptions With {
.MarginTop = 20,
.MarginBottom = 20,
.MarginLeft = 10,
.MarginRight = 10,
.PrintHtmlBackgrounds = True
}
}
Dim 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")
End Function
End ClassPublic Class InvoiceController
Inherits Controller
Private ReadOnly _invoiceService As IInvoiceService
Public Async Function DownloadInvoicePdf(invoiceId As Integer) As Task(Of ActionResult)
' Load data within authenticated context
Dim invoice = Await _invoiceService.GetInvoiceAsync(invoiceId)
If invoice Is Nothing OrElse invoice.UserId <> User.Identity.GetUserId() Then
Return HttpNotFound()
End If
' Create view model
Dim viewModel = New InvoiceDetailsViewModel With {
.Invoice = invoice,
.Company = Await _invoiceService.GetCompanyDetailsAsync(),
.LineItems = Await _invoiceService.GetLineItemsAsync(invoiceId),
.TaxDetails = Await _invoiceService.GetTaxDetailsAsync(invoiceId)
}
' Render to HTML string
Dim html As String = Me.RenderPartialViewToString("~/Views/Invoice/DetailsPdf.vbhtml", 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
Dim renderer = New ChromePdfRenderer With {
.RenderingOptions = New ChromePdfRenderOptions With {
.MarginTop = 20,
.MarginBottom = 20,
.MarginLeft = 10,
.MarginRight = 10,
.PrintHtmlBackgrounds = True
}
}
Dim 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")
End Function
End Class認証ソリューションを実装する前に、IronPDFが正しくインストールされ、ライセンスキーが設定されていることを確認してください。
次に何ができるのかを見てみましょうか? チュートリアルページにアクセスしてください: PDFを変換。
RenderDelay
よくある質問
HTMLをPDFに変換する際にログイン認証を行うには、C#でどのようにすれば良いですか?
ネットワーク認証にはIronPDFの'ChromeHttpLoginCredentials'クラスを使用するか、変換前にSystem.Net.WebClientまたはHttpClientを使用してHTMLをダウンロードすることができます。これにより、ネットワークとHTMLフォームのログインを効果的に処理できます。
IronPDFの'ChromeHttpLoginCredentials'クラスの目的は何ですか?
IronPDFの'ChromeHttpLoginCredentials'クラスはネットワーク認証に使用され、基本認証、ダイジェスト認証、NTLM認証などのさまざまな認証タイプをサポートします。これにより、保護されたHTMLコンテンツにアクセスするための認証を回避できます。
HTMLコンテンツをPDFに変換する前にダウンロードすべきなのはなぜですか?
事前にHTMLコンテンツをダウンロードすることでHTMLを制御し、アセットの管理を行い、認証の柔軟性を高め、キャッシングを通じてパフォーマンスを向上させ、HTMLを調べることでデバッグを支援します。
PDF変換中にIronPDFは画像やスタイルシートのようなアセットをどのように処理しますか?
IronPDFはHttpClientを利用してアセットをダウンロードできます。HtmlAgilityPackを使用してHTMLを解析し、相対パスを絶対URLに変換し、CSSを直接埋め込むことで、すべてのリソースがPDFに含まれるようにします。
フォーム投稿を超えるネットワーク認証の利点は何ですか?
ネットワーク認証は標準化されたHTTPヘッダーを使用し、一般的により安全で、ブラウザと良好に統合し、セッションを自動的に管理し、Active Directoryのようなエンタープライズシステムと互換性があります。
C#でHTMLを解析するために推奨されるツールは何ですか?
HtmlAgilityPackは.NETでのHTML解析と操作に人気があります。代替には、最新のHTML解析に対応するAngleSharp、jQueryのような構文を持つCsQuery、そしてシンプルな抽出に正規表現を使用する方法がありますが、複雑な作業には推奨されません。
IronPDFを使ったHTMLフォーム認証でのログイン方法はどうすれば良いですか?
IronPDFを使用して、URLとフォームデータを'ChromeHttpLoginCredentials'に設定することで、フォームベースのログインを構成できます。CSRFトークンのような隠しフィールドを含むHTMLフォームからすべての入力データを正確にキャプチャすることが重要です。
フォームベースの認証で発生する可能性のある一般的な問題は何ですか?
一般的な問題には、CSRFトークンの処理、JavaScriptの検証、マルチステッププロセス、CAPTCHAの要件、セッションのタイムアウトが含まれます。これらを適切に対応することで、自動化されたタスクのログインプロセスを円滑に進めることができます。
IronPDFを使った認証失敗のトラブルシューティング方法は?
認証の問題は、資格情報の確認、401または403エラーの確認、タイムアウト設定の調整、適切なTLS/SSL構成の確認、診断するための詳細なログの有効化によって対処できます。
PDFに変換する前にMVCビューを文字列にレンダリングする利点は何ですか?
ビューを文字列にレンダリングすることで認証コンテキストが維持され、MVCの機能をサポートし、変換前にHTMLを修正できます。このアプローチは、セキュリティ、パフォーマンス、一貫性を確保し、ユーザーがブラウザで見るものを反映します。
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。