Skip to footer content
USING IRONPDF

PDF Conversion in C# (Developer Tutorial)

PDF Conversion in C# (Developer Tutorial)

IronPDF lets you convert documents to PDF in C# applications with just a few lines of code. It handles HTML-to-PDF and image-to-PDF transformations seamlessly across Windows, Linux, and macOS platforms.

This article shows you how PDF conversion works using IronPDF, the PDF library for .NET and .NET Core. Whether you're working on Windows, Linux, or macOS, IronPDF provides cross-platform support for all your PDF needs. The library offers comprehensive documentation and tutorials to help you get started quickly.

What is IronPDF?

  1. PDF Generation: Easily create PDF documents programmatically in C# from various sources, including HTML, images, text, and existing files.
  2. HTML to PDF Conversion: Convert HTML content into PDFs, including web pages or HTML templates, into high-quality PDFs with full control over styling and formatting.
  3. Image to PDF Conversion: Convert image files (such as JPEG, PNG, or BMP) into PDF documents, allowing for easy integration of images into PDF reports and documents.
  4. PDF Manipulation: Comprehensive PDF editing capabilities, including text extraction from PDFs, merging and splitting PDFs, and rotation, as well as adding, modifying, or removing content and annotations.
  5. PDF Forms: Create, fill, and extract data from PDF forms, making it suitable for applications that require interactive forms and data collection.

Whether you need to generate PDFs from scratch, convert HTML pages, images, or existing documents into PDF format, or manipulate existing PDFs, IronPDF offers straightforward APIs to accomplish these tasks. The library uses a Chrome rendering engine to ensure your HTML conversions look exactly as they should. For a complete list of capabilities, check out the IronPDF Features Overview website.

  1. PDF Generation: Create PDFs programmatically from HTML, images, text, and files. Supports custom sizes, orientation, and margins. Handles international languages too.
  2. HTML to PDF Conversion: Convert HTML to PDF with full styling. Supports CSS media, JavaScript, and web fonts. Works with WebGL and responsive designs.
  3. Image to PDF Conversion: Convert JPEG, PNG, or BMP files to PDF. Supports TIFF conversion and SVG graphics. Can embed images with DataURIs.
  4. PDF Manipulation: Edit PDFs with text extraction, merging/splitting, and annotations. Also redact text, add stamps, and manage metadata.
  5. PDF Forms: Create and fill PDF forms. Supports creating and editing forms. Can flatten PDFs to static content.

How Do I Create a New Visual Studio Project?

Before diving into code, let's set up a new C# Console Application project. If you're new to .NET development, you might find the quickstart guide helpful for additional setup tips. F# developers can also use IronPDF with functional programming approaches.

  1. Open Visual Studio and create a new project by clicking File > New > Project.

    Visual Studio File menu expanded showing various options including New Project, Clone Repository, Open File/Project, and Save options with keyboard shortcuts The File menu in Visual Studio provides quick access to essential project management functions, from creating new projects to cloning repositories from version control systems.

  2. A new window appears. Select the Console Application template and click Next at the bottom. This template is perfect for learning PDF basics before moving to complex project types like Blazor applications or ASP.NET MVC.

    Visual Studio's 'Create a new project' dialog showing Console Application template selected for creating a .NET Core command-line application that supports Windows, Linux, and macOS. The Console Application template in Visual Studio provides a starting point for creating cross-platform command-line applications using .NET Core.

  3. In the next window, name your project and choose a location, then click Next. Consider organizing projects in a dedicated folder for easy access to code examples and sample files.

    Visual Studio's 'Configure your new project' dialog showing setup for a Console Application named 'PDF Conversion' with project location and solution settings. Step 2: Configuring the new Console Application project with appropriate naming and location settings for the PDF conversion application.

  4. Select your target framework and click Create. For modern applications, use .NET 6 or later for best performance and support. Recent versions offer improved performance and async capabilities.

    Visual Studio project creation dialog showing 'Additional information' page with .NET 5.0 selected as the target framework for a Console Application. The final step in creating a new Console Application in Visual Studio, where you select the target framework. Note that .NET 5.0 is marked as 'Out of support' - consider using .NET 6.0 or .NET 8.0 for current projects.

