ASPX and .NET: Save ASPX Page as PDF Save ASPX Page as PDF
using IronPdf;

private void Form1_Load(object sender, EventArgs e)
{
    //Changes the ASPX output into a pdf instead of HTML
    IronPdf.AspxToPdf.RenderThisPageAsPdf();
}
Imports IronPdf

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
	'Changes the ASPX output into a pdf instead of HTML
	IronPdf.AspxToPdf.RenderThisPageAsPdf()
End Sub

Using the IronPDF library, ASP.NET web pages can be rendered to PDF instead of HTML by adding a single line of code to the Form_Load event.

This example shows how IronPDF can produce complex, data-driven PDFs that are designed and tested as HTML first for simplicity.

IronPDF's ASPX to PDF Conversion functionality allows you to call a single method within an ASPX page and have it return a PDF instead of HTML.

You can code the PDF to either display "in-browser," or to behave as a file download.

Below is an example demonstrating how to implement this functionality in ASP.NET:

using System;
using System.Web.UI;
using IronPdf;

public partial class MyPage : Page 
{
    // This event is executed when the page is loaded
    protected void Page_Load(object sender, EventArgs e) 
    {
        if (!IsPostBack) 
        {
            // Create a new instance of the HtmlToPdf converter
            HtmlToPdf Renderer = new HtmlToPdf();

            // Render the current page as a PDF
            // "RenderUrlAsPdf" converts the URL (current page) to PDF
            PdfDocument PDF = Renderer.RenderUrlAsPdf(Request.Url.ToString());

            // Optional: Set PDF display or download in the browser
            // PDF is sent to user's browser using this method:
            PDF.StreamTo(Response, false, "MyPDF.pdf");
        }
    }
}
using System;
using System.Web.UI;
using IronPdf;

public partial class MyPage : Page 
{
    // This event is executed when the page is loaded
    protected void Page_Load(object sender, EventArgs e) 
    {
        if (!IsPostBack) 
        {
            // Create a new instance of the HtmlToPdf converter
            HtmlToPdf Renderer = new HtmlToPdf();

            // Render the current page as a PDF
            // "RenderUrlAsPdf" converts the URL (current page) to PDF
            PdfDocument PDF = Renderer.RenderUrlAsPdf(Request.Url.ToString());

            // Optional: Set PDF display or download in the browser
            // PDF is sent to user's browser using this method:
            PDF.StreamTo(Response, false, "MyPDF.pdf");
        }
    }
}
Imports System
Imports System.Web.UI
Imports IronPdf

Partial Public Class MyPage
	Inherits Page

	' This event is executed when the page is loaded
	Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
		If Not IsPostBack Then
			' Create a new instance of the HtmlToPdf converter
			Dim Renderer As New HtmlToPdf()

			' Render the current page as a PDF
			' "RenderUrlAsPdf" converts the URL (current page) to PDF
			Dim PDF As PdfDocument = Renderer.RenderUrlAsPdf(Request.Url.ToString())

			' Optional: Set PDF display or download in the browser
			' PDF is sent to user's browser using this method:
			PDF.StreamTo(Response, False, "MyPDF.pdf")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

Explanation:

  • Namespace Usage: using directives are used for necessary namespaces, including IronPdf for PDF creation.
  • Page_Load Event: This is an ASP.NET page lifecycle event that is triggered when the page is loaded. The code checks IsPostBack to ensure that PDF is generated only once, preventing multiple downloads during postbacks.
  • HtmlToPdf: A new instance of HtmlToPdf class is created to perform the conversion from HTML to PDF.
  • RenderUrlAsPdf: This method takes the current page URL and converts it to a PDF document.
  • StreamTo Method: Streams the generated PDF to the browser. The method parameters control how the PDF is displayed: false indicates that the PDF will be displayed directly in the browser, while true would prompt a file download dialog.
  • Download Filename: The PDF filename used in the browser prompt is specified as "MyPDF.pdf".

By following this example, you can easily integrate PDF generation into your ASP.NET applications using IronPDF.

ASPX and .NET: ASPX To PDF Settings ASPX To PDF Settings
using IronPdf;

var PdfOptions = new IronPdf.ChromePdfRenderOptions()
{
    CreatePdfFormsFromHtml = true,
    EnableJavaScript = false,
    Title = "My ASPX Page Rendered as a PDF"
    //.. many more options available
};

AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.Attachment, "MyPdfFile.pdf", PdfOptions);
Imports IronPdf

Private PdfOptions = New IronPdf.ChromePdfRenderOptions() With {
	.CreatePdfFormsFromHtml = True,
	.EnableJavaScript = False,
	.Title = "My ASPX Page Rendered as a PDF"
}

AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.Attachment, "MyPdfFile.pdf", PdfOptions)

This example demonstrates how the user can change PDF print options to turn a form into HTML.

IronPDF's ASPX to PDF Conversion Guide functionality has many options available for rendering HTML to PDF from a string or a file.

Two options of particular importance are:

  • Allowing developers to specify if HTML forms should be rendered as interactive PDF forms during conversion.
  • Allowing developers to specify if the PDF should be displayed "in browser," or as a file download.

Here is an example of how you might set these options using C# and IronPDF:

// Import the necessary namespaces
using IronPdf;

namespace PdfConversionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the HtmlToPdf class
            var Renderer = new HtmlToPdf();

            // Enable the forms to be rendered as interactive fields in the PDF
            Renderer.PrintOptions.RenderFormsAsInteractivePdf = true;

            // Set the output file option
            Renderer.PrintOptions.DisplayPdfInBrowser = true; // Choose 'true' to show in-browser, 'false' for download

            // Define the HTML content source (could be a string or path to an HTML file)
            string htmlContent = "<html><body><h1>Sample PDF Form</h1><form><input type='text' name='textfield'/></form></body></html>";

            // Convert the HTML content to a PDF
            var PDF = Renderer.RenderHtmlAsPdf(htmlContent);

            // Save the PDF to disk
            PDF.SaveAs("output.pdf");

            // Inform the user that the process is complete
            System.Console.WriteLine("PDF creation complete. Check 'output.pdf' for results.");
        }
    }
}
// Import the necessary namespaces
using IronPdf;

namespace PdfConversionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the HtmlToPdf class
            var Renderer = new HtmlToPdf();

            // Enable the forms to be rendered as interactive fields in the PDF
            Renderer.PrintOptions.RenderFormsAsInteractivePdf = true;

            // Set the output file option
            Renderer.PrintOptions.DisplayPdfInBrowser = true; // Choose 'true' to show in-browser, 'false' for download

            // Define the HTML content source (could be a string or path to an HTML file)
            string htmlContent = "<html><body><h1>Sample PDF Form</h1><form><input type='text' name='textfield'/></form></body></html>";

            // Convert the HTML content to a PDF
            var PDF = Renderer.RenderHtmlAsPdf(htmlContent);

            // Save the PDF to disk
            PDF.SaveAs("output.pdf");

            // Inform the user that the process is complete
            System.Console.WriteLine("PDF creation complete. Check 'output.pdf' for results.");
        }
    }
}
' Import the necessary namespaces
Imports IronPdf

Namespace PdfConversionExample
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Create an instance of the HtmlToPdf class
			Dim Renderer = New HtmlToPdf()

			' Enable the forms to be rendered as interactive fields in the PDF
			Renderer.PrintOptions.RenderFormsAsInteractivePdf = True

			' Set the output file option
			Renderer.PrintOptions.DisplayPdfInBrowser = True ' Choose 'true' to show in-browser, 'false' for download

			' Define the HTML content source (could be a string or path to an HTML file)
			Dim htmlContent As String = "<html><body><h1>Sample PDF Form</h1><form><input type='text' name='textfield'/></form></body></html>"

			' Convert the HTML content to a PDF
			Dim PDF = Renderer.RenderHtmlAsPdf(htmlContent)

			' Save the PDF to disk
			PDF.SaveAs("output.pdf")

			' Inform the user that the process is complete
			System.Console.WriteLine("PDF creation complete. Check 'output.pdf' for results.")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Explanation:

  1. Using IronPdf: The necessary IronPdf namespace is imported to utilize its PDF rendering functionalities.

  2. Renderer Initialization: An instance of HtmlToPdf, named Renderer, is created to handle the conversion process.

  3. Interactive PDF Forms: The RenderFormsAsInteractivePdf property is set to true to ensure that any forms within the HTML content are transformed into interactive form fields within the PDF.

  4. Display Options: The DisplayPdfInBrowser property determines how the resultant PDF will be presented to the user. Setting it to true displays the PDF directly in the browser, whereas false would prompt a file download.

  5. HTML Content: HTML content is defined, incorporating a basic form that will be converted to an interactive PDF form.

  6. Conversion Process: The RenderHtmlAsPdf method takes the HTML content and generates a PDF.

  7. Saving the PDF: The generated PDF is saved to the local file system as "output.pdf".

  8. Completion Message: A console message is printed to inform the user that the PDF was successfully created.

This example provides a simple demonstration of converting HTML with form elements to an interactive PDF using IronPDF's ASPX to PDF conversion functionalities.

ASPX and .NET: Using HTML To Create a PDF Using HTML To Create a PDF
using IronPdf;

// Disable local disk access or cross-origin requests
Installation.EnableWebSecurity = true;

// Instantiate Renderer
var renderer = new ChromePdfRenderer();

// Create a PDF from a HTML string using C#
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");

// Export to a file or Stream
pdf.SaveAs("output.pdf");

// Advanced Example with HTML Assets
// Load external html assets: Images, CSS and JavaScript.
// An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
Imports IronPdf

' Disable local disk access or cross-origin requests
Installation.EnableWebSecurity = True

' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()

' Create a PDF from a HTML string using C#
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")

' Export to a file or Stream
pdf.SaveAs("output.pdf")

' Advanced Example with HTML Assets
' Load external html assets: Images, CSS and JavaScript.
' An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
Dim myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\site\assets\")
myAdvancedPdf.SaveAs("html-with-assets.pdf")

With IronPDF, you can create new PDF documents from simple HTML strings within your .NET project, and IronPDF is able to be used in C#, F#, and VB.NET. Thanks to the use of the ChromePdfRenderer class, you can be sure that any PDF documents you render from HTML strings will come out pixel-perfect. With IronPDF's powerful HTML to PDF conversion features, you create high-quality PDF files tailored to fit your personal needs.

