HTML to PDF Conversion in .NET Core (Updated 2024 Tutorial)
.NET Core PDF Generator
Creating .NET Core PDF files is a cumbersome task. Working with PDFs in ASP.NET MVC projects, as well as converting MVC views, HTML files, and online web pages to PDF can be challenging. This tutorial works with the IronPDF tool to tackle these problems, providing instructional guidelines for many of your PDF .NET needs.
IronPDF also supports debugging of your HTML with Chrome for Pixel Perfect PDFs.
How to Convert HTML to PDF in .NET Core
- Download the C# library to convert HTML to PDF
- Use
RenderUrlAsPdf
to convert web URLs to PDF - Convert HTML markdown strings to PDF with
RenderHtmlAsPdf
- Convert MVC views to PDF by configuring the Model and Services class
- Modify the HTML page to use the Model and invoke a method to pass the HTML to
RenderHtmlAsPdf
Overview
After this tutorial, you'll be able to:
- Convert to PDF from different sources like URL, HTML, MVC views
- Engage with advanced options used for different output PDF settings
- Deploy your project to Linux and Windows
- Work with PDF document manipulation capabilities
- Add headers and footers, merge files, add stamps
- Work with Dockers
This wide range of .NET Core HTML to PDF capabilities will help with a whole range of project needs.
Get started with IronPDF
Start using IronPDF in your project today with a free trial.
Step 1
1. Install the IronPDF Library Free
IronPDF can be installed and used on all of the .NET project types like Windows applications, ASP.NET MVC, and .NET Core applications.
To add the IronPDF library to our project we have two ways, either from the Visual Studio editor install using NuGet, or with a command line using package console manager.
Install using NuGet
To add the IronPDF library to our project using NuGet, we can use the visualized interface (NuGet Package Manager) or by command using Package Manager Console:
1.1.1 Using NuGet Package Manager
1- Right click on project name -> Select Manage NuGet Package 2- From browser tab -> search for IronPdf -> Install 3- Click Ok 4- Done!
1.1.2 Using NuGet Package Console manager
1- From Tools -> NuGet Package Manager -> Package Manager Console 2- Run command -> Install-Package IronPdf
How To Tutorials
2. Convert Website to PDF
Sample: ConvertUrlToPdf console application
Follow these steps to create a new Asp.NET MVC Project
1- Open Visual Studio 2- Choose Create new project 3- Choose Console App (.NET Core) 4- Give our sample name “ConvertUrlToPdf” and click create 5- Now we have a console application created 6- Add IronPdf => click install
7- Add our first few lines that render a Wikipedia website main page to PDF
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-1.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderUrlAsPdf("https://www.wikipedia.org/");
pdf.SaveAs("wiki.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
8- Run and check created file wiki.pdf
3. Convert .NET Core HTML to PDF
Sample: ConvertHTMLToPdf Console application
To render HTML to PDF we have two ways:
1- Write HTML into string then render it
2- Write HTML into file and pass it path to IronPDF to render it
Rendering the HTML string sample code will look like this.
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-2.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
pdf.SaveAs("HtmlString.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
And the resulting PDF will look like this.
4. Convert MVC View to PDF
Sample: TicketsApps .NET Core MVC Application
Let's implement a real-life example. I've chosen an online ticketing site. Open the site, navigate to 'book ticket,' fill in the required information, and then download your copy as a PDF file.
We will go through these steps:
- Create Project
- Create client object model
- Create client services (add, view)
- Design Ticket Booking Page
- Validate and Save The Booking Information
- Download PDF ticket
Create Project
- Choose "ASP.NET Core Web App (Model-View-Controller)" project.
- Name the project "TicketsApps."
- Let's use .NET 8 with Linux Docker enabled. Inside the Dockerfile, change from "USER app" to "USER root". This will ensure that sufficient permissions are granted to the library.
- Now it’s ready.
Add Client Model
- Right click on "Models" folder and add class.
- Name the model “ClientModel” then click add.
- Add the attributes 'name,' 'phone,' and 'email' to the ClientModel class. Make them all required by adding the 'Required' attribute over each of them as follows:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-3.cs
public class ClientModel
{
[Required]
public string Name { get; set; }
[Required]
public string Phone { get; set; }
[Required]
public string Email { get; set; }
}
Public Class ClientModel
<Required>
Public Property Name() As String
<Required>
Public Property Phone() As String
<Required>
Public Property Email() As String
End Class
Add Client Services
- Create a folder and name it "services."
- Add a class named "ClientServices."
- Add a static object of type "ClientModel" to use it as a repository.
- Add two functions: one for saving clients to the repository, and the second to retrieve saved clients.
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-4.cs
public class ClientServices
{
private static ClientModel _clientModel;
public static void AddClient(ClientModel clientModel)
{
_clientModel = clientModel;
}
public static ClientModel GetClient()
{
return _clientModel;
}
}
Public Class ClientServices
Private Shared _clientModel As ClientModel
Public Shared Sub AddClient(ByVal clientModel As ClientModel)
_clientModel = clientModel
End Sub
Public Shared Function GetClient() As ClientModel
Return _clientModel
End Function
End Class
Design Ticket Booking Page
- From solution explorer, right click on the "Controllers" folder and add a controller.
- Name it "BookTicketController."
- Right click on the index function (or as we called it action) and choose "Add View."
- Add a View named “index.”
- Update the HTML as follows
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-5.cs
@model IronPdfMVCHelloWorld.Models.ClientModel
@{
ViewBag.Title = "Book Ticket";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-10 pull-right">
<button type="submit" value="Save" class="btn btn-sm">
<i class="fa fa-plus"></i>
<span>
Save
</span>
</button>
</div>
</div>
</div>
}
model ReadOnly Property () As IronPdfMVCHelloWorld.Models.ClientModel
ViewBag.Title = "Book Ticket"
End Property
'INSTANT VB TODO TASK: The following line could not be converted:
(Of h2) Index</h2> [using](Html.BeginForm())
If True Then
'INSTANT VB TODO TASK: The following line uses invalid syntax:
' <div class="form-horizontal"> @Html.ValidationSummary(True, "", New { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Name, htmlAttributes: New { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Name, New { htmlAttributes = New { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", New { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Phone, htmlAttributes: New { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Phone, New { htmlAttributes = New { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Phone, "", New { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Email, htmlAttributes: New { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Email, New { htmlAttributes = New { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email, "", New { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-10 pull-right"> <button type="submit" value="Save" class="btn btn-sm"> <i class="fa fa-plus"></i> <span> Save </span> </button> </div> </div> </div> }
- Add a navitation link to enable our website visitors to navigate to our new booking page. This can be done by updating the layout in the existing path (Views -> Shared -> _Layout.cshtml). Add the following code:
<li class="nav-item">
<a
class="nav-link text-dark"
asp-area=""
asp-controller="BookTicket"
asp-action="Index"
>Book Ticket</a
>
</li>
<li class="nav-item">
<a
class="nav-link text-dark"
asp-area=""
asp-controller="BookTicket"
asp-action="Index"
>Book Ticket</a
>
</li>
- The result should look like this.
- Navigate to the "Book Ticket" page. You should find that it looks like this:
Validate and Save The Booking Information
- Add another index action with the attribute [HttpPost] to inform the MVC engine that this action is for submitting data. Validate the sent model, and if it's valid, the code will redirect the visitor to the TicketView Page. If it's not valid, the visitor will receive error validation messages on the screen.
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-7.cs
[HttpPost]
public ActionResult Index(ClientModel model)
{
if (ModelState.IsValid)
{
ClientServices.AddClient(model);
return RedirectToAction("TicketView");
}
return View(model);
}
<HttpPost>
Public Function Index(ByVal model As ClientModel) As ActionResult
If ModelState.IsValid Then
ClientServices.AddClient(model)
Return RedirectToAction("TicketView")
End If
Return View(model)
End Function
Sample of the error messages
- Create a Ticket model in the "Models" file and add code as follows
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-9.cs
public class TicketModel : ClientModel
{
public int TicketNumber { get; set; }
public DateTime TicketDate { get; set; }
}
Public Class TicketModel
Inherits ClientModel
Public Property TicketNumber() As Integer
Public Property TicketDate() As DateTime
End Class
- Add TicketView to display our ticket. This view will host a Ticket partial view that is responsible to display the ticket and will be used later to print the Ticket.
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-8.cs
public ActionResult TicketView()
{
var rand = new Random();
var client = ClientServices.GetClient();
var ticket = new TicketModel()
{
TicketNumber = rand.Next(100000, 999999),
TicketDate = DateTime.Now,
Email = client.Email,
Name = client.Name,
Phone = client.Phone
};
return View(ticket);
}
Public Function TicketView() As ActionResult
Dim rand = New Random()
Dim client = ClientServices.GetClient()
Dim ticket = New TicketModel() With {
.TicketNumber = rand.Next(100000, 999999),
.TicketDate = DateTime.Now,
.Email = client.Email,
.Name = client.Name,
.Phone = client.Phone
}
Return View(ticket)
End Function
- Right click on TicketView function, choose "Add View" and name it "TicketView". Add the following code:
@model TicketsApps.Models.TicketModel @{ ViewData["Title"] = "TicketView"; }
@Html.Partial("_TicketPdf", Model) @using (Html.BeginForm()) { @Html.HiddenFor(c
=> c.Email) @Html.HiddenFor(c => c.Name) @Html.HiddenFor(c => c.Phone)
@Html.HiddenFor(c => c.TicketDate) @Html.HiddenFor(c => c.TicketNumber)
<div class="form-group">
<div class="col-md-10 pull-right">
<button type="submit" value="Save" class="btn btn-sm">
<i class="fa fa-plus"></i>
<span> Download Pdf </span>
</button>
</div>
</div>
}
@model TicketsApps.Models.TicketModel @{ ViewData["Title"] = "TicketView"; }
@Html.Partial("_TicketPdf", Model) @using (Html.BeginForm()) { @Html.HiddenFor(c
=> c.Email) @Html.HiddenFor(c => c.Name) @Html.HiddenFor(c => c.Phone)
@Html.HiddenFor(c => c.TicketDate) @Html.HiddenFor(c => c.TicketNumber)
<div class="form-group">
<div class="col-md-10 pull-right">
<button type="submit" value="Save" class="btn btn-sm">
<i class="fa fa-plus"></i>
<span> Download Pdf </span>
</button>
</div>
</div>
}
- Right click on BookTicket file, add another View and name it "_TicketPdf." Add the following code:
@model TicketsApps.Models.TicketModel @{ Layout = null; }
<link href="../css/ticket.css" rel="stylesheet" />
<div class="ticket">
<div class="stub">
<div class="top">
<span class="admit">VIP</span>
<span class="line"></span>
<span class="num">
@Model.TicketNumber
<span> Ticket</span>
</span>
</div>
<div class="number">1</div>
<div class="invite">Room Number</div>
</div>
<div class="check">
<div class="big">
Your <br />
Ticket
</div>
<div class="number">VIP</div>
<div class="info">
<section>
<div class="title">Date</div>
<div>@Model.TicketDate.ToShortDateString()</div>
</section>
<section>
<div class="title">Issued By</div>
<div>Admin</div>
</section>
<section>
<div class="title">Invite Number</div>
<div>@Model.TicketNumber</div>
</section>
</div>
</div>
</div>
@model TicketsApps.Models.TicketModel @{ Layout = null; }
<link href="../css/ticket.css" rel="stylesheet" />
<div class="ticket">
<div class="stub">
<div class="top">
<span class="admit">VIP</span>
<span class="line"></span>
<span class="num">
@Model.TicketNumber
<span> Ticket</span>
</span>
</div>
<div class="number">1</div>
<div class="invite">Room Number</div>
</div>
<div class="check">
<div class="big">
Your <br />
Ticket
</div>
<div class="number">VIP</div>
<div class="info">
<section>
<div class="title">Date</div>
<div>@Model.TicketDate.ToShortDateString()</div>
</section>
<section>
<div class="title">Issued By</div>
<div>Admin</div>
</section>
<section>
<div class="title">Invite Number</div>
<div>@Model.TicketNumber</div>
</section>
</div>
</div>
</div>
- Add the following "ticket.css" file in the "wwwroot/css" file.
- Add IronPDF to the project and agree to the license.
- Add the TicketView post method that will handle the download button.
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-10.cs
[HttpPost]
public ActionResult TicketView(TicketModel model)
{
IronPdf.Installation.TempFolderPath = $@"{Directory.GetParent}/irontemp/";
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
var html = this.RenderViewAsync("_TicketPdf", model);
var renderer = new IronPdf.ChromePdfRenderer();
using var pdf = renderer.RenderHtmlAsPdf(html.Result, @"wwwroot/css");
return File(pdf.Stream.ToArray(), "application/pdf");
}
<HttpPost>
Public Function TicketView(ByVal model As TicketModel) As ActionResult
IronPdf.Installation.TempFolderPath = $"{AddressOf Directory.GetParent}/irontemp/"
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = True
Dim html = Me.RenderViewAsync("_TicketPdf", model)
Dim renderer = New IronPdf.ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(html.Result, "wwwroot/css")
Return File(pdf.Stream.ToArray(), "application/pdf")
End Function
- Create a controller in the "Controller" file and name it "ControllerExtensions". This controller will render the partial view to a string. Use the extension code as follows:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-11.cs
using System.IO;
using System.Threading.Tasks;
public static class ControllerExtensions
{
public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
{
if (string.IsNullOrEmpty(viewName))
{
viewName = controller.ControllerContext.ActionDescriptor.ActionName;
}
controller.ViewData.Model = model;
using (var writer = new StringWriter())
{
IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);
if (viewResult.Success == false)
{
return $"A view with the name {viewName} could not be found";
}
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, new HtmlHelperOptions());
await viewResult.View.RenderAsync(viewContext);
return writer.GetStringBuilder().ToString();
}
}
}
Imports System.IO
Imports System.Threading.Tasks
Public Module ControllerExtensions
<System.Runtime.CompilerServices.Extension> _
Public Async Function RenderViewAsync(Of TModel)(ByVal controller As Controller, ByVal viewName As String, ByVal model As TModel, Optional ByVal As Boolean = False) As Task(Of String)
If String.IsNullOrEmpty(viewName) Then
viewName = controller.ControllerContext.ActionDescriptor.ActionName
End If
controller.ViewData.Model = model
Using writer = New StringWriter()
Dim viewEngine As IViewEngine = TryCast(controller.HttpContext.RequestServices.GetService(GetType(ICompositeViewEngine)), ICompositeViewEngine)
Dim viewResult As ViewEngineResult = viewEngine.FindView(controller.ControllerContext, viewName, Not partial)
If viewResult.Success = False Then
Return $"A view with the name {viewName} could not be found"
End If
Dim viewContext As New ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, New HtmlHelperOptions())
Await viewResult.View.RenderAsync(viewContext)
Return writer.GetStringBuilder().ToString()
End Using
End Function
End Module
- Run the application and fill out the ticket information, then click 'Save'.
- View the generated ticket
Download PDF ticket
To download the ticket as a PDF, click 'Download Pdf'. You will receive a PDF containing the ticket.
You can download the complete code for this guide. It comes as a zipped file that you can open in Visual Studio. Click here to download the project.
5. .NET PDF Render Options Chart
We have some advanced options that define PDF-rendering options like adjusting margins, paper orientation, paper size, and more.
Below is a table to illustrate the many different options.
Class | ChromePdfRenderer | |
---|---|---|
Description | Used to define PDF print out options, like paper size, DPI, headers and footers | |
Properties / functions | Type | Description |
CustomCookies | Dictionary<string, string> | Custom cookies for the HTML render. Cookies do not persist between renders and must be set each time. |
PaperFit | VirtualPaperLayoutManager | A manager for setting up virtual paper layouts, controlling how content will be laid out on PDF "paper" pages. Includes options for Default Chrome Behavior, Zoomed, Responsive CSS3 Layouts, Scale-To-Page & Continuous Feed style PDF page setups. |
UseMarginsOnHeaderAndFooter | UseMargins | Use margin values from the main document when rendering headers and footers. |
CreatePdfFormsFromHtml | bool | Turns all HTML form elements into editable PDF forms. Default value is true. |
CssMediaType | PdfCssMediaType | Enables Media="screen" CSS Styles and StyleSheets. Default value is PdfCssMediaType.Screen. |
CustomCssUrl | string | Allows a custom CSS style-sheet to be applied to HTML before rendering. May be a local file path or a remote URL. Only applicable when rendering HTML to PDF. |
EnableJavaScript | bool | Enables JavaScript and JSON to be executed before the page is rendered. Ideal for printing from Ajax / Angular Applications. Default value is false. |
EnableMathematicalLaTex | bool | Enables rendering of Mathematical LaTeX Elements. |
Javascript | string | A custom JavaScript string to be executed after all HTML has loaded but before PDF rendering. |
JavascriptMessageListener | StringDelegate | A method callback to be invoked whenever a browser JavaScript console message becomes available. |
FirstPageNumber | int | First page number to be used in PDF Headers and Footers. Default value is 1. |
TableOfContents | TableOfContentsTypes | Generates a table of contents at the location in the HTML document where an element is found with id "ironpdf-toc". |
GrayScale | bool | Outputs a black-and-white PDF. Default value is false. |
TextHeader | ITextHeaderFooter | Sets the footer content for every PDF page as text, supporting 'mail-merge' and automatically turning URLs into hyperlinks. |
TextFooter | ||
HtmlHeader | HtmlHeaderFooter | Sets the header content for every PDF page as HTML. Supports 'mail-merge'. |
HtmlFooter | ||
InputEncoding | Encoding | The input character encoding as a string. Default value is Encoding.UTF8. |
MarginTop | double | Top PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25. |
MarginRight | double | Right PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25. |
MarginBottom | double | Bottom PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25. |
MarginLeft | double | Left PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25. |
PaperOrientation | PdfPaperOrientation | The PDF paper orientation, such as Portrait or Landscape. Default value is Portrait. |
PaperSize | PdfPaperSize | Sets the paper size |
SetCustomPaperSizeinCentimeters | double | Sets the paper size in centimeters. |
SetCustomPaperSizeInInches | Sets the paper size in inches. | |
SetCustomPaperSizeinMilimeters | Sets the paper size in millimeters. | |
SetCustomPaperSizeinPixelsOrPoints | Sets the paper size in screen pixels or printer points. | |
PrintHtmlBackgrounds | Boolean | Indicates whether to print background-colors and images from HTML. Default value is true. |
RequestContext | RequestContexts | Request context for this render, determining isolation of certain resources such as cookies. |
Timeout | Integer | Render timeout in seconds. Default value is 60. |
Title | String | PDF Document Name and Title metadata, useful for mail-merge and automatic file naming in the IronPdf MVC and Razor extensions. |
ForcePaperSize | Boolean | Force page sizes to be exactly what is specified via IronPdf.ChromePdfRenderOptions.PaperSize by resizing the page after generating a PDF from HTML. Helps correct small errors in page size when rendering HTML to PDF. |
WaitFor | WaitFor | A wrapper object that holds configuration for wait-for mechanism for users to wait for certain events before rendering. By default, it will wait for nothing. |
6. .NET PDF Header Footer Options Chart
Class | TextHeaderFooter | |
---|---|---|
Description | Used to define text header and footer display options | |
Properties \ functions | Type | Description |
CenterText | string | Set the text in centered/left/right of PDF header or footer. Can also merge metadata using strings placeholders: {page}, {total-pages}, {url}, {date}, {time}, {html-title}, {pdf-title} |
LeftText | ||
RightText | ||
DrawDividerLine | Boolean | Adds a horizontal line divider between the header/footer and the page content on every page of the PDF document. |
DrawDividerLineColor | Color | The color of the divider line specified for IronPdf.TextHeaderFooter.DrawDividerLine. |
Font | PdfFont | Font family used for the PDF document. Default is IronSoftware.Drawing.FontTypes.Helvetica. |
FontSize | Double | Font size in pixels. |
7. Apply PDF Printing (Rendering) Options
Let us try to configure our PDF rendering options.
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-12.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Set rendering options
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;
renderer.RenderHtmlFileAsPdf(@"testFile.html").SaveAs("GeneratedFile.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
8. Docker .NET Core Applications
8.1. What is Docker?
Docker is a set of platform as service products that uses OS-level virtualization to deliver software in packages called containers. Containers are isolated from one another and bundle their own software, libraries and configuration files; they can communicate with each other through well-defined channels.
You can learn more about Docker and ASP.NET Core application here.
We'll skip ahead to working with Docker, but if you want to learn more, there's a great introduction to .NET and Docker here. and even more about how to build containers for .NET core app.
Let's get started with Docker together.
8.2. Install Docker
Visit to the Docker website here to install Docker.
Click get started.
Click download for Mac and Windows.
Signup for free, then login.
Download Docker for Windows.
Start installing Docker.
It will require a restart. After your machine restartrs, login to Docker.
Now you can run Docker "hello world" by opening the Windows command line or PowerShell script and write:
Docker run hello-world
Here is a list of the most important command lines to help you:
- Docker images => To list all available images on this machine
- Docker ps => to list all running containers
- Docker ps –a => to list all containers
8.3. Run into Linux container
9. Work with Existing PDF Documents
9.1. Open Existing PDF
As you can create a PDF from URL and HTML (text or file), you can also work with existing PDF documents.
The following is an example to open either a normal PDF or encrypted PDF with a password
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-13.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
// Open an unencrypted pdf
PdfDocument unencryptedPdf = PdfDocument.FromFile("testFile.pdf");
// Open an encrypted pdf
PdfDocument encryptedPdf = PdfDocument.FromFile("testFile2.pdf", "MyPassword");
IronPdf.License.LicenseKey = "YourLicenseKey"
' Open an unencrypted pdf
Dim unencryptedPdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
' Open an encrypted pdf
Dim encryptedPdf As PdfDocument = PdfDocument.FromFile("testFile2.pdf", "MyPassword")
9.2. Merge Multiple PDFs
You can merge multiple PDFs into one single PDF as follows:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-14.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
List<PdfDocument> PDFs = new List<PdfDocument>();
PDFs.Add(PdfDocument.FromFile("1.pdf"));
PDFs.Add(PdfDocument.FromFile("2.pdf"));
PDFs.Add(PdfDocument.FromFile("3.pdf"));
using PdfDocument PDF = PdfDocument.Merge(PDFs);
PDF.SaveAs("mergedFile.pdf");
foreach (PdfDocument pdf in PDFs)
{
pdf.Dispose();
}
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim PDFs As New List(Of PdfDocument)()
PDFs.Add(PdfDocument.FromFile("1.pdf"))
PDFs.Add(PdfDocument.FromFile("2.pdf"))
PDFs.Add(PdfDocument.FromFile("3.pdf"))
Using PDF As PdfDocument = PdfDocument.Merge(PDFs)
PDF.SaveAs("mergedFile.pdf")
'INSTANT VB NOTE: The variable pdf was renamed since Visual Basic will not allow local variables with the same name as parameters or other local variables:
For Each Me.pdf_Conflict As PdfDocument In PDFs
Me.pdf_Conflict.Dispose()
Next pdf_Conflict
End Using
Append another PDF to the end of the current PDF as follows:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-15.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("1.pdf");
PdfDocument pdf2 = PdfDocument.FromFile("2.pdf");
pdf.AppendPdf(pdf2);
pdf.SaveAs("appendedFile.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("1.pdf")
Dim pdf2 As PdfDocument = PdfDocument.FromFile("2.pdf")
pdf.AppendPdf(pdf2)
pdf.SaveAs("appendedFile.pdf")
Insert a PDF into another PDF starting with given index:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-16.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("1.pdf");
PdfDocument pdf2 = PdfDocument.FromFile("2.pdf");
pdf.InsertPdf(pdf2, 0);
pdf.SaveAs("InsertIntoSpecificIndex.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("1.pdf")
Dim pdf2 As PdfDocument = PdfDocument.FromFile("2.pdf")
pdf.InsertPdf(pdf2, 0)
pdf.SaveAs("InsertIntoSpecificIndex.pdf")
9.3 Add Headers or Footers
You can add headers and footers to an existing PDF or when you render the PDF from HTML or URL.
There are two classes you can use to add header or footer to a PDF:
- TextHeaderFooter: add simple text in header or footer.
- HtmlHeaderFooter: add header or footer with rich HTML content and images.
Now let us see two examples of how to add header/footer to existing pdf or when it is rendered using these two classes.
9.3.1 Add header to existing pdf
Below is an example to load an existing PDF, then add a header and footer using AddTextHeaders
and AddHtmlFooters
methods.
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-17.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
TextHeaderFooter header = new TextHeaderFooter()
{
CenterText = "Pdf Header",
LeftText = "{date} {time}",
RightText = "{page} of {total-pages}",
DrawDividerLine = true,
FontSize = 10
};
pdf.AddTextHeaders(header);
pdf.SaveAs("withHeader.pdf");
HtmlHeaderFooter Footer = new HtmlHeaderFooter()
{
HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
DrawDividerLine = true,
MaxHeight = 10 //mm
};
pdf.AddHtmlFooters(Footer);
pdf.SaveAs("withHeaderAndFooters.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Dim header As New TextHeaderFooter() With {
.CenterText = "Pdf Header",
.LeftText = "{date} {time}",
.RightText = "{page} of {total-pages}",
.DrawDividerLine = True,
.FontSize = 10
}
pdf.AddTextHeaders(header)
pdf.SaveAs("withHeader.pdf")
Dim Footer As New HtmlHeaderFooter() With {
.HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
.DrawDividerLine = True,
.MaxHeight = 10
}
pdf.AddHtmlFooters(Footer)
pdf.SaveAs("withHeaderAndFooters.pdf")
9.3.2 Add header and footer to new pdf
Here is an example to create a PDF from HTML file and add a header and footer to it using rendering options.
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-18.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.TextHeader = new TextHeaderFooter()
{
CenterText = "Pdf Header",
LeftText = "{date} {time}",
RightText = "{page} of {total-pages}",
DrawDividerLine = true,
FontSize = 10
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
DrawDividerLine = true,
MaxHeight = 10
};
PdfDocument pdf = renderer.RenderHtmlFileAsPdf("test.html");
pdf.SaveAs("generatedFile.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.TextHeader = New TextHeaderFooter() With {
.CenterText = "Pdf Header",
.LeftText = "{date} {time}",
.RightText = "{page} of {total-pages}",
.DrawDividerLine = True,
.FontSize = 10
}
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {
.HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
.DrawDividerLine = True,
.MaxHeight = 10
}
Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("test.html")
pdf.SaveAs("generatedFile.pdf")
10. Add PDF Password and Security
You can secure your PDF with a password and edit file security settings like prevent copying and printing.
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-19.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
// Edit file metadata
pdf.MetaData.Author = "john smith";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = DateTime.Now;
// Edit file security settings
// The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption();
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key"); //secret-key is a owner password
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;
// Change or set the document ecrpytion password
pdf.Password = "123";
pdf.SaveAs("secured.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
' Edit file metadata
pdf.MetaData.Author = "john smith"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = DateTime.Now
' Edit file security settings
' The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key") 'secret-key is a owner password
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights
' Change or set the document ecrpytion password
pdf.Password = "123"
pdf.SaveAs("secured.pdf")
11. Digitally Sign PDFs
You can also digitally sign a PDF as follows:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-20.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
pdf.Sign(new PdfSignature("cert123.pfx", "password"));
pdf.SaveAs("signed.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
pdf.Sign(New PdfSignature("cert123.pfx", "password"))
pdf.SaveAs("signed.pdf")
Advanced example for more control:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-21.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
IronPdf.Signing.PdfSignature signature = new IronPdf.Signing.PdfSignature("cert123.pfx", "123");
// Optional signing options
signature.SigningContact = "support@ironsoftware.com";
signature.SigningLocation = "Chicago, USA";
signature.SigningReason = "To show how to sign a PDF";
// Sign the PDF with the PdfSignature. Multiple signing certificates may be used
pdf.Sign(signature);
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Dim signature As New IronPdf.Signing.PdfSignature("cert123.pfx", "123")
' Optional signing options
signature.SigningContact = "support@ironsoftware.com"
signature.SigningLocation = "Chicago, USA"
signature.SigningReason = "To show how to sign a PDF"
' Sign the PDF with the PdfSignature. Multiple signing certificates may be used
pdf.Sign(signature)
12. Extract Text and Images from PDF
Extract text and images
Using IronPdf you can extract text and images from a PDF as follows:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-22.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
pdf.ExtractAllText(); // Extract all text in the pdf
pdf.ExtractTextFromPage(0); // Read text from specific page
// Extract all images in the pdf
var AllImages = pdf.ExtractAllImages();
// Extract images from specific page
var ImagesOfAPage = pdf.ExtractImagesFromPage(0);
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
pdf.ExtractAllText() ' Extract all text in the pdf
pdf.ExtractTextFromPage(0) ' Read text from specific page
' Extract all images in the pdf
Dim AllImages = pdf.ExtractAllImages()
' Extract images from specific page
Dim ImagesOfAPage = pdf.ExtractImagesFromPage(0)
12.1. Rasterize PDF to Image
You can also convert PDF pages to images as follows
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-23.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
List<int> pageList = new List<int>() { 1, 2 };
pdf.RasterizeToImageFiles("*.png", pageList);
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Dim pageList As New List(Of Integer)() From {1, 2}
pdf.RasterizeToImageFiles("*.png", pageList)
13. Add PDF Watermark
The following is an example of how to watermark PDF pages.
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-24.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
// Apply watermark
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs("Watermarked.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
' Apply watermark
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center)
pdf.SaveAs("Watermarked.pdf")
Watermarking has a restricted set of options and features. For greater control, you can utilize the HTMLStamper class.
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-25.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<div>test text </div>");
// Configure HTML stamper
HtmlStamper backgroundStamp = new HtmlStamper()
{
Html = "<h2 style='color:red'>copyright 2018 ironpdf.com",
MaxWidth = new Length(20),
MaxHeight = new Length(20),
Opacity = 50,
Rotation = -45,
IsStampBehindContent = true,
VerticalAlignment = VerticalAlignment.Middle
};
pdf.ApplyStamp(backgroundStamp);
pdf.SaveAs("stamped.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<div>test text </div>")
' Configure HTML stamper
Dim backgroundStamp As New HtmlStamper() With {
.Html = "<h2 style='color:red'>copyright 2018 ironpdf.com",
.MaxWidth = New Length(20),
.MaxHeight = New Length(20),
.Opacity = 50,
.Rotation = -45,
.IsStampBehindContent = True,
.VerticalAlignment = VerticalAlignment.Middle
}
pdf.ApplyStamp(backgroundStamp)
pdf.SaveAs("stamped.pdf")
Tutorial Quick Access
Get the Source Code
Access all the source code found in this tutorial as a Visual Studio project ZIP file, easy to use and share for your project.
Get the CodeGitHub Tutorial Access
Explore this tutorial and many more via GitHub. Using the projects and source code is the best way to learn and apply it to your own PDF .NET Core needs and use cases.
Generate PDFs in .NET Core TutorialKeep the PDF CSharp Cheat Sheet
Develop PDFS in your .NET applications using our handy reference document. Providing quick access to common functions and examples for generating and editing PDFs in C# and VB.NET, this shareable tool helps you save time and effort getting started with IronPDF and common PDF requirements in your project.
Keep the Cheat SheetMore Documentation
Read the IronPDF API Reference, which thoroughly presents the details of all the features in IronPDF plus namespaces, classes, methods fields and enums.
API Reference Documentation