DEV Community

Allen Yang
Allen Yang

Posted on

Complete Guide to PDF Generation in C#

C# PDF Generation Tutorial

In modern software applications, PDF documents play an indispensable role due to their cross-platform compatibility, fixed layout, and ease of sharing. From generating reports and invoices to electronic contracts, programmatically creating and managing PDFs has become a daily requirement for many C# developers. But how can you efficiently and flexibly use C# to transform dynamic data into high-quality PDFs while handling complex content layouts like text, images, shapes, and tables?

This article dives into leveraging the power of C# alongside a feature-rich PDF library to automate PDF creation. We will start with the basic environment setup, gradually cover inserting and arranging text, images, and shapes, and focus on constructing structured tables to help you master the core skills for generating PDFs in C#.

Basics of PDF Generation and Environment Setup

In various scenarios such as data visualization, automated reporting systems, and online invoicing services, the demand for programmatic PDF generation in C# is growing. Compared to manual creation, coding not only increases efficiency but also ensures content consistency and accuracy.

This tutorial is based on a powerful PDF library that provides comprehensive APIs, enabling developers to create, edit, convert, and print PDFs effortlessly within C# applications.

Environment Setup and Library Reference:

First, you need a development environment such as Visual Studio. Then, use NuGet Package Manager to add the PDF library to your C# project.

  1. Open Visual Studio and create or open a C# project (e.g., a Console Application).
  2. Right-click the project, choose "Manage NuGet Packages."
  3. In the "Browse" tab, search for and install the PDF library. Once installed, references will be automatically added to your project.

“Hello World” PDF Example:

Let's start with a simple example: generating a PDF containing the text "Hello World."

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace PdfGenerationTutorial
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PDF document instance
            PdfDocument doc = new PdfDocument();

            // Add a page to the document
            PdfPageBase page = doc.Pages.Add();

            // Define font and brush
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 12f);
            PdfBrush brush = PdfBrushes.Black;

            // Draw text on the page
            page.Canvas.DrawString("Hello World from C# PDF!", font, brush, 10, 50);

            // Save the PDF document
            doc.SaveToFile("HelloWorld.pdf");
            doc.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Preview of generated PDF:

C# PDF Hello World

This code creates a PdfDocument object, adds a page, sets the font and color, draws the text at a specified location, and saves the document as HelloWorld.pdf. Running this code produces a PDF containing "Hello World."

Fine-Grained Content Layout — Text and Images

PDF content diversity is one of its strengths. Next, we’ll learn how to finely control text style and layout, and how to insert images into the document.

Text Insertion and Formatting

Inserting text in a PDF is more than just writing a few words. You need to control font, size, color, alignment, and handle automatic line wrapping and paragraph formatting.

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace PdfGenerationTutorial
{
    class AddText
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add();

            // 1. Basic text drawing
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 14f, FontStyle.Bold), true);
            PdfBrush brush1 = PdfBrushes.DarkBlue;
            page.Canvas.DrawString("This is a Title", font1, brush1, 50, 50);

            // 2. Paragraph text with automatic wrapping
            string longText = "This is a longer sample text demonstrating how to handle automatic line wrapping and paragraph layout. In real-world scenarios, you may retrieve dynamic content from a database or other sources and format it for PDF. The library provides powerful text layout features, automatically handling overflow and pagination to ensure complete presentation of content.";
            PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 12f), true);
            PdfBrush brush2 = PdfBrushes.Black;

            // Define text layout rectangle
            RectangleF textBounds = new RectangleF(50, 100, page.Canvas.ClientSize.Width - 100, page.Canvas.ClientSize.Height - 150);

            // Define text format including alignment and line spacing
            PdfStringFormat format = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Justify; // Justify alignment
            format.LineSpacing = 15f;

            // Draw text with automatic wrapping and pagination
            page.Canvas.DrawString(longText, font2, brush2, textBounds, format);

            doc.SaveToFile("TextLayout.pdf");
            doc.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Preview:

C# Insert Text into PDF

This code demonstrates drawing different text styles and using RectangleF and PdfStringFormat to control long-text layout, including line wrapping, alignment, and spacing.

Image Insertion and Positioning

