How to Use HTTP Request Headers with C#
HTTP request headers in C# allow you to send additional metadata like authentication tokens or custom user agents when converting URLs to PDFs using IronPDF. Simply create a dictionary of headers and assign it to the HttpRequestHeaders property before rendering.
-
1Install IronPDF with NuGet Package Manager
-
2Copy and run this code snippet.
new IronPdf.ChromePdfRenderer { RenderingOptions = { HttpRequestHeaders = new Dictionary<string,string> { { "Authorization", "Bearer your_token_here" }, { "User-Agent", "MyApp/1.0" } } } } .RenderUrlAsPdf("https://httpbin.org/bearer") .SaveAs("withHeaders.pdf");C# -
3Deploy to test on your live environment
Start using IronPDF in your project today with a free trial
Minimal Workflow (5 steps)
- Download IronPDF from NuGet
- Prepare the HTTP request headers as a C# dictionary
- Assign the dictionary to the HttpRequestHeaders property
- Render the URL to PDF using the
RenderUrlAsPdfmethod - Save the PDF as a file or export it as bytes
What Is an HTTP Request Header?
An HTTP request header is metadata sent by a client (such as a web browser or API client) to a server when making an HTTP request. Headers provide additional information about the request, such as authentication details, content type, user agent, and more.
This feature is used when rendering a URL to PDF, allowing you to provide HTTP header information when making the request. When working with URL to PDF conversions, headers become essential for accessing protected content or APIs that require specific authentication mechanisms.
IronPDF's HTTP header support integrates seamlessly with the Chrome PDF rendering engine, ensuring that your headers are properly sent during the rendering process. This is particularly important when dealing with secured websites or those behind TLS authentication systems.
The IronSuite play a crucial role in our operations. These are tools that increase efficiencies across the business including creating floor plans and improving inventory management.
How Do I Add Custom Headers to PDF Rendering?
Before using the HttpRequestHeaders property to set an HTTP request header, first design a proper HTTP request header object. During the rendering process, this header will be included in the URL request sent to the server. As an example, we will use httpbin.org, a website that helps show the headers request.
using IronPdf;
using System.Collections.Generic;
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HttpRequestHeaders = new Dictionary<string, string>
{
{ "Authorization", "Bearer test-token-123" }
};
// Render PDF from authenticated page
var pdf = renderer.RenderUrlAsPdf("https://httpbin.org/bearer");
pdf.SaveAs("output.pdf");Imports IronPdf
Imports System.Collections.Generic
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.HttpRequestHeaders = New Dictionary(Of String, String) From {
{"Authorization", "Bearer test-token-123"}
}
' Render PDF from authenticated page
Dim pdf = renderer.RenderUrlAsPdf("https://httpbin.org/bearer")
pdf.SaveAs("output.pdf")Working with Multiple Headers
When working with complex authentication scenarios or APIs, you often need to send multiple headers. Here's how to handle various header combinations:
using IronPdf;
using System.Collections.Generic;
var renderer = new ChromePdfRenderer();
// Configure multiple headers for API access
renderer.RenderingOptions.HttpRequestHeaders = new Dictionary<string, string>
{
{ "Authorization", "Bearer your-api-token" },
{ "Accept", "text/html,application/xhtml+xml" },
{ "Accept-Language", "en-US,en;q=0.9" },
{ "Cache-Control", "no-cache" },
{ "X-Custom-Header", "MyApplication/2.0" }
};
// Additional rendering options for better results
renderer.RenderingOptions.WaitFor.RenderDelay(500); // Wait for dynamic content
renderer.RenderingOptions.ViewPortWidth = 1920;
renderer.RenderingOptions.ViewPortHeight = 1080;
var pdf = renderer.RenderUrlAsPdf("https://api.example.com/report");
pdf.SaveAs("api-report.pdf");Imports IronPdf
Imports System.Collections.Generic
Dim renderer As New ChromePdfRenderer()
' Configure multiple headers for API access
renderer.RenderingOptions.HttpRequestHeaders = New Dictionary(Of String, String) From {
{"Authorization", "Bearer your-api-token"},
{"Accept", "text/html,application/xhtml+xml"},
{"Accept-Language", "en-US,en;q=0.9"},
{"Cache-Control", "no-cache"},
{"X-Custom-Header", "MyApplication/2.0"}
}
' Additional rendering options for better results
renderer.RenderingOptions.WaitFor.RenderDelay(500) ' Wait for dynamic content
renderer.RenderingOptions.ViewPortWidth = 1920
renderer.RenderingOptions.ViewPortHeight = 1080
Dim pdf = renderer.RenderUrlAsPdf("https://api.example.com/report")
pdf.SaveAs("api-report.pdf")Which HTTP Headers Are Most Commonly Used?
- Authorization: Sends authentication credentials (Bearer token, Basic auth, etc.)
- Content-Type: Defines the format of the request body (e.g., application/json)
- Accept: Specifies the expected response format (e.g., text/html, application/json)
- User-Agent: Identifies the client making the request (browser, API client, etc.)
- Referer: Indicates the page that linked to the current request
- Cookie: Sends cookies for session tracking
When using cookies for authentication, you can combine cookie headers with other authentication methods for enhanced security. The custom logging features in IronPDF can help you debug header-related issues during development.
When Should I Use Custom Headers?
Custom headers are essential when accessing protected resources that require authentication, working with APIs that expect specific headers, or when you need to identify your application to the server. They're particularly useful for rendering PDFs from authenticated web pages or API endpoints.
Common scenarios include:
- Accessing internal company dashboards behind authentication
- Generating reports from REST APIs that require API keys
- Converting authenticated SaaS application pages to PDF
- Working with microservices that use token-based authentication
Integration with Authentication Systems
IronPDF's header support works seamlessly with various authentication systems. For basic authentication scenarios:
using IronPdf;
using System;
using System.Text;
var renderer = new ChromePdfRenderer();
// Create Basic Auth header
string username = "user@example.com";
string password = "securepassword";
string credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"));
renderer.RenderingOptions.HttpRequestHeaders = new Dictionary<string, string>
{
{ "Authorization", $"Basic {credentials}" }
};
// Render protected resource
var pdf = renderer.RenderUrlAsPdf("https://protected.example.com/report");
pdf.SaveAs("protected-report.pdf");Imports IronPdf
Imports System
Imports System.Text
Imports System.Collections.Generic
Dim renderer As New ChromePdfRenderer()
' Create Basic Auth header
Dim username As String = "user@example.com"
Dim password As String = "securepassword"
Dim credentials As String = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"))
renderer.RenderingOptions.HttpRequestHeaders = New Dictionary(Of String, String) From {
{"Authorization", $"Basic {credentials}"}
}
' Render protected resource
Dim pdf = renderer.RenderUrlAsPdf("https://protected.example.com/report")
pdf.SaveAs("protected-report.pdf")What Happens If Headers Are Missing or Incorrect?
Missing or incorrect headers can result in 401 Unauthorized errors, 403 Forbidden responses, or incomplete page rendering. Always verify your header values match what the server expects, especially for authentication tokens and API keys.
To troubleshoot header issues, consider using IronPDF's debug features to examine the rendering process. Common problems include:
- Expired tokens or API keys
- Incorrect header formatting
- Missing required headers
- Case-sensitive header names being mistyped
Advanced Header Usage with Dynamic Content
When dealing with JavaScript-heavy pages that require authentication, combine headers with render delays:
using IronPdf;
using System.Collections.Generic;
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HttpRequestHeaders = new Dictionary<string, string>
{
{ "Authorization", "Bearer test-token-123" }
};
// Render PDF from authenticated page
var pdf = renderer.RenderUrlAsPdf("https://httpbin.org/bearer");
pdf.SaveAs("output.pdf");Imports IronPdf
Imports System.Collections.Generic
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.HttpRequestHeaders = New Dictionary(Of String, String) From {
{"Authorization", "Bearer test-token-123"}
}
' Render PDF from authenticated page
Dim pdf = renderer.RenderUrlAsPdf("https://httpbin.org/bearer")
pdf.SaveAs("output.pdf")Best Practices for Header Security
When working with sensitive authentication headers:
- Never hardcode credentials: Store tokens and API keys in secure configuration
- Use HTTPS URLs: Always render from HTTPS endpoints when sending authentication headers
- Rotate tokens regularly: Implement token rotation for long-running applications
- Validate SSL certificates: Ensure proper certificate validation for secure connections
- Monitor header usage: Log header usage for security auditing
For additional security considerations, refer to the PDF permissions and passwords guide to protect your generated PDFs.
Integrating with Modern Web Applications
Modern single-page applications (SPAs) and progressive web apps (PWAs) often require specific headers for proper rendering. Here's how to handle OAuth 2.0 protected resources:
using IronPdf;
using System.Collections.Generic;
using System.Threading.Tasks;
public async Task<PdfDocument> GenerateOAuthProtectedPdf(string accessToken, string url)
{
var renderer = new ChromePdfRenderer();
// Configure OAuth headers
renderer.RenderingOptions.HttpRequestHeaders = new Dictionary<string, string>
{
{ "Authorization", $"Bearer {accessToken}" },
{ "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" }
};
// Set rendering options for SPAs
renderer.RenderingOptions.WaitFor.RenderDelay(3000);
renderer.RenderingOptions.EnableJavaScript = true;
// Render and return the PDF
return await Task.Run(() => renderer.RenderUrlAsPdf(url));
}Imports IronPdf
Imports System.Collections.Generic
Imports System.Threading.Tasks
Public Async Function GenerateOAuthProtectedPdf(accessToken As String, url As String) As Task(Of PdfDocument)
Dim renderer = New ChromePdfRenderer()
' Configure OAuth headers
renderer.RenderingOptions.HttpRequestHeaders = New Dictionary(Of String, String) From {
{"Authorization", $"Bearer {accessToken}"},
{"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}
}
' Set rendering options for SPAs
renderer.RenderingOptions.WaitFor.RenderDelay(3000)
renderer.RenderingOptions.EnableJavaScript = True
' Render and return the PDF
Return Await Task.Run(Function() renderer.RenderUrlAsPdf(url))
End FunctionFor more complex scenarios involving async operations, consider implementing retry logic for failed authentication attempts.
Conclusion
HTTP request headers in IronPDF provide a powerful way to access and convert authenticated web content to PDF. By properly configuring headers, you can seamlessly integrate PDF generation into your existing authentication workflows, whether you're working with simple API keys or complex OAuth systems. Remember to follow security best practices and leverage IronPDF's extensive rendering options for optimal results.
Frequently Asked Questions
How can I add HTTP request headers to PDFs in C# using IronPDF?
To add HTTP request headers when converting URLs to PDFs in C#, use the IronPDF library to create a dictionary of headers and assign it to the `HttpRequestHeaders` property of the `ChromePdfRenderer` object before rendering the URL.
What are some common HTTP headers used in IronPDF for PDF rendering?
Common HTTP headers used in IronPDF for rendering PDFs include 'Authorization' for sending authentication tokens, 'User-Agent' to identify the client, 'Accept' to specify accepted response formats, and 'Referer' to indicate the source of the request.
Why is using HTTP request headers important when rendering PDFs?
HTTP request headers are important when rendering PDFs because they allow you to send authentication information, manage session cookies, and define request behaviors, ensuring secure and accurate conversion of authenticated or protected web content to PDF.
What is the process for adding multiple headers in IronPDF?
To add multiple headers in IronPDF, create a dictionary with all the required headers and assign it to the `HttpRequestHeaders` property. These should include necessary authentication tokens and additional headers like 'Accept-Language' and 'Cache-Control' for more complex requests.
How does IronPDF handle authentication systems with HTTP headers?
IronPDF integrates seamlessly with different authentication systems by allowing you to set appropriate headers such as 'Bearer' tokens for OAuth or 'Basic' authentication credentials, ensuring secure access to protected resources during PDF rendering.
What steps should be followed for troubleshooting header-related issues in IronPDF?
For troubleshooting header-related issues in IronPDF, ensure that header values are correct and up to date, use IronPDF's logging features to debug, and verify against server expectations, especially regarding authentication tokens or API keys.
When should I use custom HTTP headers with IronPDF?
Custom HTTP headers should be used with IronPDF when accessing protected resources that require authentication, interacting with APIs expecting specific headers, or when needing to identify the client application making the request.
What are best practices for ensuring security when using HTTP headers in IronPDF?
Best practices include never hardcoding credentials, using secure HTTPS URLs, regularly rotating tokens, validating SSL certificates, and monitoring header usage to ensure the security of sensitive authentication data when rendering PDFs.
Can IronPDF handle rendering for JavaScript-heavy pages with authentication?
Yes, IronPDF can handle JavaScript-heavy pages that require authentication by utilizing headers along with render delays and enabling JavaScript in the rendering options to ensure proper rendering of dynamic content.
How does IronPDF aid in integrating PDF generation with modern web applications?
IronPDF aids integration with modern web applications by supporting custom HTTP headers necessary for OAuth APIs and providing options for executing JavaScript, accommodating the advanced rendering needs of SPAs and PWAs.

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