Converter HTML para PDF com autenticação de login em C#
Para converter HTML em PDF atrás da autenticação de login em C#, use ChromeHttpLoginCredentials do IronPDF para autenticação de rede ou baixe o HTML usando System.Net.WebClient/HttpClient antes da conversão. Essa abordagem lida de forma eficaz tanto com a autenticação de rede quanto com os logins via formulário HTML.
Converta páginas HTML em PDFs por trás de formulários de login usando a API do IronPDF. Este guia demonstra ChromeHttpLoginCredentials para autenticação e recuperação de conteúdo protegido. Lide com autenticação de rede e logins via formulário HTML com exemplos de código simples.
-
1Instale o IronPDF com NuGet Package Manager
-
2Copie e execute este trecho de código.
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") -
3Implante para testar em seu ambiente de produção.
Comece a usar o IronPDF em seu projeto hoje com uma avaliação gratuita
Fluxo de trabalho mínimo (5 etapas)
- Baixe a Biblioteca IronPDF para C#
- Baixe o HTML para evitar logins
- Faça login usando a Autenticação de Rede com a propriedade LoginCredentials
- Utilize um formulário HTML para autenticação.
- Solução alternativa para autenticação de login MVC
Quais são as melhores práticas para lidar com a autenticação de login?
O IronPDF suporta autenticação de rede TLS (nome de usuário e senha) através da API ChromeHttpLoginCredentials. Para uma orientação abrangente sobre vários cenários de login, consulte o tutorial de Logins de Site e Sistema TLS.
A abordagem recomendada é usar System.Net.WebClient ou HttpClient para baixar HTML e recursos. Este método suporta cabeçalhos, logins e outros requisitos. Após o download para a memória ou disco, o IronPDF converte o HTML em PDF. Extraia recursos como folhas de estilo e imagens usando HtmlAgilityPack, depois baixe com 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. Para rebasear todos os caminhos relativos em um documento HTML, adicione uma tag <base> ao cabeçalho usando o HtmlAgilityPack. Exemplo. Para mais informações sobre como lidar com URLs e ativos, consulte o guia de URLs Base & Codificação de Ativos.Por que devo baixar o conteúdo HTML primeiro?
Fazer o download do conteúdo HTML antes da conversão oferece diversas vantagens:
- Controle Completo: Modifique HTML, corrija links quebrados ou injete tokens de autenticação antes da conversão
- Gerenciamento de Recursos: Baixe e armazene em cache recursos externos como imagens, arquivos CSS e JavaScript
- Flexibilidade de Autenticação: Use qualquer mecanismo de autenticação .NET, incluindo OAuth, tokens JWT ou cabeçalhos personalizados
- Desempenho: Armazene em cache conteúdo frequentemente acessado para reduzir a carga do servidor
- Depuração: Inspecione o HTML exato que está sendo convertido para resolver problemas
Para cenários complexos de autenticação envolvendo cookies e sessões, veja o guia de Cookies que explica o gerenciamento de estado de autenticação durante a conversão para PDF.
Como faço para gerenciar recursos como imagens e folhas de estilo?
Ao converter páginas autenticadas, os recursos externos geralmente exigem a mesma autenticação. Aqui está uma abordagem abrangente usando 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 FunctionQue ferramentas ajudam na análise de HTML?
A HtmlAgilityPack é a biblioteca de análise de HTML mais popular para .NET, mas existem alternativas:
- HtmlAgilityPack: Melhor para análise e manipulação geral de HTML
- AngleSharp: Analisador HTML moderno, compatível com padrões e suporte a seletores CSS
- CsQuery: Sintaxe semelhante ao jQuery para desenvolvedores C# familiarizados com jQuery
- Expressões Regulares: Para tarefas simples de extração (não recomendado para HTML complexo)
ChromeHttpLoginCredentials
Como faço para entrar usando a autenticação de rede?
A maioria das aplicações ASP.NET suporta autenticação de rede, que é mais confiável do que o envio de formulários HTML. O IronPDF fornece suporte integrado para autenticação básica, digest e NTLM através da classe ChromeHttpLoginCredentials. Para personalização adicional de cabeçalhos, consulte o guia de Cabeçalhos de Requisição 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")Por que a autenticação de rede é mais confiável do que o envio de formulários?
A autenticação em rede oferece diversas vantagens em relação ao envio de formulários HTML:
- Protocolo Padronizado: Utiliza cabeçalhos de autenticação HTTP seguindo os padrões RFC
- Integração com Navegador: O mecanismo de renderização do Chrome trata a autenticação
- Gerenciamento de Sessões: Tratamento automático de desafios de autenticação e persistência de sessões
- Segurança: Credenciais transmitidas com segurança via cabeçalhos em vez de dados de formulário
- Compatibilidade: Funciona com a maioria dos sistemas de autenticação empresarial (
Active Directory,LDAP)
Quais credenciais eu preciso para autenticação de rede?
Diferentes tipos de autenticação exigem credenciais diferentes:
// 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}
}Como solucionar problemas de falha de autenticação?
Problemas comuns de autenticação e suas soluções:
- 401 Não Autorizado: Verifique as credenciais e o tipo de autenticação
- 403 Proibido: Usuário autenticado, mas sem permissões
- Erros de Timeout: Aumente
Timeoutpara sistemas de autenticação lentos - Erros de Certificado: Configure as configurações de TLS/SSL adequadamente
Ative a depuração para diagnosticar problemas:
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 TryComo faço para entrar usando um formulário HTML?
Para fazer login enviando dados para um formulário HTML, use a classe ChromeHttpLoginCredentials . Veja a API ChromeHttpLoginCredentials do IronPDF.
Considere estes pontos:
- Enviar os dados de login para a URL especificada no atributo ACTION do formulário HTML. Defina isso como o atributo
LoginFormUrldeHttpLoginCredentials. Isso pode ser diferente da URL que você deseja renderizar como um PDF. - Enviar dados que representam cada campo de entrada e área de texto no formulário HTML. Os atributos de nome definem o nome de cada variável (não o ID).
- Alguns sites protegem ativamente contra logins de máquinas.
// 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")Que dados de formulário preciso coletar?
Para autenticar com sucesso através de formulários HTML, capture todos os campos do formulário:
// 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 FunctionComo encontro a URL correta da ação do formulário?
O URL da ação do formulário é fundamental para uma autenticação bem-sucedida:
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 FunctionQuais são os problemas comuns com a autenticação baseada em formulários?
- Tokens CSRF: Muitos formulários incluem tokens antifalsificação que expiram
- Validação JavaScript: Alguns formulários requerem execução de JavaScript
- Autenticação em Múltiplos Passos: Formulários que exigem várias páginas
- Proteção CAPTCHA: Desafios de verificação humana
- Tempos de Sessão: Sessões de login que expiram rapidamente
ViewBag
TempData
Html
Para uma orientação abrangente sobre conversão de HTML para PDF, incluindo cenários complexos de autenticação, visite o tutorial de HTML para PDF.
Como faço para lidar com a autenticação MVC?
A seguinte solução alternativa renderiza uma view .NET MVC em uma string programaticamente, evitando logins do MVC e, ao mesmo tempo, renderizando as views fielmente. Essa abordagem funciona bem quando se converte CSHTML para PDF no MVC Core ou 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 FunctionPor que renderizar as visualizações em strings em vez de convertê-las diretamente?
Renderizar views MVC em strings oferece diversas vantagens importantes:
- Contexto de Autenticação: As visualizações são renderizadas no contexto do usuário autenticado
- Pipeline Completo do MVC: Todos os recursos do MVC funcionam, incluindo assistentes
HtmlHelper,UrlHelper, eViewBag - Suporte a Layout: Páginas mestre e layouts são renderizados corretamente
- Binding de Modelo: Modelos de visualização complexos funcionam
- Filtros de Ação: Filtros de segurança e registro são executados normalmente
Quais são os benefícios dessa solução alternativa para o MVC?
A abordagem de renderização de strings do MVC oferece:
- Segurança: Não há necessidade de expor URLs internos ou ignorar autenticação
- Desempenho: Evite solicitações HTTP adicionais
- Consistência: Saída idêntica ao que os usuários veem nos navegadores
- Flexibilidade: Modifique o HTML antes da conversão para PDF
- Teste: Teste de unidade a geração de HTML facilmente
Como faço para passar modelos para a visualização renderizada?
Aqui está um exemplo completo com um modelo complexo:
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 ClassAntes de implementar qualquer solução de autenticação, certifique-se de ter instalado o IronPDF corretamente e configurado suas chaves de licença.
Pronto para ver o que mais você pode fazer? Visite nossa página de tutoriais: Converter PDFs.
RenderDelay
Perguntas frequentes
Como posso converter HTML em PDF por trás da autenticação de login usando C#?
Você pode usar a classe 'ChromeHttpLoginCredentials' do IronPDF para autenticação de rede ou baixar o HTML usando System.Net.WebClient ou HttpClient antes da conversão. Isso lida eficientemente com logins de rede e formulário HTML.
Qual é o propósito da classe 'ChromeHttpLoginCredentials' no IronPDF?
A classe 'ChromeHttpLoginCredentials' no IronPDF é usada para autenticação de rede, suportando vários tipos de autenticação como básico, digest e NTLM. Ela ajuda a contornar a autenticação para acessar conteúdo HTML protegido.
Por que devo baixar o conteúdo HTML antes de convertê-lo em PDF?
Baixar o conteúdo HTML antecipadamente fornece controle sobre o HTML, permite gerenciamento de ativos, aumenta a flexibilidade da autenticação, melhora o desempenho através de caching e auxilia na depuração permitindo inspecionar o HTML.
Como o IronPDF lida com recursos como imagens e folhas de estilo durante a conversão em PDF?
O IronPDF pode lidar com recursos aproveitando o HttpClient para baixá-los. Você pode analisar HTML com o HtmlAgilityPack, resolver caminhos relativos para URLs absolutas e incorporar CSS diretamente para garantir que todos os recursos sejam incluídos no PDF.
Quais são os benefícios de usar autenticação de rede em vez da postagem de formulário?
A autenticação de rede utiliza cabeçalhos HTTP padronizados, é geralmente mais segura, integra-se bem com navegadores, gerencia sessões automaticamente e é compatível com sistemas empresariais como o Active Directory.
Quais ferramentas são recomendadas para analisar HTML em C#?
HtmlAgilityPack é popular para análise e manipulação de HTML em .NET. Alternativas incluem AngleSharp para análise moderna de HTML, CsQuery para sintaxe semelhante ao jQuery e expressões regulares para extrações simples, embora não recomendadas para tarefas complexas.
Como faço para fazer login usando autenticação de formulário HTML com o IronPDF?
Usando IronPDF, você pode configurar o login baseado em formulário fornecendo URL e dados do formulário para 'ChromeHttpLoginCredentials'. Certifique-se de que todos os dados de entrada do formulário HTML, incluindo campos ocultos como tokens CSRF, sejam capturados corretamente.
Quais problemas comuns podem surgir com a autenticação baseada em formulários?
Problemas comuns incluem lidar com tokens CSRF, validações JavaScript, processos em várias etapas, exigências de CAPTCHA e tempos de expiração de sessão. Abordar adequadamente esses problemas pode garantir processos de login mais suaves para tarefas automatizadas.
Como posso solucionar falhas de autenticação com o IronPDF?
Problemas de autenticação podem ser resolvidos verificando credenciais, verificando erros 401 ou 403, ajustando configurações de tempo limite, garantindo configuração adequada de TLS/SSL e habilitando registros detalhados para diagnosticar problemas.
Quais são as vantagens de renderizar visões MVC para cadeias de caracteres antes de converter em PDF?
Renderizar visões para cadeias de caracteres mantém o contexto de autenticação, suporta recursos MVC e permite a modificação do HTML antes da conversão. Essa abordagem garante segurança, desempenho e consistência, refletindo o que os usuários veem nos navegadores.
Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais bem estruturados e visualmente atraentes.