Adding images enhances visual appeal. You can control the image’s position, size, and even set transparency.

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace PdfGenerationTutorial
{
    class AddImage
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add();

            // Load image from file
            Image image = Image.FromFile("logo.png"); // Ensure logo.png exists in project root
            PdfImage pdfImage = PdfImage.FromImage(image);

            // 1. Insert image at specific position, original size
            page.Canvas.DrawImage(pdfImage, 50, 50);

            // 2. Insert image with resizing
            RectangleF imageBounds = new RectangleF(50, 250, 200, 150);
            page.Canvas.DrawImage(pdfImage, imageBounds);

            // 3. Insert image with transparency (watermark example)
            float pageWidth = page.Canvas.ClientSize.Width;
            float pageHeight = page.Canvas.ClientSize.Height;

            float watermarkWidth = pdfImage.Width * 0.5f;
            float watermarkHeight = pdfImage.Height * 0.5f;
            float x = (pageWidth - watermarkWidth) / 2;
            float y = (pageHeight - watermarkHeight) / 2;

            page.Canvas.Save();
            page.Canvas.SetTransparency(0.3f, 0.3f, PdfBlendMode.Multiply);
            page.Canvas.DrawImage(pdfImage, x, y, watermarkWidth, watermarkHeight);
            page.Canvas.Restore();

            doc.SaveToFile("ImageInsertion.pdf");
            doc.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Preview:

C# Insert Image into PDF

This shows loading images into a PDF at different positions, resizing, and applying transparency for watermark effects.

Enhanced Visuals — Shapes and Tables

Beyond text and images, PDFs support drawing shapes and complex tables, essential for highlighting information and organizing data.

Drawing Shapes

Drawing basic shapes (lines, rectangles, circles) helps create visual separation, highlights, or custom charts.

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace PdfGenerationTutorial
{
    class ShapesAndTables
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add();

            // 1. Draw lines
            PdfPen pen1 = new PdfPen(PdfBrushes.Red, 2f);
            page.Canvas.DrawLine(pen1, 50, 50, 200, 50);
            page.Canvas.DrawLine(pen1, 250, 50, 250, 150);

            // 2. Draw rectangle
            PdfPen pen2 = new PdfPen(Color.Blue, 1f);
            PdfBrush brush2 = new PdfSolidBrush(Color.LightGray);
            page.Canvas.DrawRectangle(pen2, brush2, 50, 100, 150, 80);

            // 3. Draw ellipse/circle
            PdfPen pen3 = new PdfPen(Color.Green, 3f);
            PdfBrush brush3 = new PdfSolidBrush(Color.LightCyan);
            page.Canvas.DrawEllipse(pen3, brush3, 250, 180, 100, 50);
            page.Canvas.DrawEllipse(pen3, brush3, 380, 180, 50, 50);

            // 4. Draw polygon
            PointF[] points = { new PointF(50, 250), new PointF(100, 300), new PointF(150, 250), new PointF(100, 200) };
            PdfPen pen4 = new PdfPen(Color.Purple, 2f);
            PdfBrush brush4 = new PdfSolidBrush(Color.Lavender);
            page.Canvas.DrawPolygon(pen4, brush4, points);

            doc.SaveToFile("Shapes.pdf");
            doc.Close();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Preview:

C# Draw Shapes in PDF

This demonstrates drawing lines, rectangles, ellipses, and polygons using different pens and brushes.

Creating Tables

Tables are ideal for structured data. The library provides a powerful table component, supporting headers, data rows, merged cells, borders, adjustable column widths, and automatic pagination.

using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Tables;
using System.Data;
using System.Drawing;

namespace PdfGenerationTutorial
{
    class Tables
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add();

            // Prepare data
            DataTable dt = new DataTable();
            dt.Columns.Add("Product ID");
            dt.Columns.Add("Product Name");
            dt.Columns.Add("Unit Price");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("Total");

            for (int i = 0; i < 20; i++)
            {
                dt.Rows.Add(i + 1, $"Product {i + 1}", (10.00 + i * 0.5).ToString("C2"), i + 1, (10.00 + i * 0.5) * (i + 1));
            }

            // Create PdfTable instance
            PdfTable table = new PdfTable();
            table.DataSource = dt;

            // Table style
            table.Style.BorderPen = new PdfPen(PdfBrushes.Black, 0.5f);
            table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Arial", 10f), true);
            table.Style.DefaultStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);

            // Header style
            table.Style.HeaderSource = PdfHeaderSource.Rows;
            table.Style.HeaderRowCount = 1;
            table.Style.ShowHeader = true;
            table.Style.HeaderStyle.BackgroundBrush = new PdfSolidBrush(Color.LightSteelBlue);
            table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Arial", 12f, FontStyle.Bold), true);
            table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Style.RepeatHeader = true;

            // Alternate row style
            table.Style.AlternateStyle = new PdfCellStyle();
            table.Style.AlternateStyle.BackgroundBrush = new PdfSolidBrush(Color.AliceBlue);
            table.Style.AlternateStyle.Font = new PdfTrueTypeFont(new Font("Arial", 10f), true);
            table.Style.AlternateStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);

            // Column widths
            table.Columns[0].Width = 60;
            table.Columns[1].Width = 150;
            table.Columns[2].Width = 80;
            table.Columns[3].Width = 60;
            table.Columns[4].Width = 80;

            // Draw table
            table.Draw(page, new PointF(50, 50));

            doc.SaveToFile("ComplexTable.pdf");
            doc.Close();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Preview:

C# Create Table in PDF

This example shows creating a PDF table from a DataTable, configuring borders, font, alignment, header styles, repeated headers across pages, and automatic pagination.

Advanced Tips and Best Practices

The library offers many advanced features to further enhance professionalism and interactivity:

  • Page settings: Add headers, footers, and page numbers, with company logos or copyright information.
  • Watermarks: Apply text or image watermarks to protect content.
  • Document encryption: Set passwords and permissions for PDF security.
  • Form fields: Create interactive PDF forms for user input.

For large-scale or graphics-intensive PDFs, consider performance and memory:

  • Release resources promptly: Use using statements to ensure PdfDocument and related objects are disposed.
  • Optimize image size: Compress or resize images before insertion to reduce memory usage.
  • Batch processing: For very large documents, generate in batches or use streaming to lower memory pressure.

Conclusion

Through this tutorial, you have learned core skills for creating PDFs in C# using a powerful PDF library. From environment setup, basic text and image insertion, to advanced shape drawing and structured table creation, we provided detailed code examples and explanations.

C# demonstrates great capability in PDF generation. Whether for automated reports, data exports, or dynamic document creation, these skills will significantly boost your development efficiency and project quality.

Top comments (0)