USING IRONPDF

C# Generate PDF 7 Libraries Comparison (Free & Paid Tools)

Published December 16, 2024
Share:

The C# generate PDF functionality is critical for many modern applications, from creating reports to invoicing systems. In this article, we will explore six popular ways to generate PDF files using C#, highlighting both code-based libraries, such as IronPDF, and online API's and tools. Whether you need to generate PDF file dynamically in a web app or simply create PDF files from existing documents, these tools have you covered.

1. IronPDF

Broken image Add from Pixabay, select from your files or drag and drop an image here.

IronPDF is a premium .NET PDF library designed for developers who need high-quality HTML to PDF file conversion. IronPDF uses a Chromium-based rendering engine to ensure precise conversions, making it a perfect choice for web applications that want to convert HTML pages or web-based reports into PDF files in C#. The tool is known for its robust handling of existing PDF documents and provides features to edit, merge, or split PDFs.

IronPDF integrates easily into C# projects through NuGet Package Manager, and with just a few lines of code, you can start generating PDF documents. It’s a versatile tool for both dynamic HTML content and server-generated PDF file outputs.

Key Features

  • HTML to PDF Conversion: IronPDF excels at converting complex HTML pages, including support for JavaScript execution and modern CSS, directly into a PDF. It uses a Chromium-based rendering engine, ensuring that the output looks identical to what you'd see in a web browser.
  • PDF Manipulation: IronPDF allows you to merge, split, and modify existing PDF documents easily.
  • Advanced Styling Options: IronPDF supports external stylesheets, custom fonts, and JavaScript, enabling you to craft highly styled documents. It’s perfect for invoices, reports, and web-based content.
  • Security Features: IronPDF provides features for adding password protection, digital signatures, and setting permissions to restrict actions like printing, copying, or editing the PDF.
  • Form Handling: IronPDF allows developers to programmatically create, fill, and read PDF forms, making it a good fit for applications that need user input in PDF format.
  • NuGet Package Manager: Easily install and manage through the package manager console in Visual Studio.

Code Example

using IronPdf;
class Program
{
    static void Main()
    {
        string html = "<h1>Hello, World!</h1><p>This PDF is generated from HTML.</p>";
        ChromePdfRenderer renderer = new ChromePdfRenderer(); // Create an instance of ChromePdfRenderer
        PdfDocument pdf = renderer.RenderHtmlAsPdf(html); // Render the HTML as a PDF document
        pdf.SaveAs("Generated.pdf"); // Save the PDF to a specified file
    }
}
using IronPdf;
class Program
{
    static void Main()
    {
        string html = "<h1>Hello, World!</h1><p>This PDF is generated from HTML.</p>";
        ChromePdfRenderer renderer = new ChromePdfRenderer(); // Create an instance of ChromePdfRenderer
        PdfDocument pdf = renderer.RenderHtmlAsPdf(html); // Render the HTML as a PDF document
        pdf.SaveAs("Generated.pdf"); // Save the PDF to a specified file
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main()
		Dim html As String = "<h1>Hello, World!</h1><p>This PDF is generated from HTML.</p>"
		Dim renderer As New ChromePdfRenderer() ' Create an instance of ChromePdfRenderer
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html) ' Render the HTML as a PDF document
		pdf.SaveAs("Generated.pdf") ' Save the PDF to a specified file
	End Sub
End Class
VB   C#
  1. Namespace Import: using IronPdf; imports the IronPDF library to access its classes and methods.

  2. HTML String: The variable HTML contains the HTML content you want to convert to PDF.
  3. Renderer Instance: new ChromePdfRenderer(); creates an instance of the HtmlToPdf class, which provides methods for rendering HTML content into PDF format.

  4. Render PDF: PdfDocument PDF = renderer.RenderHtmlAsPdf(html); converts the HTML string into a PDF document.

  5. Save PDF: pdf.SaveAs("Generated.pdf"); saves the generated PDF to the specified file path.

Pros

  • Excellent rendering quality for web content.
  • Robust support for forms, hyperlinks, and bookmarks.

Cons

