icon

Table of Contents

5 Ways to generate PDFs with C#

Generating PDFs is a common task in many software applications. In this article, we will explore several ways to generate PDFs using C# programming language.

We will cover different options available, including using libraries such as iTextSharp and PdfSharp, cloud-based API, built-in classes in the .NET Framework, Crystal Reports, and the Microsoft Office Interop library.

Each method will be explained in detail, and we will provide an example code to illustrate how to use each method to generate PDFs.

1. Using a Library( iTextSharp & PdfSharp)

One of the most popular ways to generate PDFs with C# is to use a library such as iTextSharp or PdfSharp. Both of these libraries provide an easy way to generate PDFs from scratch using C# code.

  • Using iTextSharp: iTextSharp is an open-source library that provides an easy way to generate PDFs from C# code. It has a wide range of features and supports a variety of fonts, images, and text formats. To use iTextSharp, you need to first add a reference to the iTextSharp DLL in your project. Once you have done this, you can use the library’s classes and methods to generate PDFs. Below is the complete code for generating a simple PDF with iTextSharp.
using System;
using iTextSharp.text;
using iTextSharp.text.pdf;

public class Program
{
    public static void Main()
    {
        Document document = new Document();
        PdfWriter.GetInstance(document, new FileStream("MyPDF.pdf", FileMode.Create));
        document.Open();
        document.Add(new Paragraph("Hello, World!"));
        document.Close();
    }
}

In the above code, we create a new Document object, which is an iTextSharp class, and use the PdfWriter class to create a PDF file. We then add a simple “Hello, World!” paragraph to the document and close it.

You can also add images, tables, and other content to your PDFs using iTextSharp. Below is an example of how to add an image to a PDF.

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

public class Program
{
    public static void Main()
    {
        Document document = new Document();
        PdfWriter.GetInstance(document, new FileStream("MyPDF.pdf", FileMode.Create));
        document.Open();
        Image image = Image.GetInstance("MyImage.jpg");
        document.Add(image);
        document.Close();
    }
}
  • Using PdfSharp: PdfSharp is another open-source library for generating PDFs in C#. It is similar to iTextSharp in many ways, but it provides more features such as support for multiple page sizes, page orientations, and page margins. You can use PdfSharp in the same way as iTextSharp, by adding a reference to the library in your project and then using the provided classes and methods to generate the PDF. Below is the complete code for generating a simple PDF with PdfSharp.
using System;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using PdfSharp;
using System.Text;

public class Program
{
    public static void Main()
    {
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        PdfDocument document = new PdfDocument();
        document.Info.Title = "My PDF";
        PdfPage page = document.AddPage();
        XGraphics gfx = XGraphics.FromPdfPage(page);
        XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
        gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, 0 ),XStringFormats.TopLeft);
        document.Save("MyPDF.pdf");
    }
}

In the above code, we create a new PdfDocument object, which is a PdfSharp class, and use the AddPage method to add a new page to the PDF. We then use the XGraphics class to draw a “Hello, World!” string on the page and save the PDF.

There are chances that you’ll face an error System.NotSupportedException: No data is available for encoding 1252. . To solve it, you need to install the below module:

dotnet add package System.Text.Encoding.CodePages --version 5.0.0

2. Using a Third-Party Cloud-Based API

Another option for generating PDFs with C# is to use a third-party cloud-based API such as CraftMyPDF. CraftMyPDF is a powerful tool that makes it easy to create professional-quality images and PDF documents. With CraftMyPDF, you can easily generate PDFs from existing templates and customize them with your own text and images. CraftMyPDF have many features including:

  • Drag & Drop Editor: The template editor allows your users to easily customize and create PDF documents using a drag-and-drop interface. This makes it quick and simple to achieve the desired results.
  • PDF & Image Generation API: The CraftMyPDF template editor not only supports PDF templates, but it also has an image generation API that allows your users to create custom images as well. This gives you even more flexibility and customization options.
  • Automate with Nocode or Lowcode Platforms: The CraftMyPDF template editor can be easily integrated with no-code or low-code platforms such as Make.com or Zapier, allowing you to automate tasks and streamline workflows.
  • Support of Fillable Components: The template editor supports fillable components, such as text fields, checkboxes, and dropdown lists, making it easy for your users to create interactive and customizable PDF documents.
  • Expressions & Formatting Support: The template editor also offers support for expressions and formatting, allowing your users to create dynamic and visually appealing documents.

To use CraftMyPDF, you need to first create a free account on their official website. After that, you will be redirected to the dashboard, where you need to click on the API Intergration tab and copy the API key. This API key will be needed to access the CraftMyPDF APIs.