Your project is ready. Let's install IronPDF.

How Do I Install IronPDF?

IronPDF offers several installation methods. We'll use the NuGet Package Manager here. You can explore advanced installation methods for specific scenarios, including Windows Installer options and Linux configurations.

  1. In Visual Studio, open the Tools menu and hover over NuGet Package Manager.
  2. Click Manage NuGet Packages for Solutions.

    Visual Studio Tools menu expanded showing NuGet Package Manager submenu with options for Package Manager Console, Manage NuGet Packages for Solution, and Package Manager Settings The Tools menu in Visual Studio provides access to NuGet Package Manager features, which are essential for managing external libraries and dependencies in .NET projects

  3. A new window appears. Click the Browse tab and search for "IronPDF".
  4. Select IronPDF and click Install. For smaller deployments, consider IronPdf.Slim.
  5. You can also install via Package Manager Console:

    Install-Package IronPdf

Or download directly from the IronPDF NuGet page. For containers, see the Docker deployment guide or run IronPDF as a remote container.

How Do I Convert Files to PDF Using IronPDF?

Let's explore converting different document formats to PDF. IronPDF provides extensive rendering options for customizing output, including custom logging and performance monitoring.

  1. HTML Files to PDF Documents
  2. Image to PDF Documents

How Do I Convert HTML Files to PDF?

Converting HTML to PDF is incredibly straightforward with IronPDF. The library supports advanced features like headers and footers, page breaks, and custom CSS. You can handle Bootstrap layouts and implement cookie management for authenticated content.

Here's how to convert an HTML file into a PDF:

using IronPdf;

// Create an instance of the ChromePdfRenderer class.
var renderer = new ChromePdfRenderer();

// Optional: Configure rendering options for better output
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;

// Enable JavaScript execution for dynamic content
renderer.RenderingOptions.EnableJavaScript = true;

// Set print CSS media type for proper formatting
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;

// Add custom headers for authenticated content
renderer.RenderingOptions.CustomCssUrl = "___PROTECTED_URL_142___";

// Configure viewport for responsive design
renderer.RenderingOptions.ViewPortWidth = 1024;

// Render the HTML file as a PDF document.
var pdf = renderer.RenderHtmlFileAsPdf("invoice.html");

// Optional: Add metadata
pdf.MetaData.Author = "Your Company";
pdf.MetaData.Keywords = "invoice, pdf, conversion";
pdf.MetaData.CreationDate = System.DateTime.Now;

// Save the PDF document as an output file.
pdf.SaveAs("output.pdf");

// Alternative: Save with compression
pdf.CompressImages(80);
pdf.SaveAs("compressed-output.pdf");
using IronPdf;

// Create an instance of the ChromePdfRenderer class.
var renderer = new ChromePdfRenderer();

// Optional: Configure rendering options for better output
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;

// Enable JavaScript execution for dynamic content
renderer.RenderingOptions.EnableJavaScript = true;

// Set print CSS media type for proper formatting
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;

// Add custom headers for authenticated content
renderer.RenderingOptions.CustomCssUrl = "___PROTECTED_URL_142___";

// Configure viewport for responsive design
renderer.RenderingOptions.ViewPortWidth = 1024;

// Render the HTML file as a PDF document.
var pdf = renderer.RenderHtmlFileAsPdf("invoice.html");

// Optional: Add metadata
pdf.MetaData.Author = "Your Company";
pdf.MetaData.Keywords = "invoice, pdf, conversion";
pdf.MetaData.CreationDate = System.DateTime.Now;

// Save the PDF document as an output file.
pdf.SaveAs("output.pdf");

// Alternative: Save with compression
pdf.CompressImages(80);
pdf.SaveAs("compressed-output.pdf");
$vbLabelText   $csharpLabel

This code transforms an HTML file ("invoice.html") into a PDF document. By creating a ChromePdfRenderer, you're using the Chromium engine to ensure accurate conversion that preserves your web page's appearance. The rendering options let you set custom margins and paper size. The resulting PDF saves as "output.pdf" with a simple SaveAs call. This streamlined process makes HTML-to-PDF conversion straightforward for generating PDFs in C#.