See the code example below for more details:

// Import the IronPdf library, enabling use of its classes and methods for PDF generation.
using IronPdf;

// Step 2: Initialize a new ChromePdfRenderer object.
var renderer = new ChromePdfRenderer();

// Step 3: Render a simple HTML string into a PDF document.
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");

// Advanced Step: Render HTML with assets like images.
// The optional BasePath parameter helps locate external assets.
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");

// Step 4: Save the basic PDF document to the file system.
pdf.SaveAs("output.pdf");
// Import the IronPdf library, enabling use of its classes and methods for PDF generation.
using IronPdf;

// Step 2: Initialize a new ChromePdfRenderer object.
var renderer = new ChromePdfRenderer();

// Step 3: Render a simple HTML string into a PDF document.
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");

// Advanced Step: Render HTML with assets like images.
// The optional BasePath parameter helps locate external assets.
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");

// Step 4: Save the basic PDF document to the file system.
pdf.SaveAs("output.pdf");
' Import the IronPdf library, enabling use of its classes and methods for PDF generation.
Imports IronPdf

' Step 2: Initialize a new ChromePdfRenderer object.
Private renderer = New ChromePdfRenderer()

' Step 3: Render a simple HTML string into a PDF document.
Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")

' Advanced Step: Render HTML with assets like images.
' The optional BasePath parameter helps locate external assets.
Private myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\site\assets\")

' Step 4: Save the basic PDF document to the file system.
pdf.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

The first step to converting an HTML string to a PDF in C# is ensuring that you have the IronPDF library properly set up and working within your project. By including using IronPdf, we make sure we can access the classes needed from the IronPDF library to carry out HTML to PDF conversion. The next line, Installation.EnableWebSecurity = true, is conceptually used to disable local disk access or cross-origin requests, ensuring secure operations. (Note: This line was missing from the example but usually pertains to configuration settings to secure PDF rendering operations.)

The example demonstrates how to create an instance of ChromePdfRenderer which handles the conversion of HTML to PDF. The RenderHtmlAsPdf method is used to convert a simple HTML string ("<h1>Hello World</h1>") into a PDF document. This document is saved to the disk using the SaveAs method.

In the advanced example, IronPDF is shown to handle HTML content containing external assets such as images, CSS, and JavaScript. To load these assets, the optional BasePath parameter is used, specifying the directory containing the required files. The resulting PDF, which includes the external assets, is saved using the same SaveAs method. This code example highlights IronPDF's ability to handle both basic and complex HTML content, making it an efficient tool for generating PDFs programmatically.

For more examples, check the How-to Guide on using IronPDF with C#.

ASPX and .NET: Converting a URL to a PDF Converting a URL to a PDF
using IronPdf;

// Instantiate Renderer
var renderer = new ChromePdfRenderer();

// Create a PDF from a URL or local file path
var pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");

// Export to a file or Stream
pdf.SaveAs("url.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer = New ChromePdfRenderer()

' Create a PDF from a URL or local file path
Private pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/")

' Export to a file or Stream
pdf.SaveAs("url.pdf")

IronPDF makes it very straightforward to render HTML from existing URLs as PDF documents. There is a very high level of support for JavaScript, images, forms, and CSS.

Rendering PDFs from ASP.NET URLs that accept query string variables can facilitate smooth PDF development as a collaborative effort between designers and coders.


// C# Example: Converting a URL to a PDF using IronPDF

// Import the IronPDF library
using IronPdf;

public class PdfGenerator
{
    public static void ConvertUrlToPdf(string url, string outputPath)
    {
        // Create a new instance of HtmlToPdf to handle the conversion
        var Renderer = new HtmlToPdf();

        // Render the URL into a PDF and save it to the specified path
        // The RenderUrlAsPdf method accepts a URL (website) you wish to convert
        PdfDocument pdf = Renderer.RenderUrlAsPdf(url);

        // Export the created PDF document to a file
        pdf.SaveAs(outputPath);

        // Inform the user the PDF has been created
        Console.WriteLine("PDF has been successfully generated at: " + outputPath);
    }
}
// C# Example: Converting a URL to a PDF using IronPDF

// Import the IronPDF library
using IronPdf;

public class PdfGenerator
{
    public static void ConvertUrlToPdf(string url, string outputPath)
    {
        // Create a new instance of HtmlToPdf to handle the conversion
        var Renderer = new HtmlToPdf();

        // Render the URL into a PDF and save it to the specified path
        // The RenderUrlAsPdf method accepts a URL (website) you wish to convert
        PdfDocument pdf = Renderer.RenderUrlAsPdf(url);

        // Export the created PDF document to a file
        pdf.SaveAs(outputPath);

        // Inform the user the PDF has been created
        Console.WriteLine("PDF has been successfully generated at: " + outputPath);
    }
}
' C# Example: Converting a URL to a PDF using IronPDF

' Import the IronPDF library
Imports IronPdf

Public Class PdfGenerator
	Public Shared Sub ConvertUrlToPdf(ByVal url As String, ByVal outputPath As String)
		' Create a new instance of HtmlToPdf to handle the conversion
		Dim Renderer = New HtmlToPdf()

		' Render the URL into a PDF and save it to the specified path
		' The RenderUrlAsPdf method accepts a URL (website) you wish to convert
		Dim pdf As PdfDocument = Renderer.RenderUrlAsPdf(url)

		' Export the created PDF document to a file
		pdf.SaveAs(outputPath)

		' Inform the user the PDF has been created
		Console.WriteLine("PDF has been successfully generated at: " & outputPath)
	End Sub
End Class
$vbLabelText   $csharpLabel

Explanation:

  • Importing Library: The code begins by importing the IronPdf library, which provides the functionality to create PDFs from URLs.
  • PdfGenerator Class: Contains the ConvertUrlToPdf method, which handles the conversion process.
  • HtmlToPdf Instance: An instance of HtmlToPdf is created to access the methods required for rendering web pages into PDFs.
  • Render URL: The RenderUrlAsPdf method is called with the URL of the web page to convert it into a PdfDocument.
  • Saving PDF: The generated PDF is saved to the desired location using the SaveAs method.
  • Completion Message: A message is printed to the console to confirm successful PDF creation.

Make sure to have the IronPDF library installed in your project. You can easily do this via NuGet Package Manager by searching for "IronPDF".

ASPX and .NET: HTML or Image File to PDF HTML or Image File to PDF
using IronPdf;

// Instantiate Renderer
var renderer = new ChromePdfRenderer();

// Create a PDF from an existing HTML file using C#
var pdf = renderer.RenderHtmlFileAsPdf("example.html");

// Export to a file or Stream
pdf.SaveAs("output.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer = New ChromePdfRenderer()

' Create a PDF from an existing HTML file using C#
Private pdf = renderer.RenderHtmlFileAsPdf("example.html")

' Export to a file or Stream
pdf.SaveAs("output.pdf")

IronPDF is a powerful .NET library capable of converting HTML files into high-quality PDF files. With IronPDF, you can render HTML files to PDF in just a couple of lines, and thanks to its support for modern web standards, the resulting PDF files will come out pixel-perfect. Leveraging IronPDF's powerful HTML file to PDF feature is easy thanks to its use of the ChromePdfRenderer class, which handles the conversion of HTML to PDF with ease.

This code creates a new PDF file that has been rendered from an HTML file. To do this, we must first ensure that the IronPDF library is installed and included within your project through the using IronPdf line. Next, initialize the ChromePdfRenderer class, which provides the functionality to render HTML content as a PDF. This class ensures that the original quality of the HTML file is not lost in the conversion process.

Once the renderer is instantiated, you can convert an existing HTML file into a PDF using the RenderHtmlFileAsPdf method. In this example, the HTML file "example.html" is passed to the method, creating a PDF object. Finally, to save the generated PDF, use the SaveAs method, specifying the desired file name and location. This simple process allows you to easily generate PDFs from HTML files in your C# applications.

// Ensure to include the IronPdf library in your project
using IronPdf;

class Program
{
    static void Main()
    {
        // Instantiate the ChromePdfRenderer, which will handle the HTML to PDF conversion
        var renderer = new ChromePdfRenderer();

        // Render the HTML file "example.html" to a PDF document
        var pdf = renderer.RenderHtmlFileAsPdf("example.html");

        // Save the rendered PDF to the specified location with the name "output.pdf"
        pdf.SaveAs("output.pdf");
    }
}
// Ensure to include the IronPdf library in your project
using IronPdf;

class Program
{
    static void Main()
    {
        // Instantiate the ChromePdfRenderer, which will handle the HTML to PDF conversion
        var renderer = new ChromePdfRenderer();

        // Render the HTML file "example.html" to a PDF document
        var pdf = renderer.RenderHtmlFileAsPdf("example.html");

        // Save the rendered PDF to the specified location with the name "output.pdf"
        pdf.SaveAs("output.pdf");
    }
}
' Ensure to include the IronPdf library in your project
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		' Instantiate the ChromePdfRenderer, which will handle the HTML to PDF conversion
		Dim renderer = New ChromePdfRenderer()

		' Render the HTML file "example.html" to a PDF document
		Dim pdf = renderer.RenderHtmlFileAsPdf("example.html")

		' Save the rendered PDF to the specified location with the name "output.pdf"
		pdf.SaveAs("output.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Click here to view the How-to Guide, including examples, sample code, and files

ASPX and .NET: PDF Generation Settings PDF Generation Settings
using IronPdf;
using IronPdf.Engines.Chrome;

// Instantiate Renderer
var renderer = new ChromePdfRenderer();

// Many rendering options to use to customize!
renderer.RenderingOptions.SetCustomPaperSizeInInches(12.5, 20);
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Landscape;
renderer.RenderingOptions.Title = "My PDF Document Name";
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(50); // in milliseconds
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
renderer.RenderingOptions.FitToPaperMode = FitToPaperModes.Zoom;
renderer.RenderingOptions.Zoom = 100;
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

// Supports margin customization!
renderer.RenderingOptions.MarginTop = 40; //millimeters
renderer.RenderingOptions.MarginLeft = 20; //millimeters
renderer.RenderingOptions.MarginRight = 20; //millimeters
renderer.RenderingOptions.MarginBottom = 40; //millimeters

// Can set FirstPageNumber if you have a cover page
renderer.RenderingOptions.FirstPageNumber = 1; // use 2 if a cover page will be appended

// Settings have been set, we can render:
renderer.RenderHtmlFileAsPdf("assets/wikipedia.html").SaveAs("output/my-content.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com

IronPDF aims to be as flexible as possible for the developer.

In this C# PDF Generation Tutorial Example, we show the balance between providing an API that automates internal functionality and providing one that gives you control.

IronPDF supports many customizations for generated PDF files, including page sizing, page margins, header/footer content, content scaling, CSS rulesets, and JavaScript execution.


We want developers to be able to control how Chrome turns a web page into a PDF. The ChromePdfRenderer Class Overview makes this possible.

Examples of settings available on the ChromePdfRenderer class include settings for margins, headers, footers, paper size, and form creation.

// Import the necessary namespaces for IronPDF
using IronPdf;

namespace PdfGenerationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the ChromePdfRenderer class
            var Renderer = new ChromePdfRenderer();

            // Customize the rendering options
            Renderer.RenderingOptions = new ChromePdfRenderOptions()
            {
                // Set paper size to A4
                PaperSize = PdfPaperSize.A4,

                // Set a margin of 10mm on all sides
                MarginTop = 10, // in millimeters
                MarginBottom = 10, // in millimeters
                MarginLeft = 10, // in millimeters
                MarginRight = 10, // in millimeters

                // Enable header and footer
                DisplayHeader = true,
                DisplayFooter = true,

                // Set headers and footers content
                Header = new HtmlHeaderFooter()
                {
                    HtmlFragment = "<p>This is the header</p>",
                    Height = 15 // in millimeters
                },
                Footer = new HtmlHeaderFooter()
                {
                    HtmlFragment = "<p>This is the footer</p>",
                    Height = 15 // in millimeters
                }
            };

            // Render a URL to a PDF document
            var pdfDocument = Renderer.RenderUrlAsPdf("https://yourwebsite.com");

            // Save the PDF document to a file
            pdfDocument.SaveAs("output.pdf");
        }
    }
}
// Import the necessary namespaces for IronPDF
using IronPdf;

namespace PdfGenerationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the ChromePdfRenderer class
            var Renderer = new ChromePdfRenderer();

            // Customize the rendering options
            Renderer.RenderingOptions = new ChromePdfRenderOptions()
            {
                // Set paper size to A4
                PaperSize = PdfPaperSize.A4,

                // Set a margin of 10mm on all sides
                MarginTop = 10, // in millimeters
                MarginBottom = 10, // in millimeters
                MarginLeft = 10, // in millimeters
                MarginRight = 10, // in millimeters

                // Enable header and footer
                DisplayHeader = true,
                DisplayFooter = true,

                // Set headers and footers content
                Header = new HtmlHeaderFooter()
                {
                    HtmlFragment = "<p>This is the header</p>",
                    Height = 15 // in millimeters
                },
                Footer = new HtmlHeaderFooter()
                {
                    HtmlFragment = "<p>This is the footer</p>",
                    Height = 15 // in millimeters
                }
            };

            // Render a URL to a PDF document
            var pdfDocument = Renderer.RenderUrlAsPdf("https://yourwebsite.com");

            // Save the PDF document to a file
            pdfDocument.SaveAs("output.pdf");
        }
    }
}
' Import the necessary namespaces for IronPDF
Imports IronPdf