  • Licensing fees can be a consideration for larger projects.
  • More advanced features may require deeper learning.

2. iTextSharp

C# Generate PDF 7 Libraries Comparison (Free & Paid Tools): Figure 2

iTextSharp is a well-established .NET PDF library that provides extensive functionality for creating and editing PDF files. It is widely used in industries like finance and legal, where documents must be customized and secured. iTextSharp allows you to create PDF files from scratch, fill in forms, and modify PDF files, providing extensive control over the document's content. It is particularly useful for enterprise applications that need to generate PDF files with precise layouts and dynamic data, such as invoices or contracts.

Key Features

  • Full PDF Creation Capabilities: iTextSharp makes it easy to create a PDF file in C# from scratch, allowing developers to add text, images, tables, and vector graphics. It provides complete control over document layout, including the ability to define page sizes, margins, and metadata.
  • Form Filling: A significant strength of iTextSharp is its ability to handle PDF forms (AcroForms). You can create forms with various input fields and later programmatically fill them, a feature useful in automated document generation workflows.
  • XML to PDF Conversion: iTextSharp has robust support for converting XML data to PDF using XFA (XML Forms Architecture). This is particularly valuable in industries where XML data needs to be formatted into standard forms or reports.
  • PDF Security: iTextSharp includes advanced features such as adding encryption, digital signatures, and watermarks to ensure document authenticity and protect sensitive data.
  • Text Extraction and Manipulation: You can extract text from existing PDFs, rearrange document content, or manipulate page elements, making it useful for post-processing documents or generating summary reports from complex PDFs.

Code Example

using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Mapping;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using Voodoo;
namespace Helpers
{
    public class PdfGenerator
    {
        public static Byte[] GeneratePdfFromFragment(string htmlFragment)
        {
            var html = string.Format(@"
            <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
            <head>
            <style type='text/css'>
            table,td {{border: 1px solid black;}}
            div {{ white-space: nowrap; padding: 2px;}}
            table{{ border-collapse: collapse; width: 100%; empty-cells: show;}}
            body table {{font-size: 50%;}}
            th {{width:500px; height: 28px;}}
            td {{width:300px; height: 28px;}}
            </style>
            </head><body>{0}</body></html>", htmlFragment);
          return generate(html);
        }
        public static Byte[] GeneratePdfFromPage(string htmlPage)
        {
            return generate(htmlPage);
        }
        private static Byte[] generate (string html)
        {
            using (var memoryStream = new MemoryStream())
            {
                var pdfDocument = new Document(PageSize.LETTER);
                var pdfWriter = PdfWriter.GetInstance(pdfDocument, memoryStream);
                pdfDocument.Open();
                using (var fw = new StringReader(html))
                {                    
                    XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, fw);
                    pdfDocument.Close();
                    fw.Close();
                }
                return memoryStream.ToArray();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Mapping;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using Voodoo;
namespace Helpers
{
    public class PdfGenerator
    {
        public static Byte[] GeneratePdfFromFragment(string htmlFragment)
        {
            var html = string.Format(@"
            <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
            <head>
            <style type='text/css'>
            table,td {{border: 1px solid black;}}
            div {{ white-space: nowrap; padding: 2px;}}
            table{{ border-collapse: collapse; width: 100%; empty-cells: show;}}
            body table {{font-size: 50%;}}
            th {{width:500px; height: 28px;}}
            td {{width:300px; height: 28px;}}
            </style>
            </head><body>{0}</body></html>", htmlFragment);
          return generate(html);
        }
        public static Byte[] GeneratePdfFromPage(string htmlPage)
        {
            return generate(htmlPage);
        }
        private static Byte[] generate (string html)
        {
            using (var memoryStream = new MemoryStream())
            {
                var pdfDocument = new Document(PageSize.LETTER);
                var pdfWriter = PdfWriter.GetInstance(pdfDocument, memoryStream);
                pdfDocument.Open();
                using (var fw = new StringReader(html))
                {                    
                    XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, fw);
                    pdfDocument.Close();
                    fw.Close();
                }
                return memoryStream.ToArray();
            }
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Data.Entity.Core.Mapping
Imports System.IO
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml
Imports Voodoo
Namespace Helpers
	Public Class PdfGenerator
		Public Shared Function GeneratePdfFromFragment(ByVal htmlFragment As String) As Byte()
			Dim html = String.Format("
            <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
            <head>
            <style type='text/css'>
            table,td {{border: 1px solid black;}}
            div {{ white-space: nowrap; padding: 2px;}}
            table{{ border-collapse: collapse; width: 100%; empty-cells: show;}}
            body table {{font-size: 50%;}}
            th {{width:500px; height: 28px;}}
            td {{width:300px; height: 28px;}}
            </style>
            </head><body>{0}</body></html>", htmlFragment)
		  Return generate(html)
		End Function
		Public Shared Function GeneratePdfFromPage(ByVal htmlPage As String) As Byte()
			Return generate(htmlPage)
		End Function
		Private Shared Function generate(ByVal html As String) As Byte()
			Using memoryStream As New MemoryStream()
				Dim pdfDocument = New Document(PageSize.LETTER)
				Dim pdfWriter = PdfWriter.GetInstance(pdfDocument, memoryStream)
				pdfDocument.Open()
				Using fw = New StringReader(html)
					XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, fw)
					pdfDocument.Close()
					fw.Close()
				End Using
				Return memoryStream.ToArray()
			End Using
		End Function
	End Class
End Namespace
VB   C#
  1. GeneratePdfFromFragment: Takes an HTML fragment (like a partial HTML document) and converts it to a full HTML structure by wrapping it in a basicandtemplate. It then calls the internal generate method.
  2. GeneratePdfFromPage: Accepts a full HTML page and directly calls the generate method.

    1. generate: This method handles the conversion of HTML to PDF.

      • It initializes a MemoryStream to hold the generated PDF in memory.

      • It creates an iTextSharp Document object with Letter-sized pages.
    • The XMLWorkerHelper parses the HTML content and writes it into the PDF document using the provided StringReader.

Pros

  • Highly customizable with a rich feature set.
  • Extensive documentation and community support.

Cons

  • iTextSharp (which is free for personal use but requires a commercial license for larger-scale projects) may have limitations handling complex CSS or JavaScript.
  • XMLWorker (which is used here) is a deprecated tool from iTextSharp for parsing HTML/CSS. iText7 (the newer version of iText) uses a more robust HTML parser, pdfHTML, that might provide better support for modern web standards.
  • Steeper learning curve for beginners.

3. PDFsharp

C# Generate PDF 7 Libraries Comparison (Free & Paid Tools): Figure 3

PDFSharp is a lightweight, open-source .NET PDF library ideal for basic PDF creation tasks. If your application requires only simple operations like adding text, images, or tables, PdfSharp is an easy-to-use option for generating PDF documents in C#. It lacks advanced features like HTML to PDF conversion but shines in its simplicity for generating small to medium-sized PDF files in C#.

Key Features

  • Basic PDF Creation: Simple and easy-to-use API for drawing text and graphics. Ideal for creating straightforward documents.
  • Document Manipulation: Merge and modify existing PDFs with ease, allowing for flexibility in document management.
  • Drawing and Graphics Support: PDFsharp provides a set of tools for drawing on PDF pages, including lines, rectangles, and other vector graphics. It also supports embedding images into your PDFs.
  • Free and Open-Source: PDFsharp is completely free for commercial and non-commercial use, making it an attractive option for small businesses and developers working on open-source projects.

Code Example

using PdfSharp.Pdf;
using PdfSharp.Drawing;
class Program
{
    static void Main()
    {
        // Create a new PDF document
        PdfDocument document = new PdfDocument();
        document.Info.Title = "Created with PdfSharp";
        // Add a page to the document
        PdfPage page = document.AddPage();
        // Create an XGraphics object to draw on the page
        XGraphics gfx = XGraphics.FromPdfPage(page);
        // Set a font to use for drawing text
        XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
        // Draw the text on the PDF page
        gfx.DrawString("Hello, World!", font, XBrushes.Black, 
            new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
        // Save the document to disk
        document.Save("Generated.pdf");
    }
}
using PdfSharp.Pdf;
using PdfSharp.Drawing;
class Program
{
    static void Main()
    {
        // Create a new PDF document
        PdfDocument document = new PdfDocument();
        document.Info.Title = "Created with PdfSharp";
        // Add a page to the document
        PdfPage page = document.AddPage();
        // Create an XGraphics object to draw on the page
        XGraphics gfx = XGraphics.FromPdfPage(page);
        // Set a font to use for drawing text
        XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
        // Draw the text on the PDF page
        gfx.DrawString("Hello, World!", font, XBrushes.Black, 
            new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
        // Save the document to disk
        document.Save("Generated.pdf");
    }
}
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Friend Class Program
	Shared Sub Main()
		' Create a new PDF document
		Dim document As New PdfDocument()
		document.Info.Title = "Created with PdfSharp"
		' Add a page to the document
		Dim page As PdfPage = document.AddPage()
		' Create an XGraphics object to draw on the page
		Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
		' Set a font to use for drawing text
		Dim font As New XFont("Verdana", 20, XFontStyle.Bold)
		' Draw the text on the PDF page
		gfx.DrawString("Hello, World!", font, XBrushes.Black, New XRect(0, 0, page.Width, page.Height), XStringFormats.Center)
		' Save the document to disk
		document.Save("Generated.pdf")
	End Sub
End Class
VB   C#
  • PdfDocument: Represents the entire PDF document. You can add pages, set metadata, and manipulate the document.
  • PdfPage: Represents a single page within the document. New pages are added using the AddPage method.
  • XGraphics: This is used to draw text, images, and shapes on a specific page. It’s similar to GDI+ in .NET.
  • XFont: Specifies the font and style for text rendering. In this example, "Verdana" is used with bold styling.
  • DrawString: Draws the specified string at the defined position within the document.

Pros

  • Free and open-source with no licensing restrictions.
  • Simple and lightweight, making it easy to get started with basic PDF generation.
  • Works well for projects that don’t require complex features.

Cons

  • Limited functionality compared to other libraries.
  • No native support for converting HTML to PDF.

4. Syncfusion PDF Library

C# Generate PDF 7 Libraries Comparison (Free & Paid Tools): Figure 4

Syncfusion PDF Library is a high-performance, comprehensive tool designed for enterprises that need to work with PDFs in a wide range of applications. It’s part of the broader Syncfusion suite, which offers libraries for a variety of formats and platforms. The PDF library stands out because of its extensive feature set that goes beyond simple document creation and allows for detailed manipulation, including form filling, digital signatures, and document security.

Key Features

  • Comprehensive PDF API: Syncfusion PDF is capable of generating highly customized PDFs, including those with complex layouts, embedded fonts, and high-resolution images. It provides detailed control over all aspects of PDF creation, from page formatting to advanced layout options.
  • Form Processing: The library excels at creating, filling, and extracting data from interactive PDF forms (AcroForms). This is useful for creating fillable PDFs for user input, automating data entry, or processing filled forms.
  • Digital Signatures and Encryption: Syncfusion offers robust security features, including the ability to encrypt PDF documents, add password protection, and apply digital signatures. These features are crucial for industries like healthcare and legal services that require document authenticity and security.Code Example
using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
class Program
{
    static void Main()
    {
        //Create a new PDF document.
    PdfDocument document = new PdfDocument();
    //Add a page to the document.
    PdfPage page = document.Pages.Add();
    //Create PDF graphics for the page.
    PdfGraphics graphics = page.Graphics;
    //Set the standard font.
    PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
    //Draw the text.
    graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));
    //Save the document.
    document.Save("Output.pdf");
    //Close the document.
    document.Close(true);
    }
}
using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
class Program
{
    static void Main()
    {
        //Create a new PDF document.
    PdfDocument document = new PdfDocument();
    //Add a page to the document.
    PdfPage page = document.Pages.Add();
    //Create PDF graphics for the page.
    PdfGraphics graphics = page.Graphics;
    //Set the standard font.
    PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
    //Draw the text.
    graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));
    //Save the document.
    document.Save("Output.pdf");
    //Close the document.
    document.Close(true);
    }
}
Imports Syncfusion.Pdf
Imports Syncfusion.Pdf.Parsing
Imports Syncfusion.Pdf.Graphics
Imports Syncfusion.Pdf.Grid
Friend Class Program
	Shared Sub Main()
		'Create a new PDF document.
	Dim document As New PdfDocument()
	'Add a page to the document.
	Dim page As PdfPage = document.Pages.Add()
	'Create PDF graphics for the page.
	Dim graphics As PdfGraphics = page.Graphics
	'Set the standard font.
	Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 20)
	'Draw the text.
	graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, New PointF(0, 0))
	'Save the document.
	document.Save("Output.pdf")
	'Close the document.
	document.Close(True)
	End Sub
End Class
VB   C#
  • PdfDocument: Represents the PDF document. You can add pages, set properties, and manipulate its content.
  • PdfPage: Represents a page within the PDF document.
  • PdfFont: Defines the font for rendering text. In this case, a standard Helvetica font is used.
  • DrawString: Draws the specified string onto the PDF page at the given coordinates.

Pros

  • Rich feature set, suitable for creating complex PDFs.
  • Professional support and documentation make it ideal for large-scale applications.
  • Supports advanced PDF capabilities like form filling, encryption, and annotations.

Cons

  • Licensing fees are relatively high for commercial use.
  • Complex API, which may require time to master.

5. PDFShift (Online Tool)

C# Generate PDF 7 Libraries Comparison (Free & Paid Tools): Figure 5

PDFShift is a cloud-based service designed to convert HTML into PDF files. It integrates smoothly with C# applications via its API, allowing you to convert dynamically generated HTML web pages into professional-quality PDFs. PDFShift is particularly useful for web developers who want to generate PDFdocuments on demand from HTML content, such as invoices or reports. Since PDFShift operates entirely through its REST API, you can send just a few lines of HTML to the service and receive a downloadable PDF file in return. It’s a simple, scalable solution for web-based PDF file generation.

Key Features

  • HTML to PDF Conversion: PDFShift excels at converting HTML documents into high-quality PDFs. It handles complex CSS styles, JavaScript, and responsive design layouts, ensuring that your web page looks exactly the same in PDF format.
  • API Integration: The PDFShift API is designed for seamless integration into web applications. It’s straightforward to use: simply send an HTTP POST request with the HTML content, and the service returns a PDF document.
  • Customization Options: PDFShift allows for customization of the generated PDF, including setting page size, orientation, margins, and headers/footers. You can also add dynamic content to the headers and footers, such as page numbers or document metadata.

How It Works

  • Send a POST request with HTML content to the PDFShift API endpoint.
  • Receive the generated PDF in response, ready to download or save.

Example Code

using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            string htmlContent = "<h1>Hello, World!</h1><p>This is generated using PDFShift API.</p>";
            var content = new StringContent(htmlContent, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync("https://api.pdfshift.io/v3/convert", content);
            byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
            System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
        }
    }
}
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            string htmlContent = "<h1>Hello, World!</h1><p>This is generated using PDFShift API.</p>";
            var content = new StringContent(htmlContent, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync("https://api.pdfshift.io/v3/convert", content);
            byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
            System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
        }
    }
}
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		Using client As New HttpClient()
			Dim htmlContent As String = "<h1>Hello, World!</h1><p>This is generated using PDFShift API.</p>"
			Dim content = New StringContent(htmlContent, Encoding.UTF8, "application/json")
			Dim response As HttpResponseMessage = Await client.PostAsync("https://api.pdfshift.io/v3/convert", content)
			Dim pdfBytes() As Byte = Await response.Content.ReadAsByteArrayAsync()
			System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes)
		End Using
	End Function
