Converting TXT Text Files to PDF Using C#

Overview

Portable Document Format (PDF) offers cross-platform compatibility and document integrity, making it ideal for archival and distribution purposes. Plain text files (TXT) provide lightweight storage for raw content. Converting between these formats allows developers to preserve text content while gaining the benefits of a standardized document format. This guide demonstrates how to transform TXT files to PDF using C# and free .NET libraries.

Prerequisites

Library Selection

Free Spire.PDF for .NET is a no-cost PDF processing library that supports document creation, editing, merging, and format conversion. The free edition includes sufficient functionality for standard text-to-PDF conversions, though it may have limitations on large batch operations.

Development Setup

  • IDE: Visual Studio 2022 or later, or any .NET-compatible development environment
  • Package Installation: Install via NuGet Package Manager console:
Install-Package FreeSpire.PDF

Implementation

Conversion Workflow

The conversion process consists of the following stages:

  1. Load text content from source file
  2. Initialize PDF document structure
  3. Configure typography settings
  4. Define layout parameters
  5. Render contant and save output

Implementation Code

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

namespace TextToPdfConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Load source text file with explicit encoding handling
                string sourcePath = @"sample.txt";
                string fileContent = File.ReadAllText(sourcePath, System.Text.Encoding.UTF8);

                // Initialize PDF document with A4 page format
                PdfDocument document = new PdfDocument();
                PdfPageBase page = document.Pages.Add();

                // Configure font settings (family, size, style)
                PdfTrueTypeFont font = new PdfTrueTypeFont("Arial", 14f, PdfFontStyle.Regular, true);

                // Configure text layout properties
                PdfTextLayout layout = new PdfTextLayout();
                layout.Break = PdfLayoutBreakType.FitPage;
                layout.Layout = PdfLayoutType.Paginate;

                // Configure string formatting options
                PdfStringFormat format = new PdfStringFormat();
                format.Alignment = PdfTextAlignment.Left;
                format.LineSpacing = 18f;

                // Create text rendering widget
                PdfTextWidget widget = new PdfTextWidget(fileContent, font, PdfBrushes.Black);
                widget.StringFormat = format;

                // Define rendering area with margins
                RectangleF bounds = new RectangleF(
                    new PointF(30, 40),
                    new SizeF(page.Canvas.ClientSize.Width - 60, page.Canvas.ClientSize.Height - 80)
                );

                // Render content to PDF page
                widget.Draw(page, bounds, layout);

                // Save output document
                document.SaveToFile("output.pdf", FileFormat.PDF);

                // Cleanup resources
                document.Close();
                Console.WriteLine("Conversion completed successfully.");
            }
            catch (IOException error)
            {
                Console.WriteLine("File operation error: " + error.Message);
            }
            catch (Exception error)
            {
                Console.WriteLine("Conversion error: " + error.Message);
            }
        }
    }
}

Component Details

File Loading

Reading the source file with explicit encoding (UTF-8) prevents character encoding issues that may arise from default system settings.

Document Initialization PdfDocument.Pages.Add() creates an A4-sized page by default. Use overloaded methods to specify alternative sizes such as A3 or Letter.

Layout Configuration

  • Font: PdfTrueTypeFont accesses system-installed TrueType fonts
  • Pagination: PdfTextLayout with Paginate ensures automatic content distribution across multiple pages
  • Formatting: PdfStringFormat controls alignment and spacing for improved visual presentation
  • Rendering Area: RectangleF defines the content bounds with appropriate margins

Rendering and Output PdfTextWidget encapsulates content and styling, then renders to the PDF page via the Draw method. The SaveToFile method produces the final output.

Summary

This implementation uses the Free Spire.PDF library to convert plain text files to PDF format with minimal code. The approach entegrates well into .NET applications without requiring Office dependencies or external command-line utilities, making it suitable for standard document conversion workflows.

Tags: C# PDF Text Conversion .NET

Posted on Tue, 28 Jul 2026 16:21:33 +0000 by raja9911