1 Introduction to PDF Generation in C#
A key factor of ongoing C# programming is PDF creation, which gives programmers the ability to generate, edit, and manage papers dynamically. For the reason that they are consistent and portable across stages and devices, PDFs are frequently used for reports, invoicing, forms, and other file formats in a variety of sectors.
There are several methods for creating PDFs in C#, such as:
• Built-in.NET classes: These are appropriate for fundamental PDF jobs and offer basic functionality.
• Libraries: Third-party libraries provide flexibility and cutting-edge capabilities.
• Cloud-based programs: Using cloud infrastructure, APIs such as PDF Generator API offer scalable and reliable PDF creation capabilities.
2 Built-in .NET Classes for PDF Generation
Using System.Drawing Namespace for Basic PDF Operations
The System’s basic functionality for creating PDFs is included in the .NET framework.Namespace drawing. The system is not in particular made for PDFs, though. Simple PDF documents may be produced by combining Drawing with other namespaces, such as System.IO.
2.1 Code : Basic PDF Creation with System.Drawing
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.pdf";
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (iTextSharp.text.Document doc = new iTextSharp.text.Document()) {
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, fs); doc.Open();
// Create a simple text paragraph
iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph("Hello PDF!"); doc.Add(paragraph);
// Add an image
using (MemoryStream ms = new MemoryStream())
{
Bitmap bitmap = new Bitmap(200, 200);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.Clear(Color.White);
g.DrawString("Hello Image!", new Font("Arial", 20), Brushes.Black, new PointF(10, 80)); }
bitmap.Save(ms, ImageFormat.Png);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms.ToArray()); doc.Add(img);
}
doc.Close();
}
}
Console.WriteLine("PDF created successfully!");
}
}
Using the System.Drawing and iTextSharp libraries, it produce a basic PDF document with text and an image in this sample code block. Keep in mind that System.Drawing has limited access to center PDF capabilities, although it is still helpful for simple picture modification.
Use Cases Limitations | ||
1 | Complex Layouts: Creating documents with rich formatting or complex layouts is not a good use for the built-in classes. | Complex Layouts: Creating documents with rich formatting or complex layouts is not a good use for the built-in classes. |
2 | Rapid prototype: Development of features for creating PDFs. | Performance: Issues in handling huge documents or intricate graphics may arise. |
3 | Learning: Gaining an understanding of the fundamentals of creating PDFs in a safe setting. | Advanced Functionalities: Does not allow digital signatures, forms, annotations, or other sophisticated PDF capabilities. |
While the built-in.NET classes serve as a basis for basic PDF production activities, more intricate or performance-sensitive applications could require something more. Using third-party libraries or cloud-based solutions becomes crucial in these situations.
3 Library-based PDF Generation Solutions in C#
Using third-party libraries instead of the built-in.NET classes can provide greater functionality, flexibility, and convenience of use when it comes to creating PDFs in C#. In this article, we examine three well-known libraries: iTextSharp, PdfSharp, and QuestPDF, emphasizing their functions, applications, and licensing issues.
3.1 iTextSharp: Features, Usage, and Licensing Considerations
Features | |
1 | Complete PDF manipulation: Construct, edit, and remove PDF information. |
2 | Extra features: support for forms, annotations, encryption, and digital signatures. |
3 | Rich text formatting: authority over layout, color, and typefaces. |
Licensing Considerations | |
1 | AGPL License: The Affero General Public License (AGPL), which compels you to release your program as open source if you distribute it, applies to iTextSharp. |
2 | Commercial License: There is a commercial license available for proprietary applications. |
3.1.1 Code : Usage
Installing the iTextSharp library via NuGet is required in order to utilize iTextSharp. This is a simple illustration of how to use iTextSharp to create a PDF:
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
class Program
{
static void Main()
{
Document document = new Document();
PdfWriter.GetInstance(document, new FileStream("iTextSharpExample.pdf", FileMode.Create)); document.Open();
document.Add(new Paragraph("Hello PDF with iTextSharp!"));
document.Close();
Console.WriteLine("PDF created successfully with iTextSharp!");
}
}
3.2 PdfSharp: Key Features and Use Cases
An open-source library called PdfSharp makes creating PDFs easier. It lacks some of the more sophisticated capabilities of iTextSharp, but it is perfect for simple to moderately complicated manuscripts.
Features | |
1 | Usability: Easy-to-use API for producing and managing PDFs. |
2 | sketching capabilities: Enables the sketching of text, graphics, and forms. |
3 | MigraDoc integration: Use PdfSharp and MigraDoc together to create sophisticated documents. |
Use Cases | |
1 | AGPL License: The Affero General Public License (AGPL), which compels you to release your program as open source if you distribute it, applies to iTextSharp. |
2 | Commercial License: There is a commercial license available for proprietary applications. |
Licensing | |
1 | MIT License in PDFSharp is freely accessible for both personal and commercial usage under the terms of the MIT License. |
3.2.1 Code: Usage
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System;
class Program
{
static void Main()
{
PdfDocument document = new PdfDocument();
document.Info.Title = "PdfSharp Example";
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
gfx.DrawString("Hello PDF with PdfSharp!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
document.Save("PdfSharpExample.pdf");
Console.WriteLine("PDF created successfully with PdfSharp!");
}
}
3.3 QuestPDF: Overview and Unique Selling Points
QuestPDF is renowned for its easy-to-use API and capacity for producing intricate layouts. It is appropriate for many different applications and provides a contemporary method of creating PDFs.
Features | |
1 | Declarative document definition: Declarative document definition is achieved by using a fluent API. |
2 | Content is adjusted to fit various page sizes and orientations using responsive design. |
3 | Modern API: Developed with ease of use and intuitiveness in mind for contemporary C# developers. |
Unique Selling Point | |
1 | User friendly API: Even for complicated documents, the modern, user-friendly API is simple to understand and use. |
2 | Content that is responsive adjusts itself to different page widths. |
3 | Rich feature set combines strength and simplicity in its powers. |
Licensing | |
1 | Free for non-commercial usage: You can use it for educational purposes and personal projects. |
2 | Commercial License: To use a commercial license, one must have one. |
3.3.1 Code : Usage
Install the QuestPDF library using NuGet in order to utilize QuestPDF. Observe this simple example:
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using System;
class Program
{
static void Main()
{
Document.Create(container =>
{
container.Page(page =>
{
page.Size(PageSizes.A4);
page.Margin(2, Unit.Centimetre);
page.PageColor(Colors.White);
page.DefaultTextStyle(x => x.FontSize(20)); page.Header()
.Text("Hello PDF with QuestPDF!")
.SemiBold().FontSize(36).FontColor(Colors.Blue.Medium); page.Content()
.PaddingVertical(1, Unit.Centimetre)
.Column(x =>
{
x.Spacing(20);
x.Item().Text(Placeholders.LoremIpsum()); x.Item().Image(Placeholders.Image(200, 100)); });
});
})
.GeneratePdf("QuestPDFExample.pdf");
Console.WriteLine("PDF created successfully with QuestPDF!");
}
}
Selecting the best PDF creation option for your project will rely on its specifications. Though it has rigorous licensing, iTextSharp provides a wealth of capabilities for intricate needs. PdfSharp’s MIT license makes it appealing for commercial applications and appropriate for lesser jobs. With its user-friendly interface, cutting-edge functionality, and adaptable design, QuestPDF strikes a compromise.
Features/Library iTextSharp PdfSharp QuestPdf | |||
Advance features | Yes | Limited | Yes |
Ease Of Use | Moderate | Easy | Very Easy |
Licensing | AGPL (open source) / Commercial | MIT ( free for all use) | Free for non commercial/ commercial |
Use Cases | Complex documents, forms , Security | Simple Documents, forms , Reports | Responsive design , Modern Document |
4 HTML to PDF Conversion Methods in C#
It is sometimes necessary to convert HTML to PDF, particularly for web applications that need to use HTML information to create printable documents, invoices, or reports. Puppeteer Sharp and wkhtmltopdf are two well-liked C# programs for converting HTML 2 PDF; they both make use of various underlying HTML rendering technologies.
4.1 wkhtmltopdf: Overview and Integration with C#
An open-source command-line utility called wkhtmltopdf converts HTML to PDF by using the Webkit rendering engine. When generating complicated HTML, including CSS, JavaScript, and even SVG images, it is renowned for its dependability and quality.
4.1.1 Integration with C#
A.NET wrapper for wkhtmltopdf, the DinkToPdf library, may be used to combine wkhtmltopdf with a C# application. Here’s how to use and configure it:
Install Dink to Pdf
Add the DinkToPdf NuGet package to your project.
dotnet add package DinkToPdf
Download and Install wkhtmltopdf:
Download the appropriate version of wkhtmltopdf for your platform from the official site and ensure it is accessible from your application.
4.1.2 Code:
using DinkToPdf;
using DinkToPdf.Contracts;
using System;
using System.IO;
class Program
{
static void Main()
{
var converter = new SynchronizedConverter(new PdfTools());
var doc = new HtmlToPdfDocument()
{
GlobalSettings = {
ColorMode = ColorMode.Color,
Orientation = Orientation.Portrait,
PaperSize = PaperKind.A4
},
Objects = {
new ObjectSettings() {
PagesCount = true,
HtmlContent = "<h1>Hello PDF with wkhtmltopdf!</h1>",
WebSettings = { DefaultEncoding = "utf-8" },
HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]" },
FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Footer text" }
}
}
};
byte[] pdf = converter.Convert(doc);
File.WriteAllBytes("wkhtmltopdfExample.pdf", pdf);
Console.WriteLine("PDF created successfully with wkhtmltopdf!");
}
}
Sno. Benefits Drawback | ||
1 | High fidelity: Excellent rendering of HTML, including complex layouts and styles. | External dependency: Requires wkhtmltopdf to be installed and accessible. |
2 | Customizable: Various options to control the output PDF, including headers, footers, and page settings. | Performance: May be slower for very complex pages or large documents. |
4.2 Puppeteer Sharp: Using Headless Chrome/Chromium for PDF Generation
Puppeteer Sharp is a.NET version of the Puppeteer project that offers a high-level API via the DevTools Protocol for controlling headless Chrome or Chromium. By utilizing all of the capabilities of the Chrome browser, it can transform HTML to PDF with accuracy and great quality.
4.2.1 Integration with C#
To use Puppeteer Sharp for HTML to PDF conversion, follow these steps: Install Puppeteer Sharp:
Add the PuppeteerSharp NuGet package to your project.
dotnet add package PuppeteerSharp
4.2.2 Code:
using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision); using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true })) using (var page = await browser.NewPageAsync())
{
await page.SetContentAsync("<h1>Hello PDF with Puppeteer Sharp!</h1>"); await page.PdfAsync("PuppeteerSharpExample.pdf");
}
Console.WriteLine("PDF created successfully with Puppeteer Sharp!");
}
}
Sno. Benefits Drawback | ||
1 | Accurate rendering: Uses the Chrome rendering engine, ensuring compatibility with the latest web standards. | Resource-intensive: Running a headless browser can be more resource-intensive compared to other methods. |
2 | Feature-rich: Supports modern web features like CSS Grid, Flexbox, and advanced JavaScript. | Setup: Requires downloading and managing a Chrome or Chromium binary. |
For C# HTML to PDF conversion, Puppeteer Sharp and wkhtmltopdf are both effective solutions. While Puppeteer Sharp offers state-of-the-art rendering with support for contemporary web standards, wkhtmltopdf offers a simple method with dependable rendering. Your decision will be based on your unique requirements, which may include rendering fidelity, performance, and simplicity of integration.
5 Cloud-Based PDF Generation with PDF Generator API in C#
A scalable and adaptable method for producing PDFs is provided by cloud-based PDF production, which is especially helpful for applications that need for large volume processing or dynamic document creation. One such cloud-based option is the PDF Generator API, which offers strong PDF creation capabilities via a RESTful API.
Using PDF Generator API for cloud-based PDF generating offers a strong, scalable, and adaptable substitute for conventional library-based systems. By shifting labor-intensive PDF rendering operations to the cloud, it guarantees great performance and dependability while streamlining the development process. Even though library-based programs like QuestPDF, PdfSharp, and iTextSharp provide a great deal of flexibility and control, they might be more difficult to set up and maintain. Your unique demands, particularly those related to scalability, performance, simplicity of use, and cost concerns, will determine which of these strategies is best.
5.1.1 Integration with C# ( Using Rest Api )
HttpClient may be used to submit requests to the API endpoint in order to combine the PDF Generator API with a C# application. Here’s a detailed how-to:
5.1.2 Code : Settup Http Clients
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
class Program
{
private static readonly HttpClient client = new HttpClient();
static async Task Main()
{
var apiKey = "your_api_key"; // Replace with your actual API key
var apiUrl = "https://us1.pdfgeneratorapi.com/api/v4/documents/generate";
var templateId = "your_template_id"; // Replace with your actual template ID var outputFile = "output.pdf";
var payload = new
{
template = new
{
id = templateId,
data = new
{
name = "John Doe",
email = "john.doe@example.com",
date = DateTime.Now.ToString("yyyy-MM-dd")
}
},
format = "pdf",
output = "base64",
name = "Invoice 123"
};
var jsonPayload = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
HttpResponseMessage response = await client.PostAsync(apiUrl, content);
if (response.IsSuccessStatusCode)
{
var pdfBytes = await response.Content.ReadAsByteArrayAsync();
File.WriteAllBytes(outputFile, pdfBytes);
Console.WriteLine("PDF created successfully!");
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
}
}
}
Explanation :
• Http Client Initialization: Initializes an HttpClient instance for making HTTP requests. • API Key and URL: Set your API key and the API endpoint URL.
• Payload Creation: Constructs the payload with the template ID and dynamic data. • HTTP Request: Sends a POST request to the API endpoint with the payload and API key. • Response Handling: Checks the response status and writes the PDF to a file if the request is successful.
Scalability Flexibility Maintenance Advance Feature | |||
Cloud Infrastructure: Generate PDFs on a big scale without straining local resources by utilizing robust cloud servers. | Platform Agnostic: Capable of being accessed from any platform—including C# applications—that is able to send HTTP queries. | Decreased Complexity: Give the cloud service control over the more difficult aspects of creating PDFs, such formatting, rendering, and performance optimization. | Templates: For standardized and expert document design, use pre-made templates. |
Load balancing: Guarantees dependable and constant performance by automatically handling large | Dynamic material: You may easily include PDF generation from dynamic material, such as user inputs, database queries, or | Updates and Enhancements: Take advantage of the PDF generating engine’s automatic updates and enhancements | Rich Formatting: Support for complex layouts, images, |
quantities of requests. | web pages, into online applications. | without having to update any local libraries or code. | fonts, and other rich media elements |
6 Advanced PDF Generation Techniques in C#
This part will cover advanced C# PDF generating techniques, with an emphasis on asynchronous PDF production, managing complicated layouts, combining data, adding graphics, charts, and tables, and implementing form fields and interaction. With these methods, developers may produce dynamic, complex PDFs that work well for a range of uses.
6.1 Handling Complex Layouts and Data Merging
6.1.1 Complex Layouts:
Creating complex layouts involves positioning text, images, and other elements precisely within the PDF. Libraries like iTextSharp, PdfSharp, and QuestPDF offer advanced layout capabilities.
6.1.2 Code Usage with iTextSharp
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
class Program
{
static void Main()
{
Document document = new Document(PageSize.A4, 50, 50, 25, 25);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("ComplexLayout.pdf", FileMode.Create));
document.Open();
PdfPTable table = new PdfPTable(3);
table.WidthPercentage = 100;
table.AddCell("Cell 1");
table.AddCell("Cell 2");
table.AddCell("Cell 3");
document.Add(table);
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 12); cb.ShowTextAligned(Element.ALIGN_LEFT, "This is complex layout text", 200, 800, 0); cb.EndText();
document.Close();
Console.WriteLine("PDF with complex layout created successfully!");
}
}
6.2 Data Merging
Data fusion from several sources into a PDF is essential for creating customized documents, invoices, and reports. This usually entails obtaining information and integrating it into the PDF from files, databases, or APIs.
6.2.1 Code With QuestPdf
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using System.Collections.Generic;
class Program
{
static void Main()
{
var data = new
{
Title = "Monthly Report",
Items = new List<string> { "Item 1", "Item 2", "Item 3" } };
Document.Create(container =>
{
container.Page(page =>
{
page.Size(PageSizes.A4);
page.Margin(2, Unit.Centimetre);
page.PageColor(Colors.White);
page.DefaultTextStyle(x => x.FontSize(12));
page.Header()
.Text(data.Title)
.SemiBold().FontSize(24).FontColor(Colors.Blue.Medium);
page.Content()
.Column(column =>
{
foreach (var item in data.Items)
{
column.Item().Text(item);
}
});
});
})
.GeneratePdf("DataMerging.pdf");
Console.WriteLine("PDF with data merging created successfully!"); }
}
6.3 Adding Images:
Incorporating images into PDFs is essential for creating visually rich documents.
6.3.1 Code with iTextSharp
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
class Program
{
static void Main()
{
Document document = new Document();
PdfWriter.GetInstance(document, new FileStream("Images.pdf", FileMode.Create)); document.Open();
Image img = Image.GetInstance("path/to/image.jpg");
img.ScaleToFit(200f, 200f);
document.Add(img);
document.Close();
Console.WriteLine("PDF with images created successfully!");
}
}
6.4 Adding Charts:
Charts can be added to PDFs using libraries like PdfSharp or by generating charts as images and embedding them.
6.4.1 Code with PdfSharp
using PdfSharp.Charting;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System.Diagnostics;
class Program
{
static void Main()
{
PdfDocument document = new PdfDocument();
document.Info.Title = "Chart Example";
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
Chart chart = new Chart(ChartType.Column2D);
Series series = chart.SeriesCollection.AddSeries();
series.Add(new double[] { 1, 2, 3, 4, 5 });
chart.Draw(gfx, new XRect(50, 50, 400, 300));
document.Save("Chart.pdf");
Process.Start("Chart.pdf");
Console.WriteLine("PDF with chart created successfully!"); }
}
6.5 Adding Tables Tables are useful for organizing Data Structure in a manner.
6.5.1 Code with QuestPdf
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using System.Linq;
class Program
{
static void Main()
{
var data = new[]
{
new { Name = "John Doe", Age = 30, Profession = "Engineer" }, new { Name = "Jane Smith", Age = 28, Profession = "Doctor" } };
Document.Create(container =>
{
container.Page(page =>
{
page.Size(PageSizes.A4);
page.Margin(2, Unit.Centimetre);
page.PageColor(Colors.White);
page.DefaultTextStyle(x => x.FontSize(12));
page.Content()
.Table(table =>
{
table.ColumnsDefinition(columns =>
{
columns.ConstantColumn(100);
columns.RelativeColumn();
columns.ConstantColumn(100);
});
table.Header(header =>
{
header.Cell().Element(CellStyle).Text("Name"); header.Cell().Element(CellStyle).Text("Age"); header.Cell().Element(CellStyle).Text("Profession");
static IContainer CellStyle(IContainer container) =>
container.DefaultTextStyle(x =>
x.SemiBold().FontSize(12)).PaddingVertical(5).Background(Colors.Grey.Lighten2); });
foreach (var item in data)
{
table.Cell().Element(CellStyle).Text(item.Name); table.Cell().Element(CellStyle).Text(item.Age.ToString()); table.Cell().Element(CellStyle).Text(item.Profession); }
});
});
})
.GeneratePdf("Table.pdf");
Console.WriteLine("PDF with table created successfully!");
}
}
6.6 Implementing Form Fields and Interactivity
Interactive PDFs with form fields allow users to input data directly into the PDF.
6.6.1 Code with iTextSharp
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
class Program
{
static void Main()
{
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new
FileStream("InteractiveForm.pdf", FileMode.Create));
document.Open();
PdfPTable table = new PdfPTable(2);
table.AddCell("Name:");
var nameField = new TextField(writer, new Rectangle(0, 0, 200, 20), "name"); var nameCell = new PdfPCell(PdfFormField.CreateTextField(writer, true, true, 0)); nameField.FieldName = "name";
nameCell.CellEvent = new FieldCellEvent(nameField);
table.AddCell(nameCell);
document.Add(table);
document.Close();
Console.WriteLine("Interactive PDF form created successfully!");
}
public class FieldCellEvent : IPdfPCellEvent
{
private readonly TextField _field;
public FieldCellEvent(TextField field) => _field = field;
public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
PdfWriter writer = canvases[0].PdfWriter;
PdfFormField field = _field.GetTextField();
field.SetWidget(position, PdfAnnotation.HIGHLIGHT_INVERT); writer.AddAnnotation(field);
}
}
}
6.7 Asynchronous PDF Generation in C# Application
Your application’s efficiency and responsiveness can be enhanced via asynchronous programming, particularly when handling I/O-bound operations like creating PDFs.
6.7.1 Code with QuestPdf
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var document = Document.Create(container =>
{
container.Page(page =>
{
page.Size(PageSizes.A4);
page.Margin(2, Unit.Centimetre);
page.PageColor(Colors.White);
page.DefaultTextStyle(x => x.FontSize(12));
page.Header()
.Text("Asynchronous PDF Generation")
.SemiBold().FontSize(24).FontColor(Colors.Blue.Medium);
page.Content()
.Column(column =>
{
column.Item().Text("This PDF was generated asynchronously."); column.Item().Text(Placeholders.LoremIpsum());
});
});
});
await Task.Run(() => document.GeneratePdf("AsyncPDF.pdf"));
Console.WriteLine("Asynchronous PDF created successfully!");
}
}
7 Testing and Quality Assurance for C# PDF Generation
It is important to guarantee the accuracy and quality of PDF production in C# applications. The tools for confirming PDF output in C# settings and unit testing PDF creation programs are the main topics of this section.
7.1 Unit Testing PDF Generation Code in C#
Unit testing aids in confirming that each step in the PDF creation process operates as intended. Popular testing frameworks in the.NET environment that may be used for this include NUnit and xUnit.
7.1.1 Setting up project With NUnit
Make sure your project is setup with NUnit and NUnit3TestAdapter. Installing them may be done via NuGet Package Manager.
Write tests to confirm that specified text, graphics, or the right amount of pages are present in a PDF, among other components of the PDF generating process.
7.1.2 Code:
using iTextSharp.text;
using iTextSharp.text.pdf;
using NUnit.Framework;
using System.IO;
[TestFixture]
public class PdfGenerationTests
{
[Test]
public void GeneratePdf_ShouldCreatePdfWithExpectedContent() {
// Arrange
var outputPath = "TestOutput.pdf";
Document document = new Document();
PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create)); document.Open();
// Act
document.Add(new Paragraph("Hello NUnit!"));
document.Close();
// Assert
Assert.IsTrue(File.Exists(outputPath));
using (PdfReader reader = new PdfReader(outputPath))
{
string text = PdfTextExtractor.GetTextFromPage(reader, 1); Assert.IsTrue(text.Contains("Hello NUnit!"));
}
// Cleanup
File.Delete(outputPath);
}
}
This example shows how to use NUnit to create a PDF and verify its content. The test confirms that the requested text is included in the PDF file and that it was produced.
7.2 Tools for Verifying PDF Output in C# Environments
7.2.1 PDF Comparison Tools:
PDFs may be compared using programs like PDFBox and iTextSharp to confirm their structure and content.
7.2.2 Code with iTextSharp for comparing Pdf:
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;
public class PdfComparer
{
public bool ComparePdfFiles(string filePath1, string filePath2)
{
using (PdfReader reader1 = new PdfReader(filePath1))
using (PdfReader reader2 = new PdfReader(filePath2))
{
if (reader1.NumberOfPages != reader2.NumberOfPages)
return false;
for (int i = 1; i <= reader1.NumberOfPages; i++)
{
string text1 = PdfTextExtractor.GetTextFromPage(reader1, i);
string text2 = PdfTextExtractor.GetTextFromPage(reader2, i);
if (text1 != text2)
return false;
}
}
return true;
}
}
// Usage example
var comparer = new PdfComparer();
bool areEqual = comparer.ComparePdfFiles("file1.pdf", "file2.pdf");
System.Console.WriteLine($"PDF files are equal: {areEqual}");
8 C# PDF Generation Use Cases and Best Practices
Producing reports and invoicing, sometimes involve the creation of PDFs. This section examines best practices for creating scalable and maintainable PDF creation code as well as actual instances of PDF generation in C# applications.
Invoicing is a common use case for accounting and e-commerce systems. Here’s an example of how to make a basic invoice using iTextSharp:
8.1 Generating Invoices
To generate PDFs in C#, testing and quality control are essential. Unit testing frameworks such as NUnit and xUnit may be used to make sure your PDF generating code performs as intended. Furthermore, programs for confirming PDF output, like iTextSharp, can assist in comparing and validating PDF information and content. By putting these strategies into practice, you can keep your PDF creation operations dependable and high-quality.
8.1.1 Code:
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
public class InvoiceGenerator
{
public void GenerateInvoice(string outputPath, string customerName, string invoiceNumber, decimal amount)
{
Document document = new Document();
PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create));
document.Open();
document.Add(new Paragraph("Invoice"));
document.Add(new Paragraph($"Customer: {customerName}"));
document.Add(new Paragraph($"Invoice Number: {invoiceNumber}")); document.Add(new Paragraph($"Amount: ${amount}"));
PdfPTable table = new PdfPTable(2);
table.AddCell("Description");
table.AddCell("Price");
table.AddCell("Product 1");
table.AddCell("$50.00");
table.AddCell("Product 2");
table.AddCell("$30.00");
document.Add(table);
document.Close();
Console.WriteLine("Invoice generated successfully!");
}
}
// Usage example
var generator = new InvoiceGenerator();
generator.GenerateInvoice("Invoice.pdf", "John Doe", "INV-1001", 80.00m);
8.2 Generating Reports
Making reports that include tables and graphics is another typical use case. This example demonstrates how to use a table to build a basic report:
8.2.1 Code:
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
public class ReportGenerator
{
public void GenerateReport(string outputPath, string title, string[,] data) {
Document document = new Document();
PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create));
document.Open();
document.Add(new Paragraph(title));
PdfPTable table = new PdfPTable(data.GetLength(1));
for (int i = 0; i < data.GetLength(0); i++)
{
for (int j = 0; j < data.GetLength(1); j++)
{
table.AddCell(data[i, j]);
}
}
document.Add(table);
document.Close();
Console.WriteLine("Report generated successfully!");
}
}
// Usage example
var reportGenerator = new ReportGenerator();
string[,] data = new string[,]
{
{ "Header 1", "Header 2" },
{ "Row 1 Col 1", "Row 1 Col 2" },
{ "Row 2 Col 1", "Row 2 Col 2" }
};
reportGenerator.GenerateReport("Report.pdf", "Monthly Report", data);
8.3 Best Practices for Maintainable and Scalable PDF Generation Code in C#
8.3.1 Use a Modular Approach
Divide the logic for creating PDFs into classes or reusable methods. This facilitates code maintenance and extension.
8.3.2 Code:
public class PdfHelper
{
public void AddParagraph(Document document, string text)
{
document.Add(new Paragraph(text));
}
public void AddTable(Document document, string[,] data)
{
PdfPTable table = new PdfPTable(data.GetLength(1));
for (int i = 0; i < data.GetLength(0); i++)
{
for (int j = 0; j < data.GetLength(1); j++)
{
table.AddCell(data[i, j]);
}
}
document.Add(table);
} }
9 Conclusion
This extensive article has covered a wide range of C# PDF generation techniques, from sophisticated library-based and cloud-based solutions to built-in.NET classes. Every strategy has its own advantages and skills, meeting the requirements of various projects and developer tastes. C# developers may design scalable, secure, and effective PDF generating solutions that are customized for their particular applications by learning and applying these strategies.
The advantages and disadvantages of well-known libraries like iTextSharp, PdfSharp, and QuestPDF as well as HTML to PDF converters like wkhtmltopdf and Puppeteer Sharp have been covered in detail. We’ve also emphasized the benefits of adopting a cloud-based solution like PDF Generator API, stressing its affordability, scalability, and simplicity of integration.
To provide a comprehensive grasp of PDF creation in C#, advanced subjects including managing complicated layouts, adding visual components, integrating form fields, and guaranteeing security and compliance have also been discussed. To assist developers in creating reliable and effective solutions, best practices for maintainable and scalable code as well as performance optimization techniques were covered.
The skills and information in this book will help you succeed in your PDF creation duties, regardless of whether you’re using robust libraries or the flexible PDF Generator API. To further improve your PDF creation skills in C#, we advise you to try out various approaches, investigate the free trial of PDF Generator API, and make use of the wealth of documentation and customer assistance accessible.