DEV Community

Jeremy K.
Jeremy K.

Posted on

Convert TXT to PDF Using C#

In everyday development and office workflows, converting plain text (TXT) files to PDF is a common requirement. PDFs offer cross-platform compatibility, fixed formatting, and tamper resistance, while TXT files prioritize lightweight content storage. Converting between these formats balances content readability with document standardization and portability. This article walks through an efficient way to convert TXT to PDF using C# and a free .NET library.


I. Prerequisites

1. Core Library Overview

Free Spire.PDF for .NET is a robust free PDF manipulation library that supports essential PDF operations: creation, editing, merging, and conversion. The free edition has minor processing limits (e.g., a maximum page count per conversion), but it is fully adequate for standard TXT-to-PDF tasks.

2. Environment Setup

  • Development Environment: Visual Studio 2022+ or any .NET-compatible IDE.
  • Library Installation: Install FreeSpire.PDF via the NuGet Package Manager. Run this command in the Package Manager Console:
  Install-Package FreeSpire.PDF
Enter fullscreen mode Exit fullscreen mode

II. Step-by-Step TXT-to-PDF Conversion

The conversion process follows these core steps:

  1. Read the content of the TXT file
  2. Create a PDF document and a blank page
  3. Configure text font and styling
  4. Define text layout rules
  5. Render text to the PDF and save the file

Complete Code

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

namespace ConvertTextToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // 1. Read TXT file content (UTF-8 encoding to avoid Chinese garbling)
                string txtFilePath = "Input.txt";
                string textContent = File.ReadAllText(txtFilePath, System.Text.Encoding.UTF8);

                // 2. Initialize PDF document and add a default A4 page
                PdfDocument pdfDocument = new PdfDocument();
                PdfPageBase pdfPage = pdfDocument.Pages.Add();

                // 3. Set font for text rendering (Helvetica, 11pt)
                PdfFont pdfFont = new PdfFont(PdfFontFamily.Helvetica, 11);

                // 4. Configure layout: auto-fit page + auto-paginate overflow content
                PdfTextLayout textLayout = new PdfTextLayout
                {
                    Break = PdfLayoutBreakType.FitPage,
                    Layout = PdfLayoutType.Paginate
                };

                // 5. Set text format: justified alignment + 20px line spacing
                PdfStringFormat textFormat = new PdfStringFormat
                {
                    Alignment = PdfTextAlignment.Justify,
                    LineSpacing = 20f
                };

                // 6. Create text widget with content, font, and color
                PdfTextWidget textWidget = new PdfTextWidget(textContent, pdfFont, PdfBrushes.Black)
                {
                    StringFormat = textFormat
                };

                // 7. Define render area (10px left/right margins, 25px top/5px bottom margins)
                RectangleF renderBounds = new RectangleF(
                    x: 10, y: 25,
                    width: pdfPage.Canvas.ClientSize.Width - 20,
                    height: pdfPage.Canvas.ClientSize.Height - 30
                );

                // 8. Render text to PDF page
                textWidget.Draw(pdfPage, renderBounds, textLayout);

                // 9. Save PDF and clean up resources
                pdfDocument.SaveToFile("TextToPdf.pdf", FileFormat.PDF);
                pdfDocument.Close();

                Console.WriteLine("TXT converted to PDF successfully!");
            }
            catch (IOException ex)
            {
                Console.WriteLine($"File operation error: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Conversion failed: {ex.Message}");
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Code Explanations

  1. TXT Content Reading

    File.ReadAllText with explicit UTF-8 encoding prevents special character garbling caused by inconsistent system default encodings.

  2. PDF Page Creation

    PdfDocument.Pages.Add() adds an A4 page by default. To customize page size, use overloaded methods (e.g., PdfDocument.Pages.Add(PdfPageSize.A3)).

  3. Text Style & Layout

    • Font: PdfFont defines font family, size, and style (e.g., bold/italic).
    • Layout: PdfLayoutType.Paginate automatically creates new pages when text exceeds the current page bounds.
    • Format: PdfStringFormat controls alignment, line spacing, and other typographic settings for better readability.
    • Render Area: RectangleF sets a margin-bound drawable area to improve document aesthetics.
  4. Rendering & Saving

    PdfTextWidget binds text content to styling rules and renders it to the PDF via the Draw() method. SaveToFile() finalizes and saves the PDF file.


This C# implementation converts TXT to PDF with minimal code, no dependencies on Microsoft Office or third-party CLI tools. It is ideal for integration into small-to-medium .NET projects to meet routine document format conversion needs.

Top comments (0)