Namespace PdfGenerationExample
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Create an instance of the ChromePdfRenderer class
			Dim Renderer = New ChromePdfRenderer()

			' Customize the rendering options
			Renderer.RenderingOptions = New ChromePdfRenderOptions() With {
				.PaperSize = PdfPaperSize.A4,
				.MarginTop = 10,
				.MarginBottom = 10,
				.MarginLeft = 10,
				.MarginRight = 10,
				.DisplayHeader = True,
				.DisplayFooter = True,
				.Header = New HtmlHeaderFooter() With {
					.HtmlFragment = "<p>This is the header</p>",
					.Height = 15
				},
				.Footer = New HtmlHeaderFooter() With {
					.HtmlFragment = "<p>This is the footer</p>",
					.Height = 15
				}
			}

			' Render a URL to a PDF document
			Dim pdfDocument = Renderer.RenderUrlAsPdf("https://yourwebsite.com")

			' Save the PDF document to a file
			pdfDocument.SaveAs("output.pdf")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel
  • The code example above demonstrates how to create a PDF document from a web page using the IronPDF library.
  • This involves setting up a renderer with specific options like paper size, margins, header, and footer.
  • The ChromePdfRenderer class is used to render the URL to a PDF.
  • The resulting PDF document is then saved to a file named "output.pdf".

ASPX and .NET: Image To PDF Image To PDF
using IronPdf;
using System.IO;
using System.Linq;

// One or more images as IEnumerable. This example selects all JPEG images in a specific 'assets' folder.
var imageFiles = Directory.EnumerateFiles("assets").Where(f => f.EndsWith(".jpg") || f.EndsWith(".jpeg"));

// Converts the images to a PDF and save it.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf");

// Also see PdfDocument.RasterizeToImageFiles() method to flatten a PDF to images or thumbnails
Imports IronPdf
Imports System.IO
Imports System.Linq

' One or more images as IEnumerable. This example selects all JPEG images in a specific 'assets' folder.
Private imageFiles = Directory.EnumerateFiles("assets").Where(Function(f) f.EndsWith(".jpg") OrElse f.EndsWith(".jpeg"))

' Converts the images to a PDF and save it.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf")

' Also see PdfDocument.RasterizeToImageFiles() method to flatten a PDF to images or thumbnails

Construct a PDF from Image Files Using the IronPdf.ImageToPdfConverter Class

How to Convert an Image to a PDF in C#

Given a single image located on a computer at C:\images\example.png, you can quickly convert it into a PDF document by calling the IronPdf.ImageToPdfConverter.ImageToPdf method with its file path:

// Convert a single image to a PDF.
var pdf = IronPdf.ImageToPdfConverter.ImageToPdf(@"C:\images\example.png");
// Save the resulting PDF to the specified location.
pdf.SaveAs("example.pdf");
// Convert a single image to a PDF.
var pdf = IronPdf.ImageToPdfConverter.ImageToPdf(@"C:\images\example.png");
// Save the resulting PDF to the specified location.
pdf.SaveAs("example.pdf");
' Convert a single image to a PDF.
Dim pdf = IronPdf.ImageToPdfConverter.ImageToPdf("C:\images\example.png")
' Save the resulting PDF to the specified location.
pdf.SaveAs("example.pdf")
$vbLabelText   $csharpLabel

Combine Multiple Images Into a PDF File

You can also convert multiple images into a single PDF document using System.IO.Directory.EnumerateFiles along with ImageToPdfConverter.ImageToPdf:

// Define the source directory containing the images.
string sourceDirectory = @"D:\web\assets";
// Define the path for the resulting PDF.
string destinationFile = "JpgToPDF.pdf";

// Get all image files in the source directory with a .jpg extension.
var imageFiles = System.IO.Directory.EnumerateFiles(sourceDirectory, "*.jpg");

// Convert the images into a single PDF.
var pdf = IronPdf.ImageToPdfConverter.ImageToPdf(imageFiles);

// Save the resulting PDF to the specified location.
pdf.SaveAs(destinationFile);
// Define the source directory containing the images.
string sourceDirectory = @"D:\web\assets";
// Define the path for the resulting PDF.
string destinationFile = "JpgToPDF.pdf";

// Get all image files in the source directory with a .jpg extension.
var imageFiles = System.IO.Directory.EnumerateFiles(sourceDirectory, "*.jpg");

// Convert the images into a single PDF.
var pdf = IronPdf.ImageToPdfConverter.ImageToPdf(imageFiles);

// Save the resulting PDF to the specified location.
pdf.SaveAs(destinationFile);
' Define the source directory containing the images.
Dim sourceDirectory As String = "D:\web\assets"
' Define the path for the resulting PDF.
Dim destinationFile As String = "JpgToPDF.pdf"

' Get all image files in the source directory with a .jpg extension.
Dim imageFiles = System.IO.Directory.EnumerateFiles(sourceDirectory, "*.jpg")

' Convert the images into a single PDF.
Dim pdf = IronPdf.ImageToPdfConverter.ImageToPdf(imageFiles)

' Save the resulting PDF to the specified location.
pdf.SaveAs(destinationFile)
$vbLabelText   $csharpLabel

To explore more about converting images to PDFs using IronPDF for enhancing your applications, or to discover the entire suite of developer tools offered by Iron Software, including IronBarcode, IronOCR, and more, visit the Iron Software website.

ASPX and .NET: Headers & Footers Headers & Footers
using IronPdf;

// Initiate PDF Renderer
var renderer = new ChromePdfRenderer();

// Add a header to every page easily
renderer.RenderingOptions.FirstPageNumber = 1; // use 2 if a cover page  will be appended
renderer.RenderingOptions.TextHeader.DrawDividerLine = true;
renderer.RenderingOptions.TextHeader.CenterText = "{url}";
renderer.RenderingOptions.TextHeader.Font = IronSoftware.Drawing.FontTypes.Helvetica;
renderer.RenderingOptions.TextHeader.FontSize = 12;
renderer.RenderingOptions.MarginTop = 25; //create 25mm space for header

// Add a footer too
renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial;
renderer.RenderingOptions.TextFooter.FontSize = 10;
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}";
renderer.RenderingOptions.MarginTop = 25; //create 25mm space for footer

// Mergeable fields are:
// {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
Imports IronPdf

' Initiate PDF Renderer
Private renderer = New ChromePdfRenderer()

' Add a header to every page easily
renderer.RenderingOptions.FirstPageNumber = 1 ' use 2 if a cover page  will be appended
renderer.RenderingOptions.TextHeader.DrawDividerLine = True
renderer.RenderingOptions.TextHeader.CenterText = "{url}"
renderer.RenderingOptions.TextHeader.Font = IronSoftware.Drawing.FontTypes.Helvetica
renderer.RenderingOptions.TextHeader.FontSize = 12
renderer.RenderingOptions.MarginTop = 25 'create 25mm space for header