For complex scenarios, explore converting URLs to PDF, working with HTML strings, or converting CSHTML files in ASP.NET MVC applications. You can also render JavaScript charts and handle Angular applications.

What Does the HTML to PDF Output Look Like?

PDF viewer interface showing a sample invoice template with placeholder company information, two line items totaling $190.00, and navigation controls Example of a basic invoice template viewed in a PDF reader, demonstrating standard invoice elements including sender/recipient details, itemized services, and pricing calculations

For enhanced PDF generation, consider adding page numbers, table of contents, or custom watermarks. You can optimize output with linearization for faster web viewing.

How Do I Convert Images to PDF?

Let's convert images to PDF documents. With minimal code, you can convert JPEG, PNG, BMP, and SVG files. The library also supports advanced features like drawing lines and rectangles or adding text and bitmaps to existing PDFs.

What Image Formats Can I Convert?

IronPDF homepage screenshot displaying the C# PDF library's key features for creating, editing, and reading PDFs in .NET applications. IronPDF offers a comprehensive C# PDF library with support for HTML to PDF conversion, cross-platform compatibility, and over 50 features for PDF manipulation in .NET applications.

using IronPdf;
using System.IO;
using System.Linq;

// Enumerate all PNG files from the specified directory.
var imageFiles = Directory.EnumerateFiles("assets").Where(f => f.EndsWith(".png"));

// Create an instance of ImageToPdfConverter
var imageToPdf = new ImageToPdfConverter();

// Optional: Set rendering options for better control
imageToPdf.ImageBehavior = ImageBehavior.CropPage;
imageToPdf.PaperSize = IronPdf.Imaging.PdfPaperSize.A4;

// Set margins for professional appearance
imageToPdf.PaperMargins = new IronPdf.Imaging.PdfPaperMargins(25);

// Control image quality and compression
imageToPdf.ImageQuality = 90; // 0-100 quality scale

// Convert the images to a PDF document.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf");

// Alternative: Convert a single image with custom settings
var singleImagePdf = imageToPdf.ImageToPdf("assets/logo.png");
singleImagePdf.SaveAs("single-image.pdf");

// Advanced: Add metadata to image PDF
singleImagePdf.MetaData.Title = "Company Logo";
singleImagePdf.MetaData.Subject = "Brand Assets";
singleImagePdf.MetaData.CreationDate = DateTime.Now;
singleImagePdf.SaveAs("logo-with-metadata.pdf");
using IronPdf;
using System.IO;
using System.Linq;

// Enumerate all PNG files from the specified directory.
var imageFiles = Directory.EnumerateFiles("assets").Where(f => f.EndsWith(".png"));

// Create an instance of ImageToPdfConverter
var imageToPdf = new ImageToPdfConverter();

// Optional: Set rendering options for better control
imageToPdf.ImageBehavior = ImageBehavior.CropPage;
imageToPdf.PaperSize = IronPdf.Imaging.PdfPaperSize.A4;

// Set margins for professional appearance
imageToPdf.PaperMargins = new IronPdf.Imaging.PdfPaperMargins(25);

// Control image quality and compression
imageToPdf.ImageQuality = 90; // 0-100 quality scale

// Convert the images to a PDF document.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf");

// Alternative: Convert a single image with custom settings
var singleImagePdf = imageToPdf.ImageToPdf("assets/logo.png");
singleImagePdf.SaveAs("single-image.pdf");

// Advanced: Add metadata to image PDF
singleImagePdf.MetaData.Title = "Company Logo";
singleImagePdf.MetaData.Subject = "Brand Assets";
singleImagePdf.MetaData.CreationDate = DateTime.Now;
singleImagePdf.SaveAs("logo-with-metadata.pdf");
$vbLabelText   $csharpLabel

This code shows two approaches: batch conversion of multiple PNG files and single image conversion. It finds all PNG files in the assets folder and converts them to PDF using ImageToPdfConverter.ImageToPdf. The ImageBehavior property controls image positioning on the page. Finally, it saves the PDF using SaveAs.

For advanced image handling, explore embedding images from Azure Blob Storage or working with Base64 encoded images. You can also rasterize PDFs to images for reverse conversion.

