Lädt...


🔧 C# PDF Generator Tutorial (HTML to PDF, Merge, Watermark. Extract)


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

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 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 is a .NET PDF library designed to create, edit, and manipulate 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 conversion
  2. Support for CSS and JavaScript
  3. PDF merging and splitting
  4. Adding headers, footers, and watermarks
  5. Extracting text and images from PDFs
  6. Editing 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

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

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

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
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

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

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

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

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

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

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

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, 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 are available for those needing full access to advanced features and support.

...

🔧 C# PDF Generator Tutorial (HTML to PDF, Merge, Watermark. Extract)


📈 82.65 Punkte
🔧 Programmierung

🍏 Batch TIFF & PDF Converter 4.4.6.3.789 - Merge, resize, extract, and convert PDF and TIFF documents.


📈 39.09 Punkte
🍏 iOS / Mac OS

🍏 PDF Split and Merge 1.5 - Split,Merge & Edit PDF Anytime


📈 37.18 Punkte
🍏 iOS / Mac OS

🍏 CM PDF Merge NX 5.1.5.3.797 - Fast, easy-to-use merge of two or more PDF files.


📈 37.18 Punkte
🍏 iOS / Mac OS

🔧 How to Extract Text From PDF in C# (Beginner Tutorial)


📈 29.63 Punkte
🔧 Programmierung

🔧 How to Merge PDF Files in C# (Developer Tutorial)


📈 27.71 Punkte
🔧 Programmierung

🔧 How to create navigation menu with HTML CSS step by step | web design tutorial | HTML CSS tutorial


📈 27.51 Punkte
🔧 Programmierung

🎥 How To Use META AI (Complete Tutorial) Beginner Tutorial (LLAMA 3 Tutorial)


📈 27.36 Punkte
🎥 Video | Youtube

🍏 CM PDF & TIFF Page Extractor 4.3.7.3.682 - Extract and save PDF pages in various image formats.


📈 26.49 Punkte
🍏 iOS / Mac OS

🔧 Fast-Forward merge VS Three-Way Recursive merge


📈 25.21 Punkte
🔧 Programmierung

🕵️ CVE-2024-38986 | 75lb deep-merge 1.1.1 Merge Method prototype pollution


📈 25.21 Punkte
🕵️ Sicherheitslücken

🔧 How to Resolve Merge Conflicts Using the Merge Editor Feature on VS Code


📈 25.21 Punkte
🔧 Programmierung

🕵️ Medium CVE-2020-28499: Merge project Merge


📈 25.21 Punkte
🕵️ Sicherheitslücken

🕵️ Merge Package up to 1.1 merge.recursive Object denial of service


📈 25.21 Punkte
🕵️ Sicherheitslücken

📰 Versionsverwaltung GitLab 12.1 bietet parallele Merge Trains und private Merge Requests


📈 25.21 Punkte
📰 IT Nachrichten

📰 How to merge all PDF files into one PDF in Linux


📈 24.57 Punkte
📰 IT Security Nachrichten

🍏 PDF merge: Best ways to combine PDF files on Mac


📈 24.57 Punkte
🍏 iOS / Mac OS

🐧 How To Merge PDF Files? Easy Steps To Combine PDF Files


📈 24.57 Punkte
🐧 Linux Tipps

📰 How To Combine and Merge all PDF in One PDF File


📈 24.57 Punkte
📰 IT Security Nachrichten

🐧 Creating Watermark Using HTML and CSS


📈 23.99 Punkte
🐧 Linux Tipps

🍏 How to extract text from images on Mac [Video tutorial]


📈 23.65 Punkte
🍏 iOS / Mac OS

🕵️ Medium CVE-2019-15138: Html-pdf project Html-pdf


📈 21.23 Punkte
🕵️ Sicherheitslücken

🎥 Ellevenlabs New MUSIC GENERATOR STUNS The MUSIC INDUSTRY! (EllevenLabs Music Generator)


📈 20.9 Punkte
🎥 Video | Youtube

📰 Reverse-Shell-Generator - Hosted Reverse Shell Generator With A Ton Of Functionality


📈 20.9 Punkte
📰 IT Security Nachrichten

🕵️ TSP Dork generator v16.1|HQ Dork generator - Now with custom dork types


📈 20.9 Punkte
🕵️ Hacking

🕵️ TSP Dork generator v16.1|HQ Dork generator - Now with custom dork types


📈 20.9 Punkte
🕵️ Hacking

📰 Web-Traffic-Generator - A Quick And Dirty HTTP/S "Organic" Traffic Generator


📈 20.9 Punkte
📰 IT Security Nachrichten

📰 How to extract a single page from PDF files


📈 20.51 Punkte
🖥️ Betriebssysteme

🪟 How to extract a single page from PDF files


📈 20.51 Punkte
🪟 Windows Tipps

🔧 Extract Text From PDF in C# Using iTextSharp VS ComPDFKit


📈 20.51 Punkte
🔧 Programmierung

🔧 How to Extract Table From PDF in Python


📈 20.51 Punkte
🔧 Programmierung

matomo