End Class
VB   C#
  • HttpClient: Sends the HTML content as a POST request to the PDFShift API.
  • PostAsync: Sends the request to the API, which processes the HTML and returns the PDF.
  • ReadAsByteArrayAsync: Reads the PDF response as a byte array, which can then be saved as a file.

Pros

  • Simple API with minimal setup.
  • Ideal for web applications that require dynamic HTML to PDF conversion.
  • No need to manage PDF libraries or servers.

Cons

  • Limited to HTML to PDF conversion; doesn’t support more complex PDF features.
  • Requires an internet connection and incurs costs after a certain usage threshold.

6. DocRaptor (Online Tool)

C# Generate PDF 7 Libraries Comparison (Free & Paid Tools): Figure 6

DocRaptor is another powerful API-based PDF generation service that converts HTML and CSS into high-quality PDFs. It is known for its excellent rendering of HTML documents, particularly in handling complex CSS styles, media queries, and web fonts. This makes DocRaptor a great choice for generating professional-looking documents like reports, invoices, and eBooks, directly from HTML templates.

Key Features

  • HTML and CSS Support: Converts HTML documents with complex CSS styles, including media queries and fonts.
  • API Integration: REST API for seamless integration into web applications.
  • Custom Headers/Footers: Add dynamic headers and footers, including page numbers and custom formatting.
  • PDF Security: Supports encryption and password protection.

