C# PDF Generator Tutorial (HTML to PDF, Merge, Watermark. Extract)
Tags: csharp, dotnetcore, ironpdf, softwaredevelopment
Published: 2024-06-24 15:31:47

[PDF](https://en.wikipedia.org/wiki/PDF) generation is a common requirement in many applications, from generating reports to creating invoices and documentation. IronPDF is a powerful library that simplifies this process in C#. This article covers everything you need to know about using [IronPDF](https://ironpdf.com/) to generate PDFs, including installation, basic usage, advanced features, and common scenarios.

##How to Generate a PDF file in C#:

1. Create or open an existing project in Visual Studio.
2. Install the IronPDF library.
3. Initialize the Chrome PDF Renderer object.
4. Generate a PDF using the RenderHtmlAsPdf method.
5. Save the PDF file.

##Introduction to IronPDF

[IronPDF](https://ironpdf.com/) is a .NET PDF library designed to [create](https://ironpdf.com/blog/using-ironpdf/csharp-html-to-pdf-example/), [edit](https://ironpdf.com/tutorials/csharp-edit-pdf-complete-tutorial/), and [manipulate](https://ironpdf.com/how-to/extract-text-and-images/) PDF files. It integrates seamlessly with .NET applications, providing a robust set of features for generating high-quality PDF documents from various sources, such as HTML, images, and raw text.

###Key Features of IronPDF

1. [HTML to PDF](https://ironpdf.com/tutorials/html-to-pdf/) conversion
2. Support for CSS and JavaScript
3. PDF [merging](https://ironpdf.com/examples/merge-pdfs/) and [splitting](https://ironpdf.com/examples/split-pdf-pages-csharp/)
4. Adding [headers](https://ironpdf.com/examples/html-headers-and-footers/), [footers](https://ironpdf.com/examples/html-headers-and-footers/), and [watermarks](https://ironpdf.com/examples/pdf-watermarking/)
5. [Extracting](https://ironpdf.com/examples/reading-pdf-text/) text and images from PDFs
6. [Editing](https://ironpdf.com/examples/editing-pdfs/) existing PDFs

###Installing IronPDF

To get started with IronPDF, you need to install the library via NuGet. Open your project in Visual Studio and run the following command in the Package Manager Console:

```
Install-Package IronPdf
```
This command will install IronPDF with all required dependencies.

![C# PDF](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p1la97d0n21zc2vdr0uh.png)
##Basic PDF Generation

###Creating a PDF Document from HTML String

One of the most common uses of IronPDF is converting HTML to PDF. Here’s a simple example:

```
var Renderer = new ChromePdfRenderer();
var pdf = Renderer.RenderHtmlAsPdf("<h1>Hello, IronPDF!</h1>");
pdf.SaveAs("output.pdf");
```
The code initializes a ChromePdfRenderer instance to render HTML content into a PDF. It then converts the HTML string `<h1>Hello, IronPDF!</h1>` into a PDF document using the RenderHtmlAsPdf method. Finally, it saves the generated PDF file to the disk with the name output.pdf.

![PDF - Portable Document Format](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yx4zkfmb9aykxhk4od71.png)
###Creating a PDF from the URL

You can also generate a PDF directly from the URL:

```
 var Renderer = new ChromePdfRenderer();
 var pdf = Renderer.RenderUrlAsPdf("https://www.adobe.com/acrobat/about-adobe-pdf.html");
 pdf.SaveAs("pdf_from_url.pdf");
```

The code creates an instance of ChromePdfRenderer to render a webpage into a PDF. It converts the content of the URL "https://www.adobe.com/acrobat/about-adobe-pdf.html" into a PDF document using the RenderUrlAsPdf method. Finally, it saves the generated PDF to the file pdf_from_url.pdf.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ky53s6uwe9oclnmhyag9.png)
###Generate PDF file from HTML File:

You can also generate a PDF directly from the HTML file. The HTML file we will use for creating PDF is as:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1nmhibnysu3sahvc54ct.png)
Here is the code to Generate a PDF file from an HTML file. 

```
var Renderer = new ChromePdfRenderer();
var pdfFromHtmlFile = Renderer.RenderHtmlFileAsPdf("index.html"); // file path
pdfFromHtmlFile.SaveAs("pdf_from_html_file.pdf");
```
The code creates a ChromePdfRenderer instance to convert an HTML file into a PDF. It reads the content of the local HTML file index.html and converts it into a PDF document using the RenderHtmlFileAsPdf method. The resulting PDF is saved as pdf_from_html_file.pdf. A practical use case is generating a PDF  version of a locally stored webpage or report for distribution or printing. 
![Generate PDF Files - Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezi8wf6lr8p3eow18zy4.png)
##Advanced Features
###Using CSS and JavaScript

IronPDF supports CSS and JavaScript, allowing you to create styled and interactive PDFs.
```
var Renderer = new ChromePdfRenderer();
 var htmlContent = @"
 <html>
     <head>
         <style>
             h1 { color: blue; }
         </style>
     </head>
     <body>
         <h1>Hello, IronPDF with CSS!</h1>
     </body>
 </html>";
 var pdf = Renderer.RenderHtmlAsPdf(htmlContent);
 pdf.SaveAs("styled_output.pdf");
```
The code initializes a ChromePdfRenderer to convert HTML content with CSS styling into a PDF. It defines an HTML string that includes a `<style>` block to make the `<h1>` tag blue. This HTML content is rendered into a PDF using the RenderHtmlAsPdf method, and the resulting PDF is saved as styled_output.pdf. A practical use case is generating a styled PDF document, such as a report or presentation, directly from HTML and CSS.

![Generate PDF Documents](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l6awzz58jx0gbqz2u6sp.png)

###Adding Headers and Footers

IronPDF allows you to modify PDF files and add headers and footers to your PDF documents:

```
PdfDocument pdf = new PdfDocument("styled_output.pdf");
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("styled_output.pdf");
```

The code loads an existing PDF document named styled_output.pdf and creates text headers and footers with the specified center text. The header text is "This is the header!" and the footer text is "This is the footer!". These headers and footers are added to the PDF using the AddTextHeaders and AddTextFooters methods, respectively. Finally, the modified PDF is saved as styled_output.pdf.pdf. A practical use case is adding uniform headers and footers to a PDF for branding or informational purposes, such as adding company names or page numbers.

![Create PDF - Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jploa6vpkkikmihdhx29.png)
###Merging PDFs

IronPDF makes it easy to merge multiple PDFs into a single document:

```
var renderer = new ChromePdfRenderer();

var pdfdoc_a = new PdfDocument("styled_output.pdf");
var pdfdoc_b = new PdfDocument("pdf_from_url.pdf");
var merged = PdfDocument.Merge(pdfdoc_a, pdfdoc_b);

merged.SaveAs("merged_pdf.pdf");
```

In just a few lines, the code uses ChromePdfRenderer to handle PDF rendering. It loads two existing PDF documents, styled_output.pdf and pdf_from_url.pdf, and merges them into a single PDF document using PdfDocument.Merge. The combined document is then saved as merged_pdf.pdf. This approach is useful for generating PDF documents by combining content from multiple existing PDFs into one.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2hq0operrhh6yd8ppr8c.png)
###Adding Watermarks

You can add watermarks to your PDFs using IronPDF:

```
 var pdf = new PdfDocument("styled_output.pdf");
 pdf.ApplyWatermark("<h2 style='color:red'>MY WATER MARK</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
 pdf.SaveAs("watermark_output.pdf");
```

The code loads an existing PDF document named styled_output.pdf and applies a watermark with the text "MY WATER MARK" styled in red. The watermark is positioned at a 30-degree angle and aligned to the center both vertically and horizontally using IronPdf.Editing.VerticalAlignment.Middle and IronPdf.Editing.HorizontalAlignment.Center. The modified PDF is then saved as watermark_output.pdf. This process is useful for adding custom watermarks to create PDF documents with branding or ownership information.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fymfbxo6o1g6bycppjx2.png)
###Extracting Text from PDF

IronPDF can also extract text and images from existing PDFs.  The following code snippet demonstrates how IronPDF can extract all text content from a PDF file:

```
 var pdf = new PdfDocument("styled_output.pdf");
 var text = pdf.ExtractAllText();
 Console.WriteLine(text);
```

The code initializes a PdfDocument object by loading the PDF file named "styled_output.pdf". It then extracts all textual content from the PDF using the ExtractAllText method and stores it in the variable text. Finally, it prints the extracted text to the console. This process showcases how IronPDF can programmatically retrieve and manipulate text content from PDF documents.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ortehhvx6y7qrt2oj3k.png)
###Extract Image from a PDF document:

The following code snippet demonstrates how IronPDF can extract all images from a PDF file:

```
var pdf = new PdfDocument("pdf_from_url.pdf");
          
var images = pdf.ExtractAllImages();
for (int i = 0; i < images.Count; i++)
{
    // Export the extracted images
    images[i].SaveAs($"PDF_Images/image{i}.png");
}
```

The code initializes a PdfDocument object by loading a PDF file from a URL ("pdf_from_url.pdf"). It then extracts all images embedded within the PDF using the ExtractAllImages method. Each extracted image is saved as a PNG file in a directory named "PDF_Images", with filenames numbered sequentially. This demonstrates how IronPDF can automate the extraction and export of images from PDF documents for further processing or analysis.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqtndsvsredseenuoc9j.png)
##Conclusion:

In conclusion, IronPDF provides a robust solution for C# PDF generation, offering a comprehensive set of tools to create, edit, and manipulate PDF documents directly from .NET applications. From converting HTML to PDF and merging multiple PDFs to adding headers, footers, watermarks, and extracting content, IronPDF simplifies complex tasks with ease and efficiency. It stands as an essential C# PDF generator library, enabling developers to enhance their applications with professional-grade PDF functionality due to its seamless integration and powerful features.

For developers looking to explore its capabilities, IronPDF offers [a free trial](https://ironpdf.com/#trial-license), allowing them to evaluate its features and integration within their projects. Whether for generating reports, creating invoices, or archiving documents, IronPDF's versatility makes it a valuable tool in various scenarios. Additionally, commercial [licenses](https://ironpdf.com/licensing/) are available for those needing full access to advanced features and support.