🔧 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#:
- Create or open an existing project in Visual Studio.
- Install the IronPDF library.
- Initialize the Chrome PDF Renderer object.
- Generate a PDF using the RenderHtmlAsPdf method.
- 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
- HTML to PDF conversion
- Support for CSS and JavaScript
- PDF merging and splitting
- Adding headers, footers, and watermarks
- Extracting text and images from PDFs
- 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.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
...
🍏 PDF merge: Best ways to combine PDF files on Mac
📈 24.57 Punkte
🍏 iOS / Mac OS
🐧 Creating Watermark Using HTML and CSS
📈 23.99 Punkte
🐧 Linux Tipps
📰 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
🔧 How to Extract Table From PDF in Python
📈 20.51 Punkte
🔧 Programmierung