' Add a footer too
renderer.RenderingOptions.TextFooter.DrawDividerLine = True
renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial
renderer.RenderingOptions.TextFooter.FontSize = 10
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}"
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"
renderer.RenderingOptions.MarginTop = 25 'create 25mm space for footer

' Mergeable fields are:
' {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}

There are two methods through which headers and footers may be added to a PDF document. They can either be added as a classic text format, with the option to merge in dynamic data. Or, they can be added through the much more flexible HTML format, which allows developers to render dynamic headers and footers through their HTML content.

Steps to Add Headers and Footers to PDFs with IronPDF

// Ensure you have included the IronPdf library in your project
using IronPdf;

// Instantiate a ChromePdfRenderer for rendering PDFs
var renderer = new ChromePdfRenderer();

// Configure header options
// Enable a divider line for the header
renderer.RenderingOptions.TextHeader.DrawDividerLine = true;

// Center the text in the header, using the document URL as content
renderer.RenderingOptions.TextHeader.CenterText = "{url}";

// Select a font type and size for the header text
renderer.RenderingOptions.TextHeader.Font = IronSoftware.Drawing.FontTypes.Helvetica;
renderer.RenderingOptions.TextHeader.FontSize = 12;

// Additional header configurations can be made such as setting a margin
// Ensure you have included the IronPdf library in your project
using IronPdf;

// Instantiate a ChromePdfRenderer for rendering PDFs
var renderer = new ChromePdfRenderer();

// Configure header options
// Enable a divider line for the header
renderer.RenderingOptions.TextHeader.DrawDividerLine = true;

// Center the text in the header, using the document URL as content
renderer.RenderingOptions.TextHeader.CenterText = "{url}";

// Select a font type and size for the header text
renderer.RenderingOptions.TextHeader.Font = IronSoftware.Drawing.FontTypes.Helvetica;
renderer.RenderingOptions.TextHeader.FontSize = 12;

// Additional header configurations can be made such as setting a margin
' Ensure you have included the IronPdf library in your project
Imports IronPdf

' Instantiate a ChromePdfRenderer for rendering PDFs
Private renderer = New ChromePdfRenderer()

' Configure header options
' Enable a divider line for the header
renderer.RenderingOptions.TextHeader.DrawDividerLine = True

' Center the text in the header, using the document URL as content
renderer.RenderingOptions.TextHeader.CenterText = "{url}"

' Select a font type and size for the header text
renderer.RenderingOptions.TextHeader.Font = IronSoftware.Drawing.FontTypes.Helvetica
renderer.RenderingOptions.TextHeader.FontSize = 12

' Additional header configurations can be made such as setting a margin
$vbLabelText   $csharpLabel

Today we will be looking at how you can add classic text headers and footers into your PDF documents in just a few simple steps. The first step towards adding customized Headers and Footers into your PDF documents is to ensure that the IronPDF library is included in your project with the using IronPdf; statement. Then, instantiate the ChromePdfRenderer, which provides the functionality to render your HTML content in pixel-perfect PDF documents.

Next, configure the header settings. The FirstPageNumber property allows you to specify the starting page number, accommodating for a cover page if needed. The TextHeader properties enable you to customize the appearance, such as drawing a divider line, centering text (in this case, the document URL), selecting the font type and size, and creating a margin at the top of the page for the header.

After configuring the header, set up the footer using the TextFooter properties. Similar to the header, you can draw a divider line, choose the font type and size, and include dynamic content like the current date, time, and page numbers with total pages. Finally, a margin is created at the bottom of the page to accommodate the footer.

By following these steps, you can enhance your PDF documents with informative headers and footers that improve their professionalism and readability.

Click here to view the How-to Guide, including examples, sample code, and files

ASPX and .NET: HTML Headers & Footers HTML Headers & Footers
using IronPdf;
using System;

// Instantiate Renderer
var renderer = new IronPdf.ChromePdfRenderer();


// Build a footer using html to style the text
// mergeable fields are:
// {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    MaxHeight = 15, //millimeters
    HtmlFragment = "<center><i>{page} of {total-pages}<i></center>",
    DrawDividerLine = true
};

// Use sufficient MarginBottom to ensure that the HtmlFooter does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginBottom = 25; //mm


// Build a header using an image asset
// Note the use of BaseUrl to set a relative path to the assets
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    MaxHeight = 20, //millimeters
    HtmlFragment = "<img src='logo.png'>",
    BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri
};

// Use sufficient MarginTop to ensure that the HtmlHeader does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginTop = 25; //mm
Imports IronPdf
Imports System

' Instantiate Renderer
Private renderer = New IronPdf.ChromePdfRenderer()


' Build a footer using html to style the text
' mergeable fields are:
' {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {
	.MaxHeight = 15,
	.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>",
	.DrawDividerLine = True
}

' Use sufficient MarginBottom to ensure that the HtmlFooter does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginBottom = 25 'mm


' Build a header using an image asset
' Note the use of BaseUrl to set a relative path to the assets
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
	.MaxHeight = 20,
	.HtmlFragment = "<img src='logo.png'>",
	.BaseUrl = (New Uri("C:\assets\images\")).AbsoluteUri
}

' Use sufficient MarginTop to ensure that the HtmlHeader does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginTop = 25 'mm

HTML headers and footers provide a flexible method for creating dynamic headers and footers for your PDF documents. By adding headers and footers through this method, developers have complete control over how their headers and footers look, as they are rendered as independent HTML documents capable of containing their own assets and stylesheets.

Steps to Add Custom HTML Headers and Footers in a PDF with IronPDF

// Create a new instance of the ChromePdfRenderer class.
var renderer = new IronPdf.ChromePdfRenderer();

// Define a footer with the HtmlHeaderFooter class
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
    HtmlFragment = "<center><i>{page} of {total-pages}</i></center>", // Include page numbering
    MaxHeight = 20, // Set maximum height for the footer
    BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri // Base URL for resolving relative paths
};

// Define a header (optional)
// renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
// {
//    HtmlFragment = "<img src='logo.png' alt='Company Logo' />",
//    MaxHeight = 50, 
//    BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri 
// };

// Set margins to prevent overlap between header/footer and main content
renderer.RenderingOptions.MarginBottom = 30; // Adjust bottom margin for footer
renderer.RenderingOptions.MarginTop = 50; // Adjust top margin for header
// Create a new instance of the ChromePdfRenderer class.
var renderer = new IronPdf.ChromePdfRenderer();

// Define a footer with the HtmlHeaderFooter class
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
    HtmlFragment = "<center><i>{page} of {total-pages}</i></center>", // Include page numbering
    MaxHeight = 20, // Set maximum height for the footer
    BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri // Base URL for resolving relative paths
};

// Define a header (optional)
// renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
// {
//    HtmlFragment = "<img src='logo.png' alt='Company Logo' />",
//    MaxHeight = 50, 
//    BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri 
// };

// Set margins to prevent overlap between header/footer and main content
renderer.RenderingOptions.MarginBottom = 30; // Adjust bottom margin for footer
renderer.RenderingOptions.MarginTop = 50; // Adjust top margin for header
' Create a new instance of the ChromePdfRenderer class.
Dim renderer = New IronPdf.ChromePdfRenderer()

