How to Create a PDF in C#
Introduction
How to Create PDFs in C# with IronPDF
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.
Get Started
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.
Table of Contents
- Design Perfect PDFs
- Full PDF Customization Easy
- Standards Compliance
Start using IronPDF in your project today with a free trial.
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.csusing IronPdf;
PdfDocument pdf = new PdfDocument(270, 270);
pdf.SaveAs("blankPage.pdf");IRON VB CONVERTER ERROR developers@ironsoftware.comFor a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.
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.
HTML Header and Footer
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.csusing 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)For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.
Text Header and Footer
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.csusing 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.comAlong 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.csusing 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")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.csusing 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")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.csusing 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)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")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.csusing 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")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.csusing 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")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.csusing 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")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.csusing 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)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.csusing 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.comFor 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.
Frequently Asked Questions
How can I create a PDF document in C# using IronPDF?
You can create a PDF document in C# using IronPDF by initializing a new PDF document object and adding content such as text, images, and tables to it before saving the file.
What functionalities does IronPDF offer for editing PDFs?
IronPDF provides functionalities for editing PDFs, including adding watermarks, headers, footers, and backgrounds. It also supports merging, splitting, and compressing PDFs.
Can I add forms to a PDF document using IronPDF?
Yes, IronPDF allows you to add interactive forms to your PDF documents. You can create form fields such as text inputs, checkboxes, and radio buttons.
Is it possible to secure a PDF with a password using IronPDF?
Absolutely, you can secure your PDF documents with passwords using IronPDF. It allows you to set user and owner passwords to control access and permissions.
How do I apply a watermark to a PDF using IronPDF?
To apply a watermark using IronPDF, you can use the PDF editing functions to overlay text or an image as a watermark on each page of your PDF document.
Can IronPDF compress PDF files to reduce their size?
Yes, IronPDF includes features for compressing PDF files, helping to reduce file size while maintaining quality, which is useful for storage and sharing.
How can I add headers and footers to my PDF using IronPDF?
You can add headers and footers to your PDF documents with IronPDF by specifying the text or images you want to include on the top or bottom of each page.
Does IronPDF support background customization for PDF pages?
IronPDF supports background customization, allowing you to set images or colors as the background for your PDF pages, enhancing the document's design.
Can I convert HTML to PDF using IronPDF?
Yes, IronPDF provides a feature to convert HTML to PDF. You can render complex HTML content, including CSS and JavaScript, into a PDF document.
What are the system requirements for using IronPDF in a C# project?
IronPDF is compatible with .NET Framework and .NET Core. It requires a Windows, macOS, or Linux operating system, and it integrates seamlessly into C# projects using Visual Studio.