Once you have the API key, you need to go to the Manage Template page and click on “New PDF Template”. Here, you can select from existing pre-built templates or create your own template. After that, you need to copy the Template ID. This Template ID will be needed to access the CraftMyPDF APIs.

Now, we have everything set up. To generate a PDF with CraftMyPDF, you need to install the CraftMyPDF module and use the below code.

var options = new RestClientOptions("")
{
    MaxTimeout = -1,
};
var client = new RestClient(options);
var request = new RestRequest("https://api.craftmypdf.com/v1/create", Method.Post);
request.AddHeader("X-API-KEY", "YOUR_API_KEY");
request.AddHeader("Content-Type", "application/json");

var body = @"
{
    ""data"": {
        ""invoice_number"": ""INV38379"",
        ""date"": ""2021-09-30"",
        ""currency"": ""USD"",
        ""total_amount"": 82542.56
    },
    ""load_data_from"": null,
    ""template_id"": ""TEMPLATE_ID"",
    ""version"": 8,
    ""export_type"": ""json"",
    ""expiration"": 60,
    ""output_file"": ""output.pdf"",
    ""is_cmyk"": false,
    ""image_resample_res"": 600,
    ""direct_download"": 0,
    ""cloud_storage"": 1
}";

request.AddStringBody(body, DataFormat.Json);
RestResponse response = await client.ExecuteAsync(request);
Console.WriteLine(response.Content);

In the above code, first we are creating an instance of the RestClient class with the API key and then creating an instance of the RestRequest class with the API endpoint and the Template ID. After that, we are setting the parameters for the request body and sending the request. The response will contain a PDF file, which can be downloaded and used.

Don’t forget to replace YOUR_API_KEY with the API key that you copied earlier and TEMPLATE_ID with the Template ID that you copied earlier.

3. Using the .NET Framework

The .NET framework also provides a few built-in classes for generating PDFs in C#. The most commonly used class is the System.Drawing.Printing.PrintDocument class, which provides an easy way to generate PDFs from scratch.

  • Using PrintDocument: The PrintDocument class provides a simple way to generate PDFs in C#. It allows you to create a PDF document from a set of commands, such as adding text, images, and shapes. To use the PrintDocument class, you need to first create a PrintDocument object and then use the Print method to generate the PDF. Below is the complete code for generating a simple PDF with the PrintDocument class.
using System;
using System.Drawing.Printing;
using System.Drawing;

public class Program
{
     public static void Main()
    {
        PrintDocument document = new PrintDocument();
        document.PrintPage += new PrintPageEventHandler(OnPrintPage);
        document.Print();
    }

    private static void OnPrintPage(object sender, PrintPageEventArgs e)
    {
        e.Graphics.DrawString("Hello, World!", new Font("Arial", 20), Brushes.Black, 0, 0);
    }
}

In the above code, we create a PrintDocument object and use the PrintPage event handler to add a “Hello, World!” string to the PDF. We then call the Print method to generate the PDF.

Benefits of using PrintDocument include:

  • Easy to use: With PrintDocument, you can easily generate PDFs using a few simple commands.
  • Flexible: PrintDocument provides a lot of flexibility when it comes to generating PDFs. You can easily add text, images, and shapes to the PDF.
  • Portable: PrintDocument is supported on all major platforms, so you can generate PDFs with it on any platform.

4. Using Microsoft Office Interop

You can also use the Microsoft Office Interop library to generate PDFs using Microsoft Word. Microsoft Office Interop is a library that allows developers to access the features of Microsoft Office from .NET applications. It provides an easy way to create and manipulate Word, Excel, PowerPoint, and other documents. The library is often used to automate the creation of documents or to extract data from documents.

To use Microsoft Office Interop, you need to first add a reference to the library in your project and then use the provided classes and methods to generate the PDF. Below is the complete code for generating a simple PDF with the Microsoft Office Interop library.


using System;
using Microsoft.Office.Interop.Word;

public class Program
{
    public static void Main()
    {
        Application application = new Application();
        Document document = application.Documents.Add();
        Range range = document.Range(0, 0);
        range.Text = "Hello, World!";
        document.SaveAs2("MyPDF.pdf", WdSaveFormat.wdFormatPDF);
        document.Close();
        application.Quit();
    }
}

In the above code, we create a new Application object and then use the Add method to create a new Word document. We then use the Range class to add a “Hello, World!” string to the document and save it as a PDF. Note that, you’ll need to have Microsoft Word installed on your computer for the above code to work.