What Does the Image to PDF Output Look Like?

Screenshot of IronPDF documentation webpage showing the C# PDF library homepage with features for creating and editing PDFs in .NET applications The IronPDF library homepage displays key features including HTML to PDF conversion, cross-platform support for .NET frameworks, and a prominent 'Free 30 Day Trial' button

What Advanced PDF Conversion Features Are Available?

Beyond basic HTML and image conversion, IronPDF offers many advanced features for comprehensive PDF work. The library supports async operations and parallel processing for high-performance scenarios.

Which Document Types Can I Convert to PDF?

IronPDF supports conversion from various formats:

How Can I Enhance My Generated PDFs?

After converting documents to PDF, enhance them with:

How Do I Optimize PDF Conversion Performance?

For better performance in your applications:

What About Platform-Specific Considerations?

IronPDF provides comprehensive platform support:

What Are the Key Takeaways?

This article explored PDF conversion in C# for document management and sharing. With C# and IronPDF, you can easily integrate PDF functionality into your applications. From generating PDFs to converting HTML, images, and existing documents, IronPDF offers comprehensive capabilities. The code examples showed how to convert both HTML documents and images to PDFs with minimal effort.

IronPDF's strength lies in its comprehensive features:

  • Cross-platform support for Windows, Linux, macOS, and cloud
  • Multiple conversion formats including HTML, images, DOCX, RTF, and more
  • Advanced features like digital signatures, encryption, forms, and annotations
  • Performance optimization through async operations and parallel processing
  • Pixel-perfect rendering using the Chrome rendering engine
  • Comprehensive documentation with API reference and troubleshooting guides

As shown, IronPDF simplifies complex PDF tasks, making it valuable for developers enhancing document processing in .NET applications. Whether building web applications, desktop software, or cloud services, IronPDF provides the tools for professional PDF generation. The library's feature set includes creating, editing, converting, and securing PDF documents.

To download the PDF conversion library, visit the NuGet package for IronPDF. Also, check out the HTML-to-PDF conversion tutorial with IronPDF. For hands-on learning, explore our code examples and comprehensive tutorials. IronPDF developers can choose from various licenses to suit their needs. A free trial is available. For complete pricing and licensing information, visit the IronPDF Licensing Information page. Check the changelog for latest updates and improvements.

Frequently Asked Questions

How can I convert HTML to PDF in C#?

You can use IronPDF's RenderHtmlAsPdf method to convert HTML strings into PDFs. You can also convert HTML files into PDFs using RenderHtmlFileAsPdf.

What steps are involved in setting up IronPDF in a Visual Studio project?

To set up IronPDF in a Visual Studio project, use the NuGet Package Manager to search for 'IronPDF' and install the latest package. This process integrates IronPDF into your project, allowing you to access its PDF functionalities.

What are the capabilities of IronPDF for PDF manipulation?

IronPDF offers comprehensive PDF manipulation capabilities, including text extraction, merging and splitting PDFs, rotating pages, and modifying content and annotations.

Can I convert images to PDF using IronPDF?

Yes, you can convert images to PDF using IronPDF's ImageToPdfConverter method, which supports image formats like JPEG, PNG, and BMP.

How does IronPDF maintain formatting during PDF conversion?

IronPDF ensures that original document formatting is preserved during conversion by accurately rendering HTML and image content into PDF format, thanks to its robust rendering engine.

Is there a trial version available for IronPDF?

Yes, a free trial of IronPDF is available. For detailed pricing and licensing, you can refer to the IronPDF Licensing Information page.

What programming languages are supported by IronPDF?

IronPDF supports integration with C#, VB.NET, and F# applications, providing a wide range of possibilities for developers working within the .NET ecosystem.

Where can I find more tutorials or support for using IronPDF?

Additional tutorials and support for using IronPDF are available on the IronPDF website and documentation pages, including guides on HTML-to-PDF conversion and other functionalities.

Is IronPDF fully compatible with .NET 10?

Yes — IronPDF is fully compatible with .NET 10, working seamlessly without any special configuration. It supports the latest runtime and language features in .NET 10, including cross-platform deployment and modern async-friendly APIs.

Curtis Chau
Technical Writer

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.

...

Read More