How It Works

  • Send a POST request to the DocRaptor API with HTML content.
  • Customize the PDF output with parameters for page size, margins, headers, and footers.
  • Receive the generated PDF in response.

Example Code

using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            string apiKey = "YOUR_API_KEY";
            string htmlContent = "<h1>Professional Report</h1><p>Generated using DocRaptor API.</p>";
            string jsonData = $"{{\"test\": true, \"document_content\": \"{htmlContent}\", \"name\": \"Generated.pdf\", \"document_type\": \"pdf\"}}";
            var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync($"https://docraptor.com/docs?user_key={apiKey}", content);
            byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
            System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
        }
    }
}
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            string apiKey = "YOUR_API_KEY";
            string htmlContent = "<h1>Professional Report</h1><p>Generated using DocRaptor API.</p>";
            string jsonData = $"{{\"test\": true, \"document_content\": \"{htmlContent}\", \"name\": \"Generated.pdf\", \"document_type\": \"pdf\"}}";
            var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync($"https://docraptor.com/docs?user_key={apiKey}", content);
            byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
            System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
        }
    }
}
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		Using client As New HttpClient()
			Dim apiKey As String = "YOUR_API_KEY"
			Dim htmlContent As String = "<h1>Professional Report</h1><p>Generated using DocRaptor API.</p>"
			Dim jsonData As String = $"{{""test"": true, ""document_content"": ""{htmlContent}"", ""name"": ""Generated.pdf"", ""document_type"": ""pdf""}}"
			Dim content = New StringContent(jsonData, Encoding.UTF8, "application/json")
			Dim response As HttpResponseMessage = Await client.PostAsync($"https://docraptor.com/docs?user_key={apiKey}", content)
			Dim pdfBytes() As Byte = Await response.Content.ReadAsByteArrayAsync()
			System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes)
		End Using
	End Function