' Define a footer with the HtmlHeaderFooter class
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter With {
	.HtmlFragment = "<center><i>{page} of {total-pages}</i></center>",
	.MaxHeight = 20,
	.BaseUrl = (New Uri("C:\assets\images\")).AbsoluteUri
}

' Define a header (optional)
' renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
' {
'    HtmlFragment = "<img src='logo.png' alt='Company Logo' />",
'    MaxHeight = 50, 
'    BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri 
' };

' Set margins to prevent overlap between header/footer and main content
renderer.RenderingOptions.MarginBottom = 30 ' Adjust bottom margin for footer
renderer.RenderingOptions.MarginTop = 50 ' Adjust top margin for header
$vbLabelText   $csharpLabel

To begin with, you first need to create an instance of the ChromePdfRenderer class, which handles the rendering of HTML content into a pixel-perfect PDF document.

Next, define a footer using the HtmlHeaderFooter class, where you specify the MaxHeight, HTML content for the footer (which in our case includes page numbering), and base URL for image resolution. The footer is styled to display centered page information.

To avoid overlap between the footer and the PDF's main content, set a bottom margin using the MarginBottom property. Similarly, create a header that includes an image (such as a logo) by using the HtmlHeaderFooter class. Here we have set up a BaseUrl to the directory containing your image asset, allowing for proper image resolution during rendering.

Finally, use the MarginTop property to set a top margin that prevents overlap between the header and the content. This example demonstrates how easy it is to implement custom HTML headers and footers in your PDF documents with IronPDF.

Click here to view the How-to Guide, including examples, sample code, and files

ASPX and .NET: Editing PDFs Editing PDFs
using IronPdf;
using System.Collections.Generic;

// Instantiate Renderer
var renderer = new ChromePdfRenderer();

// Join Multiple Existing PDFs into a single document
var pdfs = new List<PdfDocument>();
pdfs.Add(PdfDocument.FromFile("A.pdf"));
pdfs.Add(PdfDocument.FromFile("B.pdf"));
pdfs.Add(PdfDocument.FromFile("C.pdf"));
var pdf = PdfDocument.Merge(pdfs);
pdf.SaveAs("merged.pdf");

// Add a cover page
pdf.PrependPdf(renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>"));

// Remove the last page from the PDF and save again
pdf.RemovePage(pdf.PageCount - 1);
pdf.SaveAs("merged.pdf");

// Copy pages 5-7 and save them as a new document.
pdf.CopyPages(4, 6).SaveAs("excerpt.pdf");

foreach (var eachPdf in pdfs)
{
    eachPdf.Dispose();
}
Imports IronPdf
Imports System.Collections.Generic

' Instantiate Renderer
Private renderer = New ChromePdfRenderer()

' Join Multiple Existing PDFs into a single document
Private pdfs = New List(Of PdfDocument)()
pdfs.Add(PdfDocument.FromFile("A.pdf"))
pdfs.Add(PdfDocument.FromFile("B.pdf"))
pdfs.Add(PdfDocument.FromFile("C.pdf"))
Dim pdf = PdfDocument.Merge(pdfs)
pdf.SaveAs("merged.pdf")

' Add a cover page
pdf.PrependPdf(renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>"))

' Remove the last page from the PDF and save again
pdf.RemovePage(pdf.PageCount - 1)
pdf.SaveAs("merged.pdf")

' Copy pages 5-7 and save them as a new document.
pdf.CopyPages(4, 6).SaveAs("excerpt.pdf")

For Each eachPdf In pdfs
	eachPdf.Dispose()
Next eachPdf

IronPDF offers 50+ features for reading and editing PDFs. The most popular are merging PDFs, cloning pages, and extracting text from rotated content.

IronPDF also allows its users to add watermarks, rotate pages, add annotations, digitally sign PDF pages, create new PDF documents, attach cover pages, customize PDF sizes, and much more when generating and formatting PDF files. Moreover, it supports conversion of PDFs into all conventional image file types, including JPG, BMP, JPEG, GIF, PNG, TIFF, etc.

Read the C# PDF editing tutorial to learn how to make full use of IronPDF to modify PDF documents to best suit project requirements.


Here is a simple example that demonstrates how to edit a PDF file by adding a watermark and saving the changes:

// Import IronPdf's namespace to access PDF editing functionalities.
using IronPdf;

class PdfEditor
{
    public static void Main()
    {
        // Load an existing PDF document from file.
        var pdf = PdfDocument.FromFile("example.pdf");

        // Add a watermark to each page in the PDF.
        foreach (var page in pdf.Pages)
        {
            page.Watermark = new TextWatermark("CONFIDENTIAL", 50);
        }

        // Save the modified document as a new PDF file.
        pdf.SaveAs("edited_example.pdf");

        // Output message indicating the operation completion.
        Console.WriteLine("PDF edited and saved successfully.");
    }
}
// Import IronPdf's namespace to access PDF editing functionalities.
using IronPdf;

class PdfEditor
{
    public static void Main()
    {
        // Load an existing PDF document from file.
        var pdf = PdfDocument.FromFile("example.pdf");

        // Add a watermark to each page in the PDF.
        foreach (var page in pdf.Pages)
        {
            page.Watermark = new TextWatermark("CONFIDENTIAL", 50);
        }

        // Save the modified document as a new PDF file.
        pdf.SaveAs("edited_example.pdf");

        // Output message indicating the operation completion.
        Console.WriteLine("PDF edited and saved successfully.");
    }
}
' Import IronPdf's namespace to access PDF editing functionalities.
Imports IronPdf

Friend Class PdfEditor
	Public Shared Sub Main()
		' Load an existing PDF document from file.
		Dim pdf = PdfDocument.FromFile("example.pdf")

		' Add a watermark to each page in the PDF.
		For Each page In pdf.Pages
			page.Watermark = New TextWatermark("CONFIDENTIAL", 50)
		Next page

		' Save the modified document as a new PDF file.
		pdf.SaveAs("edited_example.pdf")

		' Output message indicating the operation completion.
		Console.WriteLine("PDF edited and saved successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

Code Explanation

  1. Import IronPdf Namespace: This provides access to classes and methods for handling PDF files.
  2. Load PDF Document: PdfDocument.FromFile("example.pdf") loads a PDF file into the program.
  3. Add Watermark: Iterates through Pages of pdf, applying a TextWatermark with the text "CONFIDENTIAL" and a font size of 50.
  4. Save As New PDF: pdf.SaveAs("edited_example.pdf") saves the modified PDF under a new name.
  5. Inform Completion: Outputs a message to the console upon successful completion.

ASPX and .NET: Passwords, Security & Metadata Passwords, Security & Metadata
using IronPdf;

// Open an Encrypted File, alternatively create a new PDF from Html
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");

// Get file metadata
System.Collections.Generic.List<string> metadatakeys = pdf.MetaData.Keys(); // returns {"Title", "Creator", ...}

// Remove file metadata
pdf.MetaData.RemoveMetaDataKey("Title");
metadatakeys = pdf.MetaData.Keys(); // return {"Creator", ...} // title was deleted

// Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = System.DateTime.Now;

// The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption();
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key");
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;

// Change or set the document encryption password
pdf.SecuritySettings.OwnerPassword = "top-secret"; // password to edit the pdf
pdf.SecuritySettings.UserPassword = "sharable"; // password to open the pdf
pdf.SaveAs("secured.pdf");
Imports System
Imports IronPdf

' Open an Encrypted File, alternatively create a new PDF from Html
Private pdf = PdfDocument.FromFile("encrypted.pdf", "password")

' Get file metadata
Private metadatakeys As System.Collections.Generic.List(Of String) = pdf.MetaData.Keys() ' returns {"Title", "Creator", ...}

' Remove file metadata
pdf.MetaData.RemoveMetaDataKey("Title")
metadatakeys = pdf.MetaData.Keys() ' return {"Creator", ...} // title was deleted

' Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = DateTime.Now

' The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key")
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights

' Change or set the document encryption password
pdf.SecuritySettings.OwnerPassword = "top-secret" ' password to edit the pdf
pdf.SecuritySettings.UserPassword = "sharable" ' password to open the pdf
pdf.SaveAs("secured.pdf")

IronPDF provides developers with strong PDF security options, supporting the customization and setting of PDF metadata, passwords, permissions, and more. With IronPDF's passwords, security, and metadata options, you can create custom permissions and security levels to fit the need of your PDF document. This is done thanks to the use of classes such as the SecuritySettings and MetaData classes. Some options include limiting the PDF documents to be unprintable, setting them to read-only, and 128-bit encryption, and password protection of your PDF documents.

Setting custom metadata works by implementing the MetaData class to access the various PDF metadata options, and setting them with your customized values. This includes changing the author, keywords, modified data, and more. Setting custom security settings includes the ability to set custom user and owner passwords, printing permissions, read-only mode, and more.

In order to begin customizing the security of your PDF documents, you must first load an existing PDF or create a new one. Here, we have loaded an existing password-protected PDF document, where we have input the password needed to open the PDF document. Once the PDF is loaded, we then use pdf.MetaData.Keys to get the PDF's current metadata. To remove existing PDF metadata values, use the RemoveMetaDataKey method. To begin setting new metadata values, use pdf.MetaData.metadataField (e.g., pdf.MetaData.Keywords), and then just assign the new value to it. Metadata fields such as Title and Keywords take string values, whereas the ModifiedData field takes datetime values.

Next, we have set new security settings using the SecuritySettings class. As you can see, there are a variety of settings that you can set here. This gives you full control over the permissions and security levels for each PDF document you work with. To access these settings, you just need to make sure you use pdf.SecuritySettings, followed by the setting you want to adjust. For example, the MakePdfDocumentReadOnly method sets the PDF document to be read-only, encrypting the content at 128-bit. Other options for SecuritySettings include:

  • AllowUserAnnotations: Controls whether or not users can annotate the PDF.
  • AllowUserPrinting: Controls printing permissions for the document.
  • AllowUserFormData: Sets the permissions for whether users can fill-in forms.
  • OwnerPassword: Sets the owner password for the PDF, which is used to disable or enable the other security settings.
  • UserPassword: Sets the user password for the PDF, which must be entered in order to open or print the document.

Once you have set the custom metadata, passwords, and security settings for your PDF document, use the pdf.SaveAs method to save your PDF to a specified location.

Click here to view the How-to-Guide, including examples, sample code and files

ASPX and .NET: PDF Watermarking PDF Watermarking
using IronPdf;

// Stamps a Watermark onto a new or existing PDF
var renderer = new ChromePdfRenderer();

var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs("watermarked.pdf");
Imports IronPdf

' Stamps a Watermark onto a new or existing PDF
Private renderer = New ChromePdfRenderer()

Private pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center)
pdf.SaveAs("watermarked.pdf")

IronPDF provides methods to 'watermark' PDF documents with HTML.

Using the ApplyStamp method, developers can add an HTML-based watermark to a PDF file. As shown in the example above, the HTML code for the watermark goes as the first argument to the method. Additional arguments to ApplyStamp control the rotation, opacity, and position of the watermark.

Utilize the ApplyStamp method in lieu of the ApplyWatermark method for more granular control over watermark placement. For example, use ApplyStamp to:

  • Add Text, Image, or HTML watermarks to PDFs
  • Apply the same watermark to every page of the PDF
  • Apply different watermarks to specific PDF pages
  • Adjust the placement of watermarks in front or behind page copy
  • Adjust the opacity, rotation, and alignment of watermarks with more precision

Example C# Code to Apply a Watermark Using IronPDF

Ensure you have installed the IronPDF library in your project. You can find more detailed instructions on the IronPDF NuGet package page.

using IronPdf;

public class PdfWatermarkExample
{
    public static void Main()
    {
        // Create a new PDF document or load an existing one
        var pdfDocument = PdfDocument.FromFile("example.pdf");

        // Define HTML content for the watermark
        string htmlWatermark = "<div style='font-size:72pt; color:red; opacity:0.3;'>Confidential</div>";

        // Apply the watermark to the PDF
        // Parameters: HTML, Rotation (degrees), X Position, Y Position, Opacity, Page(s)
        pdfDocument.ApplyStamp(htmlWatermark, 
                               rotationDegrees: 45, 
                               left: 50, 
                               top: 50, 
                               opacity: 0.5, 
                               pageRange: PageRange.AllPages);

        // Save the modified PDF document
        pdfDocument.SaveAs("watermarked_example.pdf");
    }
}
using IronPdf;

public class PdfWatermarkExample
{
    public static void Main()
    {
        // Create a new PDF document or load an existing one
        var pdfDocument = PdfDocument.FromFile("example.pdf");

        // Define HTML content for the watermark
        string htmlWatermark = "<div style='font-size:72pt; color:red; opacity:0.3;'>Confidential</div>";

        // Apply the watermark to the PDF
        // Parameters: HTML, Rotation (degrees), X Position, Y Position, Opacity, Page(s)
        pdfDocument.ApplyStamp(htmlWatermark, 
                               rotationDegrees: 45, 
                               left: 50, 
                               top: 50, 
                               opacity: 0.5, 
                               pageRange: PageRange.AllPages);

        // Save the modified PDF document
        pdfDocument.SaveAs("watermarked_example.pdf");
    }
}
CONVERTER NOT RUNNING
$vbLabelText   $csharpLabel

Explanation of the Code:

  • We start by importing the IronPdf library, which provides all necessary classes and methods for PDF manipulation.
  • A PDF document is created or loaded using PdfDocument.FromFile, specifying the file path of the existing PDF.
  • HTML content is defined for the watermark. In this case, the watermark displays "Confidential" with specific styling.
  • The ApplyStamp method is used to overlay the watermark on the PDF. This method allows for detailed customization:
    • rotationDegrees: Specifies the rotation, in degrees, of the watermark.
    • left and top: Dictate the X and Y position of the watermark, measured from the top-left corner.
    • opacity: Determines the transparency of the watermark.
    • pageRange: Specifies which pages should receive the watermark, allowing for diverse placement strategies.
  • Finally, the SaveAs method exports the modified PDF to a new file.

In conclusion, the IronPDF ApplyStamp method allows for precise control over watermarking PDF documents using HTML. This approach is flexible, accommodating various customization needs for positioning, styling, and applying watermarks to specified pages.

ASPX and .NET: Backgrounds & Foregrounds Backgrounds & Foregrounds
using IronPdf;

// With IronPDF, we can easily merge 2 PDF files using one as a background or foreground
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.AddBackgroundPdf(@"MyBackground.pdf");
pdf.AddForegroundOverlayPdfToPage(0, @"MyForeground.pdf", 0);
pdf.SaveAs("complete.pdf");
Imports IronPdf

' With IronPDF, we can easily merge 2 PDF files using one as a background or foreground
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.AddBackgroundPdf("MyBackground.pdf")
pdf.AddForegroundOverlayPdfToPage(0, "MyForeground.pdf", 0)
pdf.SaveAs("complete.pdf")

You may want to use a specific background and foreground as you create and render your PDF documents in IronPDF. In such a case, you can use an existing or rendered PDF as the background or foreground for another PDF document. This is particularly useful for design consistency and templating.

This example shows you how to use a PDF document as the background or foreground of another PDF document.

You can do this in C# by loading or creating a multi-page PDF as an IronPdf.PdfDocument object.

You can add backgrounds using PdfDocument.AddBackgroundPdf. For more details on background insertion methods, refer to the IronPDF.PdfDocument background documentation; it describes several background insertion methods and their overrides. This adds a background to each page of your working PDF. The background is copied from a page in another PDF document.

You can add foregrounds, also known as "Overlays," using PdfDocument.AddForegroundOverlayPdfToPage. For detailed information on foreground insertion methods, consult the IronPDF.PdfDocument overlay documentation.

Here is a code snippet demonstrating how you might accomplish this in C#:

using IronPdf;

public class PdfExample
{
    public static void Main()
    {
        // Load or create the main PDF document
        var mainPdf = PdfDocument.FromFile("main.pdf"); // Load an existing PDF
        // OR
        // var mainPdf = new HtmlToPdf().RenderHtmlAsPdf("<p>Hello, World!</p>"); // Create a new PDF from HTML

        // Load the PDF you want to use as a background
        PdfDocument backgroundPdf = PdfDocument.FromFile("background.pdf");

        // Add the background PDF to each page of the main PDF
        // This operation will overlay each page of 'backgroundPdf' onto the corresponding page of 'mainPdf'
        mainPdf.AddBackgroundPdf(backgroundPdf);

        // Load the PDF you want to use as a foreground (overlay)
        PdfDocument overlayPdf = PdfDocument.FromFile("overlay.pdf");

        // Add the overlay PDF to each page of the main PDF
        // This operation overlays each page of 'overlayPdf' onto the corresponding page of 'mainPdf'
        for (int i = 0; i < mainPdf.PageCount; i++)
        {
            mainPdf.AddForegroundOverlayPdfToPage(overlayPdf, i);
        }

        // Save the modified main PDF to a file
        mainPdf.SaveAs("output.pdf");
    }
}
using IronPdf;

public class PdfExample
{
    public static void Main()
    {
        // Load or create the main PDF document
        var mainPdf = PdfDocument.FromFile("main.pdf"); // Load an existing PDF
        // OR
        // var mainPdf = new HtmlToPdf().RenderHtmlAsPdf("<p>Hello, World!</p>"); // Create a new PDF from HTML

        // Load the PDF you want to use as a background
        PdfDocument backgroundPdf = PdfDocument.FromFile("background.pdf");

        // Add the background PDF to each page of the main PDF
        // This operation will overlay each page of 'backgroundPdf' onto the corresponding page of 'mainPdf'
        mainPdf.AddBackgroundPdf(backgroundPdf);

        // Load the PDF you want to use as a foreground (overlay)
        PdfDocument overlayPdf = PdfDocument.FromFile("overlay.pdf");

        // Add the overlay PDF to each page of the main PDF
        // This operation overlays each page of 'overlayPdf' onto the corresponding page of 'mainPdf'
        for (int i = 0; i < mainPdf.PageCount; i++)
        {
            mainPdf.AddForegroundOverlayPdfToPage(overlayPdf, i);
        }

        // Save the modified main PDF to a file
        mainPdf.SaveAs("output.pdf");
    }
}
CONVERTER NOT RUNNING
$vbLabelText   $csharpLabel

Key Points

  • Background PDF is added to each page from the provided background.pdf.
  • Foreground PDF (Overlay) is added to each page from the provided overlay.pdf.
  • Modify file paths ("main.pdf", "background.pdf", "overlay.pdf", "output.pdf") as needed to fit your file system setup.

This code illustrates how to integrate additional design elements on top of a base PDF using IronPDF. Always refer to the official documentation for more advanced techniques and additional options.

ASPX and .NET: Form Data Form Data
using IronPdf;
using System;

// Step 1.  Creating a PDF with editable forms from HTML using form and input tags
// Radio Button and Checkbox can also be implemented with input type 'radio' and 'checkbox'
const string formHtml = @"
    <html>
        <body>
            <h2>Editable PDF  Form</h2>
            <form>
              First name: <br> <input type='text' name='firstname' value=''> <br>
              Last name: <br> <input type='text' name='lastname' value=''> <br>
              <br>
              <p>Please specify your gender:</p>
              <input type='radio' id='female' name='gender' value= 'Female'>
                <label for='female'>Female</label> <br>
                <br>
              <input type='radio' id='male' name='gender' value='Male'>
                <label for='male'>Male</label> <br>
                <br>
              <input type='radio' id='non-binary/other' name='gender' value='Non-Binary / Other'>
                <label for='non-binary/other'>Non-Binary / Other</label>
              <br>

              <p>Please select all medical conditions that apply:</p>
              <input type='checkbox' id='condition1' name='Hypertension' value='Hypertension'>
              <label for='condition1'> Hypertension</label><br>
              <input type='checkbox' id='condition2' name='Heart Disease' value='Heart Disease'>
              <label for='condition2'> Heart Disease</label><br>
              <input type='checkbox' id='condition3' name='Stoke' value='Stoke'>
              <label for='condition3'> Stoke</label><br>
              <input type='checkbox' id='condition4' name='Diabetes' value='Diabetes'>
              <label for='condition4'> Diabetes</label><br>
              <input type='checkbox' id='condition5' name='Kidney Disease' value='Kidney Disease'>
              <label for='condition5'> Kidney Disease</label><br>
            </form>
        </body>
    </html>";

// Instantiate Renderer
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
renderer.RenderHtmlAsPdf(formHtml).SaveAs("BasicForm.pdf");

// Step 2. Reading and Writing PDF form values.
var FormDocument = PdfDocument.FromFile("BasicForm.pdf");

// Set and Read the value of the "firstname" field
var FirstNameField = FormDocument.Form.FindFormField("firstname");
FirstNameField.Value = "Minnie";
Console.WriteLine("FirstNameField value: {0}", FirstNameField.Value);

// Set and Read the value of the "lastname" field
var LastNameField = FormDocument.Form.FindFormField("lastname");
LastNameField.Value = "Mouse";
Console.WriteLine("LastNameField value: {0}", LastNameField.Value);

FormDocument.SaveAs("FilledForm.pdf");
Imports IronPdf
Imports System

' Step 1.  Creating a PDF with editable forms from HTML using form and input tags
' Radio Button and Checkbox can also be implemented with input type 'radio' and 'checkbox'
Private Const formHtml As String = "
    <html>
        <body>
            <h2>Editable PDF  Form</h2>
            <form>
              First name: <br> <input type='text' name='firstname' value=''> <br>
              Last name: <br> <input type='text' name='lastname' value=''> <br>
              <br>
              <p>Please specify your gender:</p>
              <input type='radio' id='female' name='gender' value= 'Female'>
                <label for='female'>Female</label> <br>
                <br>
              <input type='radio' id='male' name='gender' value='Male'>
                <label for='male'>Male</label> <br>
                <br>
              <input type='radio' id='non-binary/other' name='gender' value='Non-Binary / Other'>
                <label for='non-binary/other'>Non-Binary / Other</label>
              <br>

              <p>Please select all medical conditions that apply:</p>
              <input type='checkbox' id='condition1' name='Hypertension' value='Hypertension'>
              <label for='condition1'> Hypertension</label><br>
              <input type='checkbox' id='condition2' name='Heart Disease' value='Heart Disease'>
              <label for='condition2'> Heart Disease</label><br>
              <input type='checkbox' id='condition3' name='Stoke' value='Stoke'>
              <label for='condition3'> Stoke</label><br>
              <input type='checkbox' id='condition4' name='Diabetes' value='Diabetes'>
              <label for='condition4'> Diabetes</label><br>
              <input type='checkbox' id='condition5' name='Kidney Disease' value='Kidney Disease'>
              <label for='condition5'> Kidney Disease</label><br>
            </form>
        </body>
    </html>"

' Instantiate Renderer
Private renderer = New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
renderer.RenderHtmlAsPdf(formHtml).SaveAs("BasicForm.pdf")

' Step 2. Reading and Writing PDF form values.
Dim FormDocument = PdfDocument.FromFile("BasicForm.pdf")

' Set and Read the value of the "firstname" field
Dim FirstNameField = FormDocument.Form.FindFormField("firstname")
FirstNameField.Value = "Minnie"
Console.WriteLine("FirstNameField value: {0}", FirstNameField.Value)

' Set and Read the value of the "lastname" field
Dim LastNameField = FormDocument.Form.FindFormField("lastname")
LastNameField.Value = "Mouse"
Console.WriteLine("LastNameField value: {0}", LastNameField.Value)

FormDocument.SaveAs("FilledForm.pdf")

You can create editable PDF documents with IronPDF as easily as a normal document. The PdfForm class is a collection of user-editable form fields within a PDF document. It can be implemented into your PDF render to make it a form or an editable document.

This example shows you how to create editable PDF forms in IronPDF.

PDFs with editable forms can be created from HTML simply by adding <form>, <input>, and <textarea> tags to the document parts.

The PdfDocument.Form.FindFormField method can be used to read and write the value of any form field. The field's name will be the same as the 'name' attribute given to that field in your HTML.

The PdfDocument.Form object can be used in two ways:

  • Populating Default Values: This can be used to set a default value for form fields that will be displayed in PDF viewers like Adobe Reader.
  • Reading User Input: After the user fills in the form, the form fields can be accessed and the data read back into your application.
using IronPdf; // Import the IronPdf library

// Function to create and manipulate a PDF document with form fields
public void CreateEditablePdfDocument()
{
    // HTML string defining a simple form with input fields
    var htmlContent = @"
    <html>
    <body>
        <form>
            <input type='text' name='username' placeholder='Enter your username' />
            <textarea name='comments' placeholder='Enter your comments'></textarea>
        </form>
    </body>
    </html>";

    // Render the HTML to a PDF document
    var renderer = new HtmlToPdf();
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

    // Access the form within the PDF
    var pdfForm = pdfDocument.Form;

    // Set default values for the form fields
    pdfForm["username"].Value = "DefaultUser";  // Populate the 'username' field with a default value
    pdfForm["comments"].Value = "Default comment.";  // Populate the 'comments' field with a default text

    // Save the PDF to a file
    pdfDocument.SaveAs("EditableForm.pdf");  // Save the PDF document with a specified filename

    // The document has now been created and saved with editable fields.
}
using IronPdf; // Import the IronPdf library

// Function to create and manipulate a PDF document with form fields
public void CreateEditablePdfDocument()
{
    // HTML string defining a simple form with input fields
    var htmlContent = @"
    <html>
    <body>
        <form>
            <input type='text' name='username' placeholder='Enter your username' />
            <textarea name='comments' placeholder='Enter your comments'></textarea>
        </form>
    </body>
    </html>";

    // Render the HTML to a PDF document
    var renderer = new HtmlToPdf();
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

    // Access the form within the PDF
    var pdfForm = pdfDocument.Form;

    // Set default values for the form fields
    pdfForm["username"].Value = "DefaultUser";  // Populate the 'username' field with a default value
    pdfForm["comments"].Value = "Default comment.";  // Populate the 'comments' field with a default text

    // Save the PDF to a file
    pdfDocument.SaveAs("EditableForm.pdf");  // Save the PDF document with a specified filename

    // The document has now been created and saved with editable fields.
}
Imports IronPdf ' Import the IronPdf library

' Function to create and manipulate a PDF document with form fields
Public Sub CreateEditablePdfDocument()
	' HTML string defining a simple form with input fields
	Dim htmlContent = "
    <html>
    <body>
        <form>
            <input type='text' name='username' placeholder='Enter your username' />
            <textarea name='comments' placeholder='Enter your comments'></textarea>
        </form>
    </body>
    </html>"

	' Render the HTML to a PDF document
	Dim renderer = New HtmlToPdf()
	Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

	' Access the form within the PDF
	Dim pdfForm = pdfDocument.Form

	' Set default values for the form fields
	pdfForm("username").Value = "DefaultUser" ' Populate the 'username' field with a default value
	pdfForm("comments").Value = "Default comment." ' Populate the 'comments' field with a default text

	' Save the PDF to a file
	pdfDocument.SaveAs("EditableForm.pdf") ' Save the PDF document with a specified filename

	' The document has now been created and saved with editable fields.
End Sub
$vbLabelText   $csharpLabel

In the example above, we first import the IronPdf library and define a method CreateEditablePdfDocument. This method contains the HTML structure of a simple form with input fields for username and comments. Using the HtmlToPdf renderer, we convert this HTML content into a PDF document.

The pdfDocument.Form is then used to access and manipulate the form fields. We set default values that will appear when the document is opened in a PDF viewer. Finally, the document is saved with the name "EditableForm.pdf", allowing it to be stored or shared with embedded editable fields.

ASPX and .NET: Rasterize a PDF to Images Rasterize a PDF to Images
using IronPdf;
using IronSoftware.Drawing;

var pdf = PdfDocument.FromFile("Example.pdf");

// Extract all pages to a folder as image files
pdf.RasterizeToImageFiles(@"C:\image\folder\*.png");

// Dimensions and page ranges may be specified
pdf.RasterizeToImageFiles(@"C:\image\folder\example_pdf_image_*.jpg", 100, 80);

// Extract all pages as AnyBitmap objects
AnyBitmap[] pdfBitmaps = pdf.ToBitmap();
Imports IronPdf
Imports IronSoftware.Drawing

Private pdf = PdfDocument.FromFile("Example.pdf")

' Extract all pages to a folder as image files
pdf.RasterizeToImageFiles("C:\image\folder\*.png")

' Dimensions and page ranges may be specified
pdf.RasterizeToImageFiles("C:\image\folder\example_pdf_image_*.jpg", 100, 80)

' Extract all pages as AnyBitmap objects
Dim pdfBitmaps() As AnyBitmap = pdf.ToBitmap()

To convert a PDF document to images, call IronPDF's RasterizeToImageFiles method on a PdfDocument object. A PDF document can be loaded using the PdfDocument.FromFile method or one of the available PDF generation methods for .NET Core.

RasterizeToImageFiles renders each page of the PDF as a rasterized image. The first argument specifies the naming pattern to use for each image. Optional arguments can be used to customize the quality and dimensions for each image. Another option allows the method to convert selected pages from the PDF into images.

Line 24 of the featured code example demonstrates the ToBitMap method. Call this method on any PdfDocument object to quickly convert the PDF into AnyBitmap objects that can be saved to files or manipulated as needed.


using System;
using IronPdf;

namespace PdfToImageExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Path to the PDF document
            string pdfPath = "example.pdf";

            // Load the PDF document
            PdfDocument pdf = PdfDocument.FromFile(pdfPath);

            // Specify the output naming pattern for the images
            string outputPattern = @"output_image_page_{0}.png";

            // Rasterize the PDF to image files, specifying the desired DPI and image format
            pdf.RasterizeToImageFiles(outputPattern, ImageType.Png, 300, 300);

            // Alternatively, convert to bitmap objects
            var bitmapList = pdf.ToBitMap(300, 300);

            Console.WriteLine("PDF has been successfully converted to images.");
        }
    }
}
using System;
using IronPdf;

namespace PdfToImageExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Path to the PDF document
            string pdfPath = "example.pdf";

            // Load the PDF document
            PdfDocument pdf = PdfDocument.FromFile(pdfPath);

            // Specify the output naming pattern for the images
            string outputPattern = @"output_image_page_{0}.png";

            // Rasterize the PDF to image files, specifying the desired DPI and image format
            pdf.RasterizeToImageFiles(outputPattern, ImageType.Png, 300, 300);

            // Alternatively, convert to bitmap objects
            var bitmapList = pdf.ToBitMap(300, 300);

            Console.WriteLine("PDF has been successfully converted to images.");
        }
    }
}
Imports System
Imports IronPdf

Namespace PdfToImageExample
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Path to the PDF document
			Dim pdfPath As String = "example.pdf"

			' Load the PDF document
			Dim pdf As PdfDocument = PdfDocument.FromFile(pdfPath)

			' Specify the output naming pattern for the images
			Dim outputPattern As String = "output_image_page_{0}.png"

			' Rasterize the PDF to image files, specifying the desired DPI and image format
			pdf.RasterizeToImageFiles(outputPattern, ImageType.Png, 300, 300)

			' Alternatively, convert to bitmap objects
			Dim bitmapList = pdf.ToBitMap(300, 300)

			Console.WriteLine("PDF has been successfully converted to images.")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel
  • Using IronPDF: This code snippet illustrates how to convert a PDF document to images using IronPDF. The process involves loading a PDF document using the PdfDocument.FromFile method, then converting each page into an image with the RasterizeToImageFiles method which saves images to disk with a specified naming pattern.
  • Customizing Output: Optional parameters in RasterizeToImageFiles allow you to adjust the image resolution (DPI), dimensions, and format (Png in this case).

ASPX and .NET: Digitally Sign a PDF Digitally Sign a PDF
using IronPdf;
using IronPdf.Signing;

// Cryptographically sign an existing PDF in 1 line of code!
new IronPdf.Signing.PdfSignature("Iron.p12", "123456").SignPdfFile("any.pdf");

