# How to Create a PDF in C#
Creating PDFs programmatically can often present significant challenges, whether you're adding headers and footers or navigating compatibility issues. Fortunately, Iron Software 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 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](https://ironpdf.com/docs/) that will assist you in getting everything set up smoothly.
*as-heading:2(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 smooth start for developers new to the library. Dive into PDF creation in seconds and expand your C# application capabilities with ease.
```cs
:title=Instant PDF Creation with IronPDF
new IronPdf.PdfDocument(500, 500).SaveAs("output.pdf");
```
*as-heading:2(Table of Contents)*
- **Design Perfect PDFs**
- [Create Blank PDF](#anchor-create-blank-pdf)
- [Add Headers & Footers](#anchor-add-headers-footers)
- [Add Page Numbers](#anchor-add-page-numbers)
- [Embed Images with DataURIs](#anchor-embed-images-with-datauris)
- [Embed Images from Azure Blob Storage](#anchor-embed-images-with-azure-blob-storage)
- [OpenAI for PDF](#anchor-openai-for-pdf)
- **Full PDF Customization Easy**
- [Orientation & Rotation](#anchor-orientation-rotation)
- [Custom Paper Size](#anchor-custom-paper-size)
- **Standards Compliance**
- [Export PDF/A Format Docs in C#](#anchor-export-pdf-a-format-docs-in-c-num)
- [Export PDF/UA Format Docs in C#](#anchor-export-pdf-ua-format-docs-in-c-num)
## 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. `TextHeaderFooter`
```cs
using IronPdf;
PdfDocument pdf = new PdfDocument(270, 270);
pdf.SaveAs("blankPage.pdf");
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/create-new-pdfs/).
### 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}"` `HtmlHeaderFooter`. 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](https://ironpdf.com/how-to/headers-and-footers/).
#### HTML Header and Footer
By setting the `HtmlHeaderFooter` object `<center>`, we can customize where the text appears by wrapping the page numbers in `span` tags and adding an image asset to ensure the document is unique.
```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);
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/headers-and-footers/#add-html-header-footer-example).
#### Text Header and Footer
The example below uses `TextHeaderFooter` with placeholder values to denote the page numbers, URLs, and date.
```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");
```
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](https://ironpdf.com/how-to/headers-and-footers/#add-a-text-header-footer-example).
### 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.
```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");
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/page-numbers/).
### 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.
```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");
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/datauris/).
### 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.
```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");
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/openai/).
## 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.
```csharp
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");
```
#### 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.
```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");
```
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](https://ironpdf.com/how-to/page-orientation-rotation/).
### Custom Paper Size
Set the dimensions of the PDF by setting the `width` and the `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](https://ironpdf.com/how-to/custom-paper-size/).
#### Custom Paper Size in 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");
```
#### Standard Paper Size
In this example, we also set the property `PaperSize` to the enum of `PdfPaperSize.A4`.
```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");
```
For a list of supported standardized sizes, please click [here](https://ironpdf.com/object-reference/api/IronPdf.Rendering.PdfPaperSize.html).
## Standards Compliance
### Export PDF/A Format Docs in C#
Create and export PDFs compliant with PDF/UA standards using the `SaveAsPdfUA` method.
```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);
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/pdfua/).
### 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.
```cs
using IronPdf;
// Open PDF File
PdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");
// Export as PDF/UA. Pass the document's natural language so assistive
// technologies announce the correct pronunciation.
pdf.SaveAsPdfUA("pdf-ua-wikipedia.pdf", NaturalLanguage: NaturalLanguages.English);
```
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](https://ironpdf.com/object-reference/api/IronPdf.PdfAVersions.html).
## 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](/troubleshooting/engineering-request-pdf/). We will be more than happy to assist you.
Creating PDFs programmatically can often present significant challenges, whether you're adding headers and footers or navigating compatibility issues. Fortunately, Iron Software 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 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 smooth start for developers new to the library. Dive into PDF creation in seconds and expand your C# application capabilities with ease.
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. TextHeaderFooter
using IronPdf;PdfDocument pdf = new PdfDocument(270, 270);pdf.SaveAs("blankPage.pdf");
using IronPdf;
PdfDocument pdf = new PdfDocument(270, 270);
pdf.SaveAs("blankPage.pdf");
ImportsIronPdfDim pdf As New PdfDocument(270, 270)pdf.SaveAs("blankPage.pdf")
Imports IronPdf
Dim pdf As New PdfDocument(270, 270)
pdf.SaveAs("blankPage.pdf")
For 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}"HtmlHeaderFooter. 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 <center>, we can customize where the text appears by wrapping the page numbers in span tags and adding an image asset to ensure the document is unique.
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 PDFChromePdfRenderer renderer = new ChromePdfRenderer();PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");// Create header and footerHtmlHeaderFooter htmlHeader = new HtmlHeaderFooter{HtmlFragment = headerHtml,LoadStylesAndCSSFromMainHtmlDocument = true,};HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter{HtmlFragment = footerHtml,LoadStylesAndCSSFromMainHtmlDocument = true,};// Add to PDFpdf.AddHtmlHeaders(htmlHeader);pdf.AddHtmlFooters(htmlFooter);
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);
ImportsIronPdfPrivate headerHtml AsString = " <html> <head> <link rel='stylesheet' href='style.css'> </head> <body> <h1>This is a header!</h1> </body> </html>"Private footerHtml AsString = " <html> <head> <link rel='stylesheet' href='style.css'> </head> <body> <h1>This is a footer!</h1> </body> </html>"' Instantiate renderer and create PDFPrivate renderer As New ChromePdfRenderer()Private pdf AsPdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")' Create header and footerPrivate htmlHeader As New HtmlHeaderFooterWith { .HtmlFragment = headerHtml, .LoadStylesAndCSSFromMainHtmlDocument = True}Private htmlFooter As New HtmlHeaderFooterWith { .HtmlFragment = footerHtml, .LoadStylesAndCSSFromMainHtmlDocument = True}' Add to PDFpdf.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.
using IronPdf;// Instantiate renderer and create PDFChromePdfRenderer renderer = new ChromePdfRenderer();PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");// Create text headerTextHeaderFooter textHeader = new TextHeaderFooter{CenterText = "This is the header!",};// Create text footerTextHeaderFooter textFooter = new TextHeaderFooter{CenterText = "This is the footer!",};// Add text header and footer to the PDFpdf.AddTextHeaders(textHeader);pdf.AddTextFooters(textFooter);pdf.SaveAs("addTextHeaderFooter.pdf");
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");
ImportsIronPdf' Instantiate renderer and create PDFDim renderer As New ChromePdfRenderer()Dim pdf AsPdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")' Create text headerDim textHeader As New TextHeaderFooterWith { .CenterText = "This is the header!"}' Create text footerDim textFooter As New TextHeaderFooterWith { .CenterText = "This is the footer!"}' Add text header and footer to the PDFpdf.AddTextHeaders(textHeader)pdf.AddTextFooters(textFooter)pdf.SaveAs("addTextHeaderFooter.pdf")
Imports IronPdf
' Instantiate renderer and create PDF
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")
' Create text header
Dim textHeader As New TextHeaderFooter With {
.CenterText = "This is the header!"
}
' Create text footer
Dim textFooter As New TextHeaderFooter With {
.CenterText = "This is the footer!"
}
' Add text header and footer to the PDF
pdf.AddTextHeaders(textHeader)
pdf.AddTextFooters(textFooter)
pdf.SaveAs("addTextHeaderFooter.pdf")
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.
using IronPdf;// Create text headerTextHeaderFooter textHeader = new TextHeaderFooter(){CenterText = "{page} of {total-pages}"};// Create html footerHtmlHeaderFooter htmlFooter = new HtmlHeaderFooter(){HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"};// Render a new PDFChromePdfRenderer renderer = new ChromePdfRenderer();PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");// Add header and footerpdf.AddTextHeaders(textHeader);pdf.AddHtmlFooters(htmlFooter);pdf.SaveAs("pdfWithPageNumber.pdf");
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");
ImportsIronPdf' Create text headerPrivate textHeader As New TextHeaderFooter() With {.CenterText = "{page} of {total-pages}"}' Create html footerPrivate htmlFooter As New HtmlHeaderFooter() With {.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"}' Render a new PDFPrivate renderer As New ChromePdfRenderer()Private pdf AsPdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")' Add header and footerpdf.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.
using IronPdf;using System;// Read byte from image filevar pngBinaryData = System.IO.File.ReadAllBytes("My_image.png");// Convert bytes to base64varImgDataURI = @"data:image/png;base64," + Convert.ToBase64String(pngBinaryData);// Import base64 to img tagvarImgHtml = $"<img src='{ImgDataURI}'>";ChromePdfRendererRenderer = new ChromePdfRenderer();// Render the HTML stringvar pdf = Renderer.RenderHtmlAsPdf(ImgHtml);pdf.SaveAs("datauri_example.pdf");
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");
ImportsIronPdfImportsSystem' Read byte from image filePrivate pngBinaryData = System.IO.File.ReadAllBytes("My_image.png")' Convert bytes to base64PrivateImgDataURI = "data:image/png;base64," & Convert.ToBase64String(pngBinaryData)' Import base64 to img tagPrivateImgHtml = $"<img src='{ImgDataURI}'>"PrivateRendererAs New ChromePdfRenderer()' Render the HTML stringPrivate 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.
using IronPdf;using IronPdf.AI;using Microsoft.SemanticKernel;using Microsoft.SemanticKernel.Connectors.OpenAI;using Microsoft.SemanticKernel.Memory;using System;using System.Threading.Tasks;// Setup OpenAIvar 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 Memoryvar 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 IronAIIronDocumentAI.Initialize(kernel, memory);License.LicenseKey = "<<enter your IronPdf license key here";// Import PDF documentPdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");// Summarize the documentConsole.WriteLine("Please wait while I summarize the document...");string summary = await pdf.Summarize(); // optionally pass AI instance or use AI instance directlyConsole.WriteLine($"Document summary: {summary}\n\n");
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");
ImportsMicrosoft.VisualBasicImportsIronPdfImportsIronPdf.AIImportsMicrosoft.SemanticKernelImportsMicrosoft.SemanticKernel.Connectors.OpenAIImportsMicrosoft.SemanticKernel.MemoryImportsSystemImportsSystem.Threading.Tasks' Setup OpenAIPrivate 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 MemoryPrivate memory_builder = (New MemoryBuilder()).WithMemoryStore(New VolatileMemoryStore()).WithAzureOpenAITextEmbeddingGeneration("oaiembed", azureEndpoint, apiKey)Private memory = memory_builder.Build()' Initialize IronAIIronDocumentAI.Initialize(kernel, memory)License.LicenseKey = "<<enter your IronPdf license key here"' Import PDF documentDim pdf AsPdfDocument = PdfDocument.FromFile("wikipedia.pdf")' Summarize the documentConsole.WriteLine("Please wait while I summarize the document...")Dim summary AsString = Await pdf.Summarize() ' optionally pass AI instance or use AI instance directlyConsole.WriteLine($"Document summary: {summary}" & vbLf & vbLf)
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.
ChromePdfRenderer renderer = new ChromePdfRenderer();// Change paper orientationrenderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape;PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");pdf.SaveAs("landscape.pdf");
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 orientationrenderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.LandscapeDim pdf AsPdfDocument = 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.
using IronPdf;using IronPdf.Rendering;using System.Collections.Generic;PdfDocument pdf = PdfDocument.FromFile("landscape.pdf");// Set all pagespdf.SetAllPageRotations(PdfPageRotation.Clockwise90);// Set a single pagepdf.SetPageRotation(1, PdfPageRotation.Clockwise180);// Set multiple pagesList<int> selectedPages = new List<int>() { 0, 3 };pdf.SetPageRotations(selectedPages, PdfPageRotation.Clockwise270);pdf.SaveAs("rotatedLandscape.pdf");
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");
ImportsIronPdfImportsIronPdf.RenderingImportsSystem.Collections.GenericPrivate pdf AsPdfDocument = PdfDocument.FromFile("landscape.pdf")' Set all pagespdf.SetAllPageRotations(PdfPageRotation.Clockwise90)' Set a single pagepdf.SetPageRotation(1, PdfPageRotation.Clockwise180)' Set multiple pagesDim selectedPages As New List(OfInteger)() From {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 the 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
using IronPdf;ChromePdfRenderer renderer = new ChromePdfRenderer();// Set custom paper size in cmrenderer.RenderingOptions.SetCustomPaperSizeinCentimeters(15, 15);PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Custom Paper Size</h1>");pdf.SaveAs("customPaperSize.pdf");
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");
ImportsIronPdfPrivate renderer As New ChromePdfRenderer()' Set custom paper size in cmrenderer.RenderingOptions.SetCustomPaperSizeinCentimeters(15, 15)Dim pdf AsPdfDocument = 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.
using IronPdf;using IronPdf.Rendering;ChromePdfRenderer renderer = new ChromePdfRenderer();// Set paper size to A4renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Standard Paper Size</h1>");pdf.SaveAs("standardPaperSize.pdf");
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");
ImportsIronPdfImportsIronPdf.RenderingPrivate renderer As New ChromePdfRenderer()' Set paper size to A4renderer.RenderingOptions.PaperSize = PdfPaperSize.A4Dim pdf AsPdfDocument = 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.
My favorite library of this kind is IronPDF. It allows for fast and efficient manipulation of PDF files. It also has many valuable features, like exporting to PDF/A format and digitally signing PDF documents.
IronOCR means we can save $40,000 annually from manual processing, while enhancing productivity and freeing up resources for high-impact tasks. I would highly recommend it.
Create and export PDFs compliant with PDF/UA standards using the SaveAsPdfUA method.
using IronPdf;// Create a PdfDocument object or open any PDF FilePdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");// Use the SaveAsPdfA method to save to filepdf.SaveAsPdfA("pdf-a3-wikipedia.pdf", PdfAVersions.PdfA3b);
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);
ImportsIronPdf' Create a PdfDocument object or open any PDF FileDim pdf AsPdfDocument = PdfDocument.FromFile("wikipedia.pdf")' Use the SaveAsPdfA method to save to filepdf.SaveAsPdfA("pdf-a3-wikipedia.pdf", PdfAVersions.PdfA3b)
Imports IronPdf
' Create a PdfDocument object or open any PDF File
Dim 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.
using IronPdf;// Open PDF FilePdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");// Export as PDF/UA. Pass the document's natural language so assistive// technologies announce the correct pronunciation.pdf.SaveAsPdfUA("pdf-ua-wikipedia.pdf", NaturalLanguage: NaturalLanguages.English);
using IronPdf;
// Open PDF File
PdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");
// Export as PDF/UA. Pass the document's natural language so assistive
// technologies announce the correct pronunciation.
pdf.SaveAsPdfUA("pdf-ua-wikipedia.pdf", NaturalLanguage: NaturalLanguages.English);
C#
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
What is IronPDF used for?
IronPDF is used for creating, editing, and managing PDF files in C#. It provides features like adding headers, footers, shapes, text, images, and setting the document's metadata, allowing straightforward integration into existing applications.
How can I create a PDF with a specific page size using IronPDF?
With IronPDF, you can set a custom paper size using the `SetCustomPaperSizeinCentimeters` method or choose from standardized sizes like A4 by setting the `PaperSize` property to an available enum.
Can IronPDF handle different PDF file standards?
Yes, IronPDF supports exporting documents to various PDF standards such as PDF/UA and PDF/A, ensuring compliance with accessibility and archival requirements.
How can I add HTML-based headers and footers with IronPDF?
IronPDF allows you to use the `HtmlHeaderFooter` class to add customizable HTML content to headers and footers. This enables the inclusion of complex designs and media, including text and images.
What are the options for adding page numbers in a PDF using IronPDF?
IronPDF offers `TextHeaderFooter` and `HtmlHeaderFooter` classes that allow you to incorporate placeholder values for page numbers within headers or footers, which are rendered appropriately in the PDF.
How can IronPDF help in embedding images within a PDF?
IronPDF supports embedding images directly into PDFs using Data URIs. This allows images to be included without relying on external asset directories, improving performance and portability.
Does IronPDF support document summarization or AI-based operations?
Yes, IronPDF supports operations like quick summarization, querying, and memorization by integrating with Microsoft Semantic Kernel and OpenAI models, enhancing efficiency and scalability.
Can I rotate pages or set document orientation using IronPDF?
IronPDF allows you to set page rotation using the `SetPageRotation` method with `PdfPageRotation` enums. Additionally, document orientation can be configured via the `RenderingOptions.PaperOrientation` property.
How can I start creating a PDF with IronPDF?
To get started with IronPDF, you only need a few lines of code to initialize a new PDF document using the `PdfDocument` class and use the `SaveAs` method to create a PDF file.
Where can I find more detailed guides and documentation for IronPDF?
Guides and documentation for IronPDF can be found on their official website, with links embedded within tutorials to guide users through various features and implementations.
Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.