Here, it’s possible that you’ll get an error Range' is an ambiguous reference between 'Microsoft.Office.Interop.Word.Range' and 'System.Range. This is because the Range class is defined in both the Microsoft Office Interop and the System namespace. To fix this error, you can specify the full namespace of the class, like this:


Microsoft.Office.Interop.Word.Range range = document.Range(0, 0);

You can also use other Microsoft Office applications, such as Excel and PowerPoint, to generate PDFs using Microsoft Office Interop.

5. Using Crystal Reports

Crystal Reports is a powerful reporting tool that allows you to generate PDFs from data stored in different sources, such as databases and spreadsheets. To use Crystal Reports in C#, you need to first install the NuGet package Crystal Reports for .NET.

dotnet add package CrystalDecisions.CrystalReports --version 13.0.25.3158

Once you have done this, you can use the package’s classes and methods to generate PDFs from data. Below is the complete code for generating a simple PDF with Crystal Reports.


using System;
using CrystalDecisions.CrystalReports.Engine;

public class Program
{
    public static void Main()
    {
        ReportDocument document = new ReportDocument();
        document.Load("MyReport.rpt");
        document.ExportToDisk(ExportFormatType.PortableDocFormat, "MyPDF.pdf");
    }
}

In the above code, we first create a ReportDocument object, which is a Crystal Reports class, and use the Load method to load a Crystal Reports file. We then use the ExportToDisk method to export the report to a PDF file.

Benefits of Using Crystal Reports:

Using Crystal Reports to generate PDFs has a few advantages over other methods:

  • Crystal Reports allows you to generate PDFs from data stored in different sources, such as databases and spreadsheets.
  • It provides powerful features, such as the ability to create complex reports with charts and graphs.
  • It is easy to use and has good documentation and support.

There are many other files and methods available in the Crystal Reports library, so be sure to explore the documentation to find out what else you can do.

Conclusion

In summary, there are several ways to generate PDFs with C#. These include using a library like iTextSharp or PdfSharp, cloud-based API CraftMyPDF, the .NET Framework’s PrintDocument class, the Microsoft Office Interop library, and Crystal Reports.

Each method has its own advantages and limitations, so it’s important to choose the one that best fits your needs.

Using a library like iTextSharp or PdfSharp is a popular choice as they provide a wide range of features and are easy to use.

The .NET Framework’s PrintDocument class is easy to use and portable but has limited features.

The Microsoft Office Interop library and Crystal Reports allow you to generate PDFs from data stored in different sources and provide powerful features for creating complex reports.

If you are looking for an easy-to-use solution that allows you to create professional-looking PDFs quickly, CraftMyPDF is definitely worth a try. Signing up is easy and free, and you will get access to ready-made templates and customization options.

Recent Posts
blog

A Guide to Generate Barcodes and QRcodes

In this article, we’ll explore barcodes and QR codes, discussing their applications and how they’re used in various scenarios. I’ll guide you through the steps to create these codes using Python and Node.js. Additionally, we’ll look at how to generate barcodes and QR codes with CraftMyPDF, which supports REST API and integrates seamlessly with no-code platforms like Zapier, Make.com, and Bubble.

Read More »
blog

How to generate PDF documents with PHP

There are various libraries available to generate PDF documents with PHP such as FPDF, TCPDF, or DOMPDF. These libraries provide a wide range of features for creating PDF documents, such as setting page size, margins, fonts, and images.

In this article, I would briefly discuss some of these libraries along with some code snippets and show you how to generate a PDF document using PHP and CraftMyPDF.

Read More »
blog

5 Ways to generate PDFs with C#

In this article, we will cover different options available, including using libraries such as iTextSharp and PdfSharp, cloud-based APIs such as CraftMyPDF, built-in classes in the .NET Framework like the PrintDocument class, and the Microsoft Office Interop library.

Read More »
blog

How to Generate PDF Invoices with Zapier

With PDF invoices, it’s easier to send invoices directly to clients without needing paper copies.

In this article, I would be showing you how to generate PDF invoices with Zapier and also help you understand the benefits of doing this. Let’s get to it!

Read More »
blog

Best-performing Banner Ads Sizes in 2023

Choosing the most appropriate banner for your company isn’t always easy. There are lots of things to consider such as the color, size, type of banner, and so on. This could be a little problematic if you have no knowledge of the different types of banner ads but don’t worry, that’s why I’m here.

Read More »
Copyright ©2024 CraftMyPDF.com

Email us at [email protected] for support