Csharp Create PDF Tutorial
Photo from Unsplash
Originally Posted On: https://ironpdf.com/blog/using-ironpdf/csharp-create-pdf-tutorial/
C# Create PDF (Code Example Tutorial)
This article will teach you how to produce PDF documents from a web page in the C# .NET programming language using IronPDF.
IronPDF is a fully-featured PDF library for .NET and Java. It is one of several third-party libraries available that work efficiently in creating, editing, and processing PDF documents, as well as in outputting editable PDF files from the content of other file types (HTML, PNG, RTF, etc.). Find out more about IronPDF and similar PDF libraries from the growing catalog of third-party library comparison articles.
How to Create PDF Files in C#
- Create a New Project in Visual Studio
- Install the PDF C# Library using the NuGet Package Manager
- Create a PDF from HTML using
RenderHtmlToPdf()
- Create PDF Document from URL
- Create and View PDF Document with many options
- Call SaveAs to save the PDF file to the computer
- More
As HTML is a markup language, it can be difficult to convert the contents of HTML to a PDF without the HTML tags. IronPDF offers features such as creating PDF in C# from HTML, because of its ease of use and additional features like using JavaScript, CSS, and images.
This article will cover the HTML to PDF conversion in C#, provided by IronPDF, in detail.
1. Create a New Project in Visual Studio
Open the Visual Studio software and go to the File menu. Select New Project and then select Console Application. This article will use a Console Application to generate PDF documents.
Create a new project in Visual Studio
Enter the project name and select the path in the appropriate TextBox. Then, click the Next button.
Configure this project
Select the required .NET Framework, then click the Create button, as shown below:
.NET Framework selection
The Visual Studio project will now generate the structure for the selected application, and if you have selected the Console, Windows, and Web Application, it will open the program.cs
file where you can enter the code and build/run the application.
The next step is to add the library and test the program.
Using the Visual Studio NuGet Package Manager
The Visual Studio software provides the NuGet Package Manager option to install the package directly to the solution. The below screenshot shows how to open the NuGet Package Manager.
Don’t worry about the license key, IronPDF is free for development.
Navigate to NuGet Package Manager
It provides the search box to show the list of available package libraries from the NuGet website. In the package manager, search for the keyword “IronPDF,” as shown in the below screenshot:
Install the IronPdf package from the NuGet Package Manager
From the image above, select the IronPDF option from the list of related NuGet packages and install the package for the solution.
Using the Visual Studio Command-Line
In the Visual Studio menu, go to Tools > NuGet Package Manager > Package Manager Console
Navigate to Package Manager Console
Enter the following line in the Package Manager Console tab:
Install-Package IronPdf
Installation step
Now the package will download/install to the current project and be ready to use.
Installation process in Package Manager Console
2. Create a PDF from HTML using RenderHtmlAsPdf()
After the IronPDF library is installed, the first objective is to create a PDFDocument
object in C#. Copy the code below and paste it into your Visual Studio, then run the program.
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
var pdf = new ChromePdfRenderer();
PdfDocument doc = pdf.RenderHtmlAsPdf("
This is a heading
");mypdf.SaveAs("FirstPDFDocument.pdf");
After execution of your C# project, there will be a file named “FirstPDFDocument.pdf” in the bin folder of your project, double click on the said file, and the PDF file will open in the browser tab.
Creating PDF files in C# or creating PDF files converting HTML to PDF is just a few lines of code using IronPDF.
3. Create a PDF Document from a URL
Creating a PDF file in C# using a URL is just as easy as the above example with just these three lines of code. The following code will demonstrate how to create PDF files from a URL.
using IronPdf;
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
var renderer = new IronPdf.ChromePdfRenderer();
// Create a PDF from a URL or local file path
using var pdf = renderer.RenderUrlAsPdf("https://www.amazon.com/?tag=hp2-brobookmark-us-20");
// Export to a file or Stream
pdf.SaveAs("url.pdf");
Here is the output of the above code.
PDF file output, rendered from a URL
Other examples of converting popular complex sites to PDF.
Another example of rendering a complex website
4. Render ASP.NET MVC to PDF
You can serve an existing HTML file or string, an existing PDF document, or a PDF in ASP.NET MVC. To easily serve these files or strings, use IronPDF and access it via a DLL ZIP file or through the IronPDF NuGet Package.
To serve a PDF document in ASP.NET MVC requires generating a FileResult method. With IronPDF you can use MVC to return a PDF file.
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
var renderer = new IronPdf.ChromePdfRenderer();
using var pdf = renderer.RenderHtmlFileAsPdf("Project/MyHtmlDocument.html");
// or to convert an HTML string
//var pdf = renderer.RenderHtmlAsPdf("
Hello IronPdf
");Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition","attachment;filename=\"FileName.pdf\"");
// edit this line to display ion browser and change the file name
Response.BinaryWrite(pdf.BinaryData);
Response.Flush();
Response.End();
5. Render Razor Views To PDF
The following method makes it easy to render a Razor view to a string. IronPDF’s HTML to PDF Conversion functionality can be used to render that Razor view as a string. Don’t forget to set the optional BaseURI parameter of the IronPdf.ChromePdfRenderer.RenderHtmlAsPdf
Method to load relative assets, CSS, JavaScript and images. Here is an example:
public string RenderRazorViewToString(string viewName, object model)
{
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View,
ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
Please read the .NET MVC PDF Guide documentation to learn how to render an MVC view as a binary PDF file.
6. Convert XML to PDF
C# XML to PDF directly can be a complex challenge, and it is best to start with XSLT. XML may be rendered to PDF via HTML(5) using XLST transformations.
These documents define how XML from a given schema may be converted to an accurate HTML representation and are a well-established standard.
The resultant HTML string or file may then be rendered as a PDF using the .NET PDF Generator:
Here is an example:
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
XslCompiledTransform transform = new XslCompiledTransform();
using(XmlReader reader = XmlReader.Create(new StringReader(XSLT))) {
transform.Load(reader);
}
StringWriter results = new StringWriter();
using(XmlReader reader = XmlReader.Create(new StringReader(XML))) {
transform.Transform(reader, null, results);
}
IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();
// options, headers and footers may be set there
// Render the XML as a PDF via XSLT
Renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf");
7. Generate PDF Reports
IronPDF can be used as a PDF Reader for C# and help visualize and export SSRS reports to PDF in ASP.NET C#. IronPDF can be used to render snapshots of data as “reports” in the PDF File Format. It also works as a PDF C# Parser. The basic methodology is to first generate the report as an HTML document – and then render the HTML as a PDF using IronPDF.
To style an XML report, the XML may be parsed and then the HTML is generated with the data. These reports may be generated as HTML which may then be customized and converted to PDF format using IronPDF. The easiest way to serve HTML content in ASP.NET is to use the IronPdf.AspxToPdf
class on the Form_Load
event of an ASP.NET WebForms.
Here is an example:
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();
// add a header to very page easily
Renderer.RenderingOptions.FirstPageNumber = 1;
Renderer.RenderingOptions.TextHeader.DrawDividerLine = true;
Renderer.RenderingOptions.TextHeader.CenterText = "{url}";
Renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Helvetica;
Renderer.RenderingOptions.TextHeader.FontSize = 12;
// add a footer too
Renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
Renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial;
Renderer.RenderingOptions.TextFooter.FontSize = 10;
Renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
Renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}";
Renderer.RenderHtmlFileAsPdf("Report.html").SaveAs("Report.pdf");
CSharp Create PDF
8. Work with PDF images and CSS
To use IronPDF to convert HTML String to PDF, provide a BaseUri when working with assets. All assets such as CSS, JavaScript files, and images will be loaded relative to that base URL.
The BaseURL
may be a web URL starting with “http” to load remote assets, or a local file path to access assets on your disk.
Another trick is to use the IronPdf.Imaging.ImageUtilities.ImageToDataUri
method to convert any System.Drawing.Image
or Bitmap object into an HTML string which can be embedded in HTML without saving to disk. Here is an example:
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
using var pdf = Renderer.RenderHtmlAsPdf("",@"C:\site\assets\");
pdf.SaveAs("html-with-assets.pdf");
var renderer = new IronPdf.ChromePdfRenderer();
using var advancedPDF = renderer.RenderHtmlFileAsPdf("C:\\Assets\\TestInvoice1.html");
advancedPDF.SaveAs("Invoice.pdf");
9. Convert ASPX Files to PDF
First, let’s access the ‘free for development’ C# Library for converting ASPX files to PDF. Download and install the IronPDF library as usual into your Visual Studio project. Additionally, it requires IronPdf.Extensions.ASPX from NuGet official page to be installed. It is not available in .NET Core because ASPX is superseded by the MVC model. Now that you have IronPDF and its extensions, you’ll see that it has the functionality for HTML conversion as well as ASPX to PDF generation as in the code below.
using System;
using System.Web.UI;
using IronPdf;
namespace aspxtopdf
{
public partial class SiteMaster : MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
AspxToPdf.RenderThisPageAsPdf();
}
}
}
CSharp Create PDF
10. View HTML to PDF Example File
The code below demonstrates how IronPDF can be used to convert HTML to PDF documents programmatically.
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
var uri = new Uri("https://www.c-sharpcorner.com/article/how-to-create-pdf-file-in-c-sharp-using-ironpdf/");
// turn page into pdf
var pdf = ChromePdfRenderer.StaticRenderUrlAsPdf(uri);
// save resulting pdf into file
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdf.Pdf"));
The PDF file is created inside the Debug folder. Here is the output:
CSharp Create PDF
The Getting Started Guide explains how to install IronPDF via NuGet (for those who are unfamiliar with the NuGet Package Manager).
11. Generate PDF File in C# .NET
With an extensive C# library using IronPDF, any ASP.NET page can easily be converted from HTML to PDF. This allows full control over reading, editing, and manipulating documents with just a single line of code.
Here is an example:
using System;
using System.Web.UI;
using IronPdf;
namespace aspxtopdf
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
AspxToPdf.RenderThisPageAsPdf();
}
}
}
CSharp Create PDF
This requires IronPdf.Extensions.ASPX from NuGet official page to be installed. It is not available in .NET Core because ASPX is superseded by the MVC model.
12. Generate PDF Document
Here is a very quick example of how to generate a PDF from an HTML input string:
/**
PDF from HTML String
anchor-generate-pdf-from-html-string
**/
private void HTMLString()
{
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Render any HTML fragment or document to HTML
var renderer = new IronPdf.ChromePdfRenderer();
using var pdf = renderer.RenderHtmlAsPdf("
Hello IronPDF
");var outputPath = "ChromePdfRenderer.pdf";
pdf.SaveAs(outputPath);
}
The following code makes use of IronPDF to generate a PDF directly from an ASPX file:
/**
PDF from ASPX
anchor-generate-pdf-from-aspx
**/
protected void Page_Load(object sender, EventArgs e)
{
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
IronPdf.AspxToPdf.RenderThisPageAsPdf();
}
IronPDF supports JavaScript quite nicely via the Chromium rendering engine. One stipulation though, you may have to add a delay to a page render to allow JavaScript time to execute whilst generating PDFs.
13. PDF Library For .NET
Using IronPDF, we’re able to create and edit PDF features simply according to application requirements. IronPDF provides a suite of functionality with its C# .NET PDF Library. The two main ways of accessing the library are to either:
- Download and unpack the DLL file for PDF.NET Library
- Navigate through NuGet and install the package via Visual Studio.
In the code below, C# Forms with button1_Click
demonstrate how simple it is to create a PDF with C#.
using IronPdf;
using System.Windows.Forms;
namespace ReadPdf
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, System.EventArgs e)
{
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
//Used ChromePdfRenderer Convert Class
var renderer = new ChromePdfRenderer();
//Getting Text from TextBox
string text = textBox1.Text;
//rendering or converting htmlaspdf.
renderer.RenderHtmlAsPdf("
"
+text+"").SaveAs("custom.pdf");//Confirmation
MessageBox.Show("Done !");
}
}
}
CSharp Create PDF
14. Chrome PDF Rendering Engine
The Iron Software engineering team is proud to release a game-changing upgrade to IronPDF now featuring “Chrome Identical” PDF rendering.
First, you must install IronPDF into your project from the NuGet Package Manager named IronPdf. Changing to the new renderer at a global level is simple. This approach updates all usages of your existing ChromePdfRenderer
and AspxToPdf
code.
Some of the Features of Chrome PDF Rendering Feature are:
- High-Quality Rendering
- The latest “Blink!” HTML rendering. Choose from Chrome Identical rendering or Enhanced Rendering.
- 20% Faster Renders
- Provides effortless multithreading and Async, using as many CPU cores as you wish. For SAAS and high-load applications, this may be 5-20 times faster, outperforming direct browser usage and web-drivers.
- Full Support
- Full support for JavaScript, responsive layout, and CSS3.
- Azure as a first-class citizen. It just works.
- Continued maintenance and improved full support for .NET 6, 5, Core, and Framework 4.0+.
- Rigorously Tested
- The release passed with 1156 green units & integration tests (and no red ones), ensuring stability similar to the main release, and continuously and actively improving it every day.
- Section 508 Accessibility Compliance
Produces accessible PDFs using the PDF(UA) tagged PDF standard.
Explore the multithreading and async support features for the Chrome rendering engine.
Here is an example:
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
IChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
using var doc = renderer.RenderHtmlAsPdf("
Hello world! This is sample for IronPdf
");doc.SaveAs("google_chrome.pdf");
CSharp Create PDF
15. Summary
Thanks for reading! This article demonstrated how to create a PDF document in C# using IronPDF. IronPDF is ideal for users needing to convert the contents of HTML to PDF without using HTML tags because of its ease of use and additional features like JavaScript, CSS, and images.
So, try out these methods and leave your feedback in the comments section of this article post! If you are not yet an IronPDF customer, you can try the 30-day free trial to check out their available features.
If you buy the complete Iron Suite, you will get All 7 Products for the Price of 2. For further details on [IronPDF licensing options]/licensing/), visit the Iron Suite pricing page to purchase the complete package.
Information contained on this page is provided by an independent third-party content provider. XPRMedia and this Site make no warranties or representations in connection therewith. If you are affiliated with this page and would like it removed please contact [email protected]