End Class
VB   C#
  • API Key: You must provide an API key for authentication when using DocRaptor. Replace "YOUR_API_KEY" with your actual key.
  • JsonData: This JSON string contains the HTML content, document name, and type (PDF in this case).
  • PostAsync: Sends the HTML content and parameters to the DocRaptor API for PDF generation.

Pros

  • High-quality rendering with full support for HTML, CSS, and JavaScript.
  • Advanced customization options for document layout and security.
  • No need to maintain PDF generation libraries or infrastructure.

Cons

  • Paid service after exceeding a free usage limit.
  • Dependent on internet connectivity.

7. Code-Free Online Tools

If you don’t want to write code or need a quick solution for generating PDFs, several online tools allow you to create PDFs quickly and easily. Here are a few notable options:

7.1. Smallpdf

C# Generate PDF 7 Libraries Comparison (Free & Paid Tools): Figure 7

Smallpdf is an online platform offering a variety of PDF-related tools, including the ability to create PDFs from a wide range of file formats. It’s designed for users who want a simple drag-and-drop interface without needing to write code. Smallpdf is widely used for quick file conversions, such as turning Word documents, Excel sheets, or images into PDFs. It also provides tools for merging, compressing, and splitting PDFs, making it a versatile tool for basic PDF tasks.

Key Features

  • File Conversion: Smallpdf supports converting Word, Excel, PowerPoint, and image files (JPG, PNG) into PDF. This makes it ideal for users who need to create PDFs from a variety of document types quickly.
  • Merging and Splitting PDFs: Smallpdf offers a simple interface for merging multiple PDFs into a single file or splitting a PDF into individual pages.
  • Cloud Storage Integration: You can easily upload files from Google Drive or Dropbox and save the converted PDFs back to these platforms, streamlining file management.
  • PDF Editing Tools: In addition to conversion, Smallpdf provides basic PDF editing tools to edit any existing PDF document, such as adding annotations, filling out forms, and signing documents digitally.

Pros

  • Very easy to use for non-developers.
  • Free for basic usage with options to upgrade for more features.
  • Offers a wide variety of PDF-related tools like merging, splitting, and compressing PDFs.

Cons

  • Limited customization compared to code-based solutions.
  • Free tier may have some feature restrictions.

7.2. PDFescape

C# Generate PDF 7 Libraries Comparison (Free & Paid Tools): Figure 8

PDFescape is an easy-to-use web-based PDF editor that allows users to create, edit, and view PDFs without the need for installing any software. It’s a great tool for those who need to make quick edits to PDFs, such as filling out forms, adding text annotations, or inserting images. PDFescape also offers tools for creating new PDFs from scratch, making it a flexible choice for basic document creation.

Key Features

  • Form Filling and Editing: PDFescape excels in handling PDF forms. Users can easily fill out forms or edit existing fields in PDF documents, which is useful for contracts, applications, and other forms.
  • Basic PDF Creation: For users looking to create PDFs from scratch, PDFescape offers tools to add text, shapes, images, and form fields. This is useful for creating simple documents like letters or forms.
  • Annotations and Comments: You can add comments, sticky notes, and other annotations to existing PDFs, making PDFescape a great tool for document review and collaboration.
  • No Installation Required: As a web-based tool, PDFescape works entirely in your browser, so there’s no need to install any software. This makes it ideal for users who need quick access to PDF tools on the go.

Pros

  • Simple to use for non-technical users.
  • Free tier for basic PDF creation and editing.
  • Suitable for minor PDF editing tasks.

Cons

  • Lacks advanced features for complex PDF creation.
  • Limited design and formatting options.

7.3. PDF Candy

C# Generate PDF 7 Libraries Comparison (Free & Paid Tools): Figure 9

PDF Candy is a suite of free online PDF tools that covers a wide range of PDF-related tasks, from file conversion to editing. It’s an excellent choice for users who need to perform quick PDF operations without registering for an account or installing software. PDF Candy supports converting various file types, such as Word documents, images, and text files, into PDFs. It also provides tools for merging, splitting, and compressing PDFs.

Key Features

  • Wide Range of Conversion Options: PDF Candy can convert multiple file formats, including Word documents, images, and text files, into PDFs. This makes it a flexible tool for handling different types of content.
  • Merging and Splitting PDFs: The platform allows users to merge multiple PDFs into one or split large PDFs into smaller, more manageable files.
  • File Privacy: PDF Candy automatically deletes files from its servers after a short period, ensuring that your documents remain private.
  • Free to Use: Most tools on PDF Candy are free to use without registration, making it accessible to a wide audience. However, it also offers a premium version with more advanced features for those who need more frequent use or larger file conversions.

Pros

  • Easy to use and completely free for most users.
  • Supports a variety of file types for conversion to PDF.
  • No account registration required for basic usage.

Cons

  • Limited advanced PDF customization features.
  • Some tools may have restrictions on file size or conversion complexity.

Conclusion

C# Generate PDF 7 Libraries Comparison (Free & Paid Tools): Figure 10

Choosing the right tool to generate PDF files in C# depends on your needs. If you need to generate PDF documents from HTML content, IronPDF and PDFShift are excellent choices. iTextSharp and Syncfusion offer extensive customization options and control over document structure for more complex projects. For simpler, open-source solutions, PDFsharp is a reliable choice for modifying PDF files or creating basic PDFs. Finally, for non-developers, Smallpdf, PDFescape, and PDF Candy provide easy, code-free options for working with PDF files.

For those interested in trying IronPDF, making it an excellent option for developers to test out its HTML-to-PDF conversion and PDF manipulation features before committing to a paid license. The trial allows you to explore its premium features, such as high-quality PDF file generation, security options, and modifying existing PDF documents, giving you a hands-on experience with the tool’s capabilities. If your project requires frequent HTML-to-PDF conversions or complex PDF editing, IronPDF's free trial is a great way to see if it fits your needs.

By evaluating the specific features of each tool and your project’s scope, you can choose the best solution for generating PDF files efficiently in C#..

NEXT >
html2pdf Page Break Fixed in C# (Developer Tutorial)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,853,890 View Licenses >