/***** Advanced example for more control *****/

// Step 1. Create a PDF
var renderer = new ChromePdfRenderer();
var doc = renderer.RenderHtmlAsPdf("<h1>Testing 2048 bit digital security</h1>");

// Step 2. Create a Signature.
// You may create a .pfx or .p12 PDF signing certificate using Adobe Acrobat Reader.
// Read: https://helpx.adobe.com/acrobat/using/digital-ids.html

var signature = new IronPdf.Signing.PdfSignature("Iron.pfx", "123456")
{
    // Step 3. Optional signing options and a handwritten signature graphic
    SigningContact = "support@ironsoftware.com",
    SigningLocation = "Chicago, USA",
    SigningReason = "To show how to sign a PDF"
};

//Step 3. Sign the PDF with the PdfSignature. Multiple signing certificates may be used
doc.Sign(signature);

//Step 4. The PDF is not signed until saved to file, steam or byte array.
doc.SaveAs("signed.pdf");
Imports IronPdf
Imports IronPdf.Signing

' Cryptographically sign an existing PDF in 1 line of code!
Call (New IronPdf.Signing.PdfSignature("Iron.p12", "123456")).SignPdfFile("any.pdf")

'''*** Advanced example for more control ****

' Step 1. Create a PDF
Dim renderer = New ChromePdfRenderer()
Dim doc = renderer.RenderHtmlAsPdf("<h1>Testing 2048 bit digital security</h1>")

' Step 2. Create a Signature.
' You may create a .pfx or .p12 PDF signing certificate using Adobe Acrobat Reader.
' Read: https://helpx.adobe.com/acrobat/using/digital-ids.html

Dim signature = New IronPdf.Signing.PdfSignature("Iron.pfx", "123456") With {
	.SigningContact = "support@ironsoftware.com",
	.SigningLocation = "Chicago, USA",
	.SigningReason = "To show how to sign a PDF"
}

'Step 3. Sign the PDF with the PdfSignature. Multiple signing certificates may be used
doc.Sign(signature)

'Step 4. The PDF is not signed until saved to file, steam or byte array.
doc.SaveAs("signed.pdf")

<div class="alert alert-info iron-variant-1" role="alert">
  Your business is spending too much on yearly subscriptions for PDF security and compliance. Consider <a href="https://ironsoftware.com/enterprise/securedoc/">IronSecureDoc</a>, which provides solutions for managing SaaS services like digital signing, redaction, encryption, and protection, all for one-time payment. <a href="https://ironsoftware.com/enterprise/securedoc/docs/">Explore IronSecureDoc documentation</a>.
</div>

<div class="alert alert-info iron-variant-1" role="alert">
  Your business is spending too much on yearly subscriptions for PDF security and compliance. Consider <a href="https://ironsoftware.com/enterprise/securedoc/">IronSecureDoc</a>, which provides solutions for managing SaaS services like digital signing, redaction, encryption, and protection, all for one-time payment. <a href="https://ironsoftware.com/enterprise/securedoc/docs/">Explore IronSecureDoc documentation</a>.
</div>
HTML

Digitally signing a PDF document helps ensure the document's integrity by providing a method of adding authentication to the PDF itself. With IronPDF, you have several options when it comes to signing a new or existing PDF file. These include digitally signing the PDF document with a certificate, adding a graphical handwritten version of your signature to the PDF, stamping an image of the certificate on the PDF, or simply creating a signature form field on the PDF to prompt user signing.

Steps to Digitally Signing a PDF with IronPDF

// Instantiate the ChromePdfRenderer to convert HTML to PDF.
var renderer = new ChromePdfRenderer();

// Render PDF from HTML string.
var doc = renderer.RenderHtmlAsPdf("<h1>Testing 2048 bit digital security</h1>");

// Initialize a new PdfSignature object with the required certificate file and password.
var signature = new IronPdf.Signing.PdfSignature("Iron.pfx", "123456")
{
    // Optional: Metadata about this digital signature.
    SigningContact = "support@ironsoftware.com",
    SigningLocation = "Chicago, USA",
    SigningReason = "To show how to sign a PDF"
};

// Apply the digital signature to the PDF document.
doc.Sign(signature);

// Save the signed PDF to the specified path.
doc.SaveAs("signed.pdf");
// Instantiate the ChromePdfRenderer to convert HTML to PDF.
var renderer = new ChromePdfRenderer();

// Render PDF from HTML string.
var doc = renderer.RenderHtmlAsPdf("<h1>Testing 2048 bit digital security</h1>");

// Initialize a new PdfSignature object with the required certificate file and password.
var signature = new IronPdf.Signing.PdfSignature("Iron.pfx", "123456")
{
    // Optional: Metadata about this digital signature.
    SigningContact = "support@ironsoftware.com",
    SigningLocation = "Chicago, USA",
    SigningReason = "To show how to sign a PDF"
};

// Apply the digital signature to the PDF document.
doc.Sign(signature);

// Save the signed PDF to the specified path.
doc.SaveAs("signed.pdf");
' Instantiate the ChromePdfRenderer to convert HTML to PDF.
Dim renderer = New ChromePdfRenderer()

' Render PDF from HTML string.
Dim doc = renderer.RenderHtmlAsPdf("<h1>Testing 2048 bit digital security</h1>")

' Initialize a new PdfSignature object with the required certificate file and password.
Dim signature = New IronPdf.Signing.PdfSignature("Iron.pfx", "123456") With {
	.SigningContact = "support@ironsoftware.com",
	.SigningLocation = "Chicago, USA",
	.SigningReason = "To show how to sign a PDF"
}

' Apply the digital signature to the PDF document.
doc.Sign(signature)

' Save the signed PDF to the specified path.
doc.SaveAs("signed.pdf")
$vbLabelText   $csharpLabel

The first step in this process is to either load in or create the PDF we want to sign. For this example, we create a new PDF document from HTML content. To do this, you first need to create a new ChromePdfRenderer instance. This is IronPDF's powerful rendering engine used to render HTML, CSS, and JavaScript to PDF without losing quality. We then use the RenderHtmlAsPdf method to render our HTML string into a high-quality PDF document ready to be signed. The resulting PDF is stored in the doc variable.

Next, we need to create our signature. For this example, we sign our PDF document with a certificate. PdfSignature represents the digital signature object for signing the PDF, and it requires the path to the .pfx file we want to use for the signature and the password to access this file. We have included three optional properties: SigningContact adds an email or contact information to the signature metadata, SigningLocation represents where the document is signed, and SigningReason provides the reason for the document being signed.

Next, we sign the PDF document with the PdfSignature object we created. By calling the Sign method, we apply the signature to the PDF document in one easy line. Multiple signing certificates can be applied to the PDF document using this method.

Finally, we save the signed PDF document using the SaveAs method, which saves the PDF to the specified file location.

Click here to view the How-to Guide, including examples, sample code, and files >

Contact Iron Software Support

Support from our IronPDF Team

Choosing support with Iron puts Iron's development team as a support team for your project integration. Contact our team directly for questions on the product, integration or licensing.

Ask a Question
ASPX to PDF in .NET

ASPX to PDF conversion directly in .NET Projects

No need to learn new APIs. The Aspx file to pdf converter is Quick and Easy to get to a result in minutes. Supports HTML, Images, Fonts, JS and CSS. IronPDF uses a well tested industry leading Chromium rendering engine to save ASPX pages as PDFs.

See our ASPX to PDF Tutorial
.NET PDF Text Reading Library

Read PDF Text & Extract Images

The IronPDF Aspx to PDF converter also supports PDF text reading and Images extraction. Content can be passed to your .NET applications and databases to archive content from legacy documents and systems into new business process apps.

Get Started with documentation
Editing PDF Documents .NET with IronPDF

Editing PDF Documents in .NET

From merging, to splitting, to editing PDFs, use your development skills to output exactly the right PDF at the right time. IronPDF puts a growing array of feature sets directly into your hands, inside your C# / VB.NET Project.

Clear Documentation
Convert ASPX to PDF. Also Supports HTML, JavaScript, CSS and Images

Supports ASPX and standardized web docs

Use IronPDF to automatically convert your ASPX forms, CSS, and images to PDF documents on the fly. IronPDF will reference and use all your files directly as referenced in your ASPX documents.

Works with ASPX, C#, .NET, VB, MVC, ASP.NET, .NET Core

HTML to PDF Tutorial
Visual Studio Software Extension for PDF Conversion and Editing.

Install into Visual Studio

IronPDF puts PDF generation and manipulation tools in your own hands quickly with fully intellisense support and a Visual Studio installer. Whether installing directly from NuGet with Visual Studio or downloading the DLL, you'll be set up in no time. Just one DLL and no dependencies.

NuGet Install Visual Studio DLL
Supports:
  • .NET Framework 4.0 and above support C#, VB, F#
  • .NET Core 2 and above
  • Microsoft Visual Studio. .NET Development IDE Icon
  • NuGet Installer Support for Visual Studio
  • JetBrains ReSharper C# language assistant compatible
  • Microsoft Azure C# .NET  hosting platform compatible

Commercial Licenses

Free for Development. Licenses for deployment starting at $749.

Project C# + VB.NET Library Licensing

Project

Developer C# + VB.NET Library Licensing

Developer

Organization C# + VB.NET Library Licensing

Organization

Agency C# + VB.NET Library Licensing

Agency

SaaS C# + VB.NET Library Licensing

SaaS

OEM C# + VB.NET Library Licensing

OEM

View Full License Options  

ASP .NET Tutorials including ASPX to PDF

Tutorial + Code Examples ASPX to PDF | ASP.NET Tutorial

C# PDF ASP.NET ASPX

Jacob Müller Software Product Designer @ Team Iron

ASPX to PDF | Tutorial for .NET

Learn how to turn any ASP.NET ASPX page into a PDF document into a PDF instead of HTML using a single line of code in C# or VB.NET…

View Jacob's ASPX-To-PDF Example
Tutorial + Code Examples C# HTML to PDF | C Sharp & VB.NET Tutorial

C# PDF HTML

Jean Ashberg .NET Software Engineer

C# HTML to PDF | C# and VB Tutorial

For many this is the most efficient way to generate PDF files from .NET, because there is no additional API to learn, or complex design system to navigate…

See Jean's HTML-To-PDF Examples
Tutorial + Code Examples VB.NET PDF Creation and Editing | VB.NET & ASP.NET PDF

VB PDF ASP.NET

Veronica Sillar .NET Software Engineer

VB.NET PDF Library | VB ASP.NET Tutorial

Learn how to create and edit PDF documents in VB.NET applications and websites. A free tutorial with code examples.…

View Veronica's Vb.NET PDF Tutorial
Thousands of developers use IronPDF for...

Accounting and Finance Systems

  • # Receipts
  • # Reporting
  • # Invoice Printing
Add PDF Support to ASP.NET Accounting and Finance Systems

Business Digitization

  • # Documentation
  • # Ordering & Labelling
  • # Paper Replacement
C# Business Digitization Use Cases

Enterprise Content Management

  • # Content Production
  • # Document Management
  • # Content Distribution
.NET CMS PDF Support

Data and Reporting Applications

  • # Performance Tracking
  • # Trend Mapping
  • # Reports
C# PDF Reports
Iron Software Enterprise .NET Component Developers

Thousands of corporations, governments, SMEs and developers alike trust Iron software products.

Iron's team have over 10 years experience in the .NET software component market.

IronPDF Customer Icon
IronPDF Customer Icon
IronPDF Customer Icon
IronPDF Customer Icon
IronPDF Customer Icon
IronPDF Customer Icon
IronPDF Customer Icon
IronPDF Customer Icon