How to Create a PDF in C#

This article was translated from English: Does it need improvement?
Translated
View the article in English

Creating PDFs programmatically can often present significant challenges, whether you're adding headers and footers or navigating compatibility issues. Fortunately, IronSoftware simplifies this process by consolidating various PDF creation functions into intuitive and easy-to-understand methods, allowing developers to dive straight into their projects.

With IronPDF, you can seamlessly add shapes, text, images, headers, and footers. You also have the flexibility to set the document’s orientation, size, and metadata and export to various standards such as PDF/UA and PDF/A. Furthermore, integrating IronPDF into existing applications for PDF viewing or programmatically printing documents is straightforward.

In this tutorial, we'll explore each feature and showcase how IronPDF enhances the development experience. It enables you to create readable and reusable code components that can be deployed across any supported environment and platform.

By the end of this article, you will possess a solid understanding of how to create stylistic and unique PDFs tailored to your needs with IronPDF.

To begin installing IronPDF and to follow the tutorial examples outlined in this article, check out this quick installation guide that will assist you in getting everything set up smoothly.

Quickstart: Create Your First PDF with IronPDF

Effortlessly create your first PDF in C# using IronPDF with just a few lines of code. This quick guide shows you how to initialize a PDF document, add content, and save it, ensuring a seamless start for developers new to the library. Dive into PDF creation in seconds and expand your C# application capabilities with ease.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    new IronPdf.PdfDocument(500, 500).SaveAs("output.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer

Table of Contents

NuGet Instalar con NuGet

PM >  Install-Package IronPdf

Echa un vistazo a IronPDF en NuGet para una instalación rápida. Con más de 10 millones de descargas, está transformando el desarrollo de PDF con C#. También puede descargar el DLL o el instalador de Windows.

Design Your Perfect PDF

Create Blank PDF

Creating a blank PDF with IronPDF is intuitive and straightforward, requiring only a couple of lines of code. We first initiate a new PdfDocument class, provide it with dimensions, and call the SaveAs method to save it.

:path=/static-assets/pdf/content-code-examples/how-to/create-new-pdfs.cs
using IronPdf;

PdfDocument pdf = new PdfDocument(270, 270);

pdf.SaveAs("blankPage.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Comience a usar IronPDF en su proyecto hoy con una prueba gratuita.

Primer Paso:
green arrow pointer

Add Headers & Footers

Add headers and footers at the top or bottom of your PDF easily using IronPDF. IronPDF allows you to add two types of headers and footers. TextHeaderFooter is ideal for scenarios where only text is required, such as showcasing the page number with string interpolation, e.g.,"{page} of {total-pages}". At the same time, HtmlHeaderFooter is a more advanced variation that lets developers customize the HTML content they place.

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

By setting the HtmlHeaderFooter object, we can customize where the text appears by wrapping the page numbers in <center> tags and adding an image asset to ensure the document is unique.

:path=/static-assets/pdf/content-code-examples/how-to/headers-and-footers-htmlheaderfooter.cs
using IronPdf;

string headerHtml = @"
    <html>
    <head>
        <link rel='stylesheet' href='style.css'>
    </head>
    <body>
        <h1>This is a header!</h1>
    </body>
    </html>";

string footerHtml = @"
    <html>
    <head>
        <link rel='stylesheet' href='style.css'>
    </head>
    <body>
        <h1>This is a footer!</h1>
    </body>
    </html>";

// Instantiate renderer and create PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");

// Create header and footer
HtmlHeaderFooter htmlHeader = new HtmlHeaderFooter
{
    HtmlFragment = headerHtml,
    LoadStylesAndCSSFromMainHtmlDocument = true,
};

HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter
{
    HtmlFragment = footerHtml,
    LoadStylesAndCSSFromMainHtmlDocument = true,
};

// Add to PDF
pdf.AddHtmlHeaders(htmlHeader);
pdf.AddHtmlFooters(htmlFooter);
Imports IronPdf

Private headerHtml As String = "
    <html>
    <head>
        <link rel='stylesheet' href='style.css'>
    </head>
    <body>
        <h1>This is a header!</h1>
    </body>
    </html>"

Private footerHtml As String = "
    <html>
    <head>
        <link rel='stylesheet' href='style.css'>
    </head>
    <body>
        <h1>This is a footer!</h1>
    </body>
    </html>"

' Instantiate renderer and create PDF
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")

' Create header and footer
Private htmlHeader As New HtmlHeaderFooter With {
	.HtmlFragment = headerHtml,
	.LoadStylesAndCSSFromMainHtmlDocument = True
}

Private htmlFooter As New HtmlHeaderFooter With {
	.HtmlFragment = footerHtml,
	.LoadStylesAndCSSFromMainHtmlDocument = True
}

' Add to PDF
pdf.AddHtmlHeaders(htmlHeader)
pdf.AddHtmlFooters(htmlFooter)
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

The example below uses TextHeaderFooter with placeholder values to denote the page numbers, URLs, and date.

:path=/static-assets/pdf/content-code-examples/how-to/headers-and-footers-add-textheaderfooter.cs
using IronPdf;

// Instantiate renderer and create PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");

// Create text header
TextHeaderFooter textHeader = new TextHeaderFooter
{
    CenterText = "This is the header!",
};

// Create text footer
TextHeaderFooter textFooter = new TextHeaderFooter
{
    CenterText = "This is the footer!",
};

// Add text header and footer to the PDF
pdf.AddTextHeaders(textHeader);
pdf.AddTextFooters(textFooter);

pdf.SaveAs("addTextHeaderFooter.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Along with the fields shown above, we also have the following placeholder values that are available and will be replaced when rendering:{page}, {total-pages}, {url}, {date}, {time}, {html-title}, {pdf-title}.

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Add Page Numbers

Similar to the example above, we can use the TextHeaderFooter or HtmlHeaderFooter to display the page number by placing placeholder values in the header or footer, which will be shown when the document is rendered.

:path=/static-assets/pdf/content-code-examples/how-to/page-numbers-basic.cs
using IronPdf;

// Create text header
TextHeaderFooter textHeader = new TextHeaderFooter()
{
    CenterText = "{page} of {total-pages}"
};

// Create html footer
HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter()
{
    HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"
};

// Render a new PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");

// Add header and footer
pdf.AddTextHeaders(textHeader);
pdf.AddHtmlFooters(htmlFooter);

pdf.SaveAs("pdfWithPageNumber.pdf");
Imports IronPdf

' Create text header
Private textHeader As New TextHeaderFooter() With {.CenterText = "{page} of {total-pages}"}

' Create html footer
Private htmlFooter As New HtmlHeaderFooter() With {.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"}

' Render a new PDF
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")

' Add header and footer
pdf.AddTextHeaders(textHeader)
pdf.AddHtmlFooters(htmlFooter)

pdf.SaveAs("pdfWithPageNumber.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Embed Images with DataURIs

There are times when relying on a directory of assets is too slow and ineffective; as such, we can embed images with Data URIs as a workaround. Here's a brief code snippet on how to do it.

:path=/static-assets/pdf/content-code-examples/how-to/datauris-image.cs
using IronPdf;
using System;

// Read byte from image file
var pngBinaryData = System.IO.File.ReadAllBytes("My_image.png");

// Convert bytes to base64
var ImgDataURI = @"data:image/png;base64," + Convert.ToBase64String(pngBinaryData);

// Import base64 to img tag
var ImgHtml = $"<img src='{ImgDataURI}'>";

ChromePdfRenderer Renderer = new ChromePdfRenderer();

// Render the HTML string
var pdf = Renderer.RenderHtmlAsPdf(ImgHtml);

pdf.SaveAs("datauri_example.pdf");
Imports IronPdf
Imports System

' Read byte from image file
Private pngBinaryData = System.IO.File.ReadAllBytes("My_image.png")

' Convert bytes to base64
Private ImgDataURI = "data:image/png;base64," & Convert.ToBase64String(pngBinaryData)

' Import base64 to img tag
Private ImgHtml = $"<img src='{ImgDataURI}'>"

Private Renderer As New ChromePdfRenderer()

' Render the HTML string
Private pdf = Renderer.RenderHtmlAsPdf(ImgHtml)

pdf.SaveAs("datauri_example.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

OpenAI for PDF

IronPDF improves efficiency and scalability by supporting the OpenAI model for quick summarization, querying, and memorization, all utilizing Microsoft Semantic Kernel. Here's a brief code snippet on how to use OpenAI to quickly summarize the contents of a PDF.

:path=/static-assets/pdf/content-code-examples/how-to/openai-summarize.cs
using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Microsoft.SemanticKernel.Memory;
using System;
using System.Threading.Tasks;

// Setup OpenAI
var azureEndpoint = "<<enter your azure endpoint here>>";
var apiKey = "<<enter your azure API key here>>";
var builder = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration("oaiembed", azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion("oaichat", azureEndpoint, apiKey);
var kernel = builder.Build();

// Setup Memory
var memory_builder = new MemoryBuilder()
    // optionally use new ChromaMemoryStore("http://127.0.0.1:8000") (see https://github.com/microsoft/semantic-kernel/blob/main/dotnet/notebooks/09-memory-with-chroma.ipynb)
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration("oaiembed", azureEndpoint, apiKey);
var memory = memory_builder.Build();

// Initialize IronAI
IronDocumentAI.Initialize(kernel, memory);

License.LicenseKey = "<<enter your IronPdf license key here";

// Import PDF document
PdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");

// Summarize the document
Console.WriteLine("Please wait while I summarize the document...");
string summary = await pdf.Summarize(); // optionally pass AI instance or use AI instance directly
Console.WriteLine($"Document summary: {summary}\n\n");
Imports Microsoft.VisualBasic
Imports IronPdf
Imports IronPdf.AI
Imports Microsoft.SemanticKernel
Imports Microsoft.SemanticKernel.Connectors.OpenAI
Imports Microsoft.SemanticKernel.Memory
Imports System
Imports System.Threading.Tasks

' Setup OpenAI
Private azureEndpoint = "<<enter your azure endpoint here>>"
Private apiKey = "<<enter your azure API key here>>"
Private builder = Kernel.CreateBuilder().AddAzureOpenAITextEmbeddingGeneration("oaiembed", azureEndpoint, apiKey).AddAzureOpenAIChatCompletion("oaichat", azureEndpoint, apiKey)
Private kernel = builder.Build()

' Setup Memory
Private memory_builder = (New MemoryBuilder()).WithMemoryStore(New VolatileMemoryStore()).WithAzureOpenAITextEmbeddingGeneration("oaiembed", azureEndpoint, apiKey)
Private memory = memory_builder.Build()

' Initialize IronAI
IronDocumentAI.Initialize(kernel, memory)

License.LicenseKey = "<<enter your IronPdf license key here"

' Import PDF document
Dim pdf As PdfDocument = PdfDocument.FromFile("wikipedia.pdf")

' Summarize the document
Console.WriteLine("Please wait while I summarize the document...")
Dim summary As String = Await pdf.Summarize() ' optionally pass AI instance or use AI instance directly
Console.WriteLine($"Document summary: {summary}" & vbLf & vbLf)
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Full PDF Customization

Orientation & Rotation

Orientation

The PaperOrientation property from the RenderingOptions class allows you to dictate how the orientation of the PDF renders. In this example, we set it to PdfPaperOrientation.Landscape to render the PDF orientation to landscape mode.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-create-pdf-complete-1.cs

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Change paper orientation
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape;

PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");

pdf.SaveAs("landscape.pdf");
Dim renderer As New ChromePdfRenderer()

' Change paper orientation
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape

Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")

pdf.SaveAs("landscape.pdf")
$vbLabelText   $csharpLabel

Rotation

To set the rotation of a PDF page, we can use the SetPageRotation method, along with a PdfPageRotation enum as input, to rotate the page.

:path=/static-assets/pdf/content-code-examples/how-to/page-orientation-rotation-set-rotation.cs
using IronPdf;
using IronPdf.Rendering;
using System.Collections.Generic;

PdfDocument pdf = PdfDocument.FromFile("landscape.pdf");

// Set all pages
pdf.SetAllPageRotations(PdfPageRotation.Clockwise90);

// Set a single page
pdf.SetPageRotation(1, PdfPageRotation.Clockwise180);

// Set multiple pages
List<int> selectedPages = new List<int>() { 0, 3 };
pdf.SetPageRotations(selectedPages, PdfPageRotation.Clockwise270);

pdf.SaveAs("rotatedLandscape.pdf");
Imports IronPdf
Imports IronPdf.Rendering
Imports System.Collections.Generic

Private pdf As PdfDocument = PdfDocument.FromFile("landscape.pdf")

' Set all pages
pdf.SetAllPageRotations(PdfPageRotation.Clockwise90)

' Set a single page
pdf.SetPageRotation(1, PdfPageRotation.Clockwise180)

' Set multiple pages
Dim selectedPages As New List(Of Integer)() From {0, 3}
pdf.SetPageRotations(selectedPages, PdfPageRotation.Clockwise270)

pdf.SaveAs("rotatedLandscape.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of setting the orientation and rotation of the PDF and to explore its additional functionality, please refer to our comprehensive how-to guide.

Custom Paper Size

Set the dimensions of the PDF by setting the width and height using the method SetCustomPaperSizeinCentimeters. IronPDF also supports setting to standardized sizes such as A4 by setting the PaperSize property to a list of available enums.

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Custom Paper Size in Cm

:path=/static-assets/pdf/content-code-examples/how-to/custom-paper-size-cm.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Set custom paper size in cm
renderer.RenderingOptions.SetCustomPaperSizeinCentimeters(15, 15);

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Custom Paper Size</h1>");

pdf.SaveAs("customPaperSize.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

' Set custom paper size in cm
renderer.RenderingOptions.SetCustomPaperSizeinCentimeters(15, 15)

Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Custom Paper Size</h1>")

pdf.SaveAs("customPaperSize.pdf")
$vbLabelText   $csharpLabel

Standard Paper Size

In this example, we also set the property PaperSize to the enum of PdfPaperSize.A4.

:path=/static-assets/pdf/content-code-examples/how-to/custom-paper-size-standard-paper-size.cs
using IronPdf;
using IronPdf.Rendering;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Set paper size to A4
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Standard Paper Size</h1>");

pdf.SaveAs("standardPaperSize.pdf");
Imports IronPdf
Imports IronPdf.Rendering

Private renderer As New ChromePdfRenderer()

' Set paper size to A4
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4

Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Standard Paper Size</h1>")

pdf.SaveAs("standardPaperSize.pdf")
$vbLabelText   $csharpLabel

For a list of supported standardized sizes, please click here.

Standards Compliance

Export PDF/A Format Docs in C#

Create and export PDFs compliant with PDF/UA standards using the SaveAsPdfUA method.

:path=/static-assets/pdf/content-code-examples/how-to/pdfa-fromfile.cs
using IronPdf;

// Create a PdfDocument object or open any PDF File
PdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");

// Use the SaveAsPdfA method to save to file
pdf.SaveAsPdfA("pdf-a3-wikipedia.pdf", PdfAVersions.PdfA3b);
Imports IronPdf

' Create a PdfDocument object or open any PDF File
Private pdf As PdfDocument = PdfDocument.FromFile("wikipedia.pdf")

' Use the SaveAsPdfA method to save to file
pdf.SaveAsPdfA("pdf-a3-wikipedia.pdf", PdfAVersions.PdfA3b)
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Export PDF/UA Format Docs in C#

To convert PDF to PDF/A in C#, we can use the IronPDf library as well, it supports the latest standards of PDF/A, ensuring the integrity of your files; similar to the example above, we call SaveAsPdfA to save the PDF in PDF/A standards.

:path=/static-assets/pdf/content-code-examples/how-to/pdfua-fromfile.cs
using IronPdf;

// Open PDF File
PdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");

// Export as PDF/UA compliance PDF
pdf.SaveAsPdfUA("pdf-ua-wikipedia.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

In this example, we save the PDF to the PDF/A-3 variation, using the enum for PdfAVersions.

For a complete list of supported PDF/A versions, please click here.

Conclusion

The brief examples shared above showcase the impressive capabilities and standout features you can unlock while creating PDFs using IronPDF.

If you want to request a feature or have general questions about IronPDF or licensing, please contact our support team. We will be more than happy to assist you.

Preguntas Frecuentes

¿Cómo puedo crear un documento PDF en C# usando IronPDF?

Puede crear un documento PDF en C# usando IronPDF al inicializar un nuevo objeto de documento PDF y agregar contenido como texto, imágenes y tablas antes de guardar el archivo.

¿Qué funcionalidades ofrece IronPDF para editar PDFs?

IronPDF proporciona funcionalidades para editar PDFs, incluyendo la adición de marcas de agua, encabezados, pies de página y fondos. También admite la fusión, división y compresión de PDFs.

¿Puedo agregar formularios a un documento PDF usando IronPDF?

Sí, IronPDF le permite agregar formularios interactivos a sus documentos PDF. Puede crear campos de formulario como entradas de texto, casillas de verificación y botones de opción.

¿Es posible proteger un PDF con una contraseña usando IronPDF?

Absolutamente, puede proteger sus documentos PDF con contraseñas usando IronPDF. Le permite establecer contraseñas de usuario y de propietario para controlar el acceso y los permisos.

¿Cómo aplico una marca de agua a un PDF usando IronPDF?

Para aplicar una marca de agua usando IronPDF, puede utilizar las funciones de edición de PDF para superponer texto o una imagen como marca de agua en cada página de su documento PDF.

¿Puede IronPDF comprimir archivos PDF para reducir su tamaño?

Sí, IronPDF incluye características para comprimir archivos PDF, ayudando a reducir el tamaño del archivo mientras mantiene la calidad, lo cual es útil para almacenamiento y compartición.

¿Cómo puedo agregar encabezados y pies de página a mi PDF usando IronPDF?

Puede agregar encabezados y pies de página a sus documentos PDF con IronPDF especificando el texto o las imágenes que desea incluir en la parte superior o inferior de cada página.

¿IronPDF admite la personalización del fondo para las páginas PDF?

IronPDF admite la personalización del fondo, permitiéndole establecer imágenes o colores como fondo para sus páginas PDF, mejorando el diseño del documento.

¿Puedo convertir HTML a PDF usando IronPDF?

Sí, IronPDF proporciona una función para convertir HTML a PDF. Puede renderizar contenido HTML complejo, incluyendo CSS y JavaScript, en un documento PDF.

¿Cuáles son los requisitos del sistema para usar IronPDF en un proyecto C#?

IronPDF es compatible con .NET Framework y .NET Core. Requiere un sistema operativo Windows, macOS o Linux, y se integra sin problemas en proyectos C# usando Visual Studio.

¿IronPDF es totalmente compatible con .NET 10?

Sí, IronPDF es totalmente compatible con .NET 10. Funciona de inmediato con el entorno de ejecución más reciente, aprovechando las mejoras de rendimiento y del lenguaje de .NET 10. Es compatible con las versiones 10, 9, 8, 7, 6 y 5 de .NET, .NET Standard 2.0+ y .NET Framework 4.6.2+ en entornos Windows, macOS, Linux y contenedores.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 16,133,208 | Versión: 2025.11 recién lanzado