C# Convert TXT to PDF: A Comprehensive Guide
Converting plain text (TXT) files to PDF format is a ubiquitous requirement in modern software development and office workflows. PDFs offer unparalleled advantages—cross-platform compatibility, fixed formatting, and tamper resistance—while TXT files excel at lightweight, unstructured content storage. Bridging these two formats enables you to preserve content readability while ensuring document standardization and portability. This guide provides a production-ready, efficient approach to TXT-to-PDF conversion using C# and a free .NET library.
I. Environment Setup
Install the FreeSpire.PDF package via NuGet (the official package manager for .NET):
Install-Package FreeSpire.PDF
Note: The free tier imposes minor limitations (e.g., a 10-page cap per document for processing), but it is fully adequate for most standard TXT-to-PDF use cases.
II. Step-by-Step Implementation
The conversion workflow follows a logical, modular process that is easy to extend and maintain:
- Read and validate the TXT file content
- Initialize a PDF document and page structure
- Configure typography (font, size, color)
- Define layout rules (pagination, alignment, margins)
- Render text to PDF pages
- Save and clean up resources
Complete Production-Grade Code
This implementation includes error handling, input validation, and best practices for resource management:
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System;
using System.Drawing;
using System.IO;
using System.Text;
namespace TextToPdfConverter
{
internal class Program
{
static void Main(string[] args)
{
// Configure input/output paths (customize these paths as needed)
string inputTxtPath = "Input.txt";
string outputPdfPath = @"ConvertedDocument.pdf";
try
{
// Step 1: Validate input file and read content with UTF-8 encoding
if (!File.Exists(inputTxtPath))
{
throw new FileNotFoundException("Input TXT file not found", inputTxtPath);
}
// Use UTF-8 encoding to avoid garbled text (critical for non-English characters)
string textContent = File.ReadAllText(inputTxtPath, Encoding.UTF8);
// Step 2: Initialize PDF document (disposable pattern for resource safety)
using (PdfDocument pdfDoc = new PdfDocument())
{
// Add a default A4 page
PdfPageBase pdfPage = pdfDoc.Pages.Add();
// Step 3: Configure font (Helvetica for universal compatibility)
// For Chinese/Japanese/Korean (CJK) text: Use PdfTrueTypeFont with a CJK font
PdfFont pdfFont = new PdfFont(PdfFontFamily.Helvetica, 11, PdfFontStyle.Regular);
// Step 4: Define layout rules (auto-paginate for long text)
PdfTextLayout textLayout = new PdfTextLayout
{
Break = PdfLayoutBreakType.FitPage, // Adjust content to page boundaries
Layout = PdfLayoutType.Paginate // Auto-create new pages for overflow content
};
// Step 5: Configure text formatting (professional typography)
PdfStringFormat textFormat = new PdfStringFormat
{
Alignment = PdfTextAlignment.Justify, // Justify text for clean line breaks
LineSpacing = 20f, // 20pt line spacing (improves readability)
CharacterSpacing = 0.5f // Minor character spacing for better flow
};
// Step 6: Create text widget and bind formatting
PdfTextWidget textWidget = new PdfTextWidget(textContent, pdfFont, PdfBrushes.Black)
{
StringFormat = textFormat
};
// Step 7: Define render area (10px margin on left/right, 25px top, 5px bottom)
RectangleF renderArea = new RectangleF(
x: 10,
y: 25,
width: pdfPage.Canvas.ClientSize.Width - 20,
height: pdfPage.Canvas.ClientSize.Height - 30
);
// Step 8: Render text to PDF page
textWidget.Draw(pdfPage, renderArea, textLayout);
// Step 9: Save PDF
pdfDoc.SaveToFile(outputPdfPath, FileFormat.PDF);
}
Console.WriteLine($"Success! TXT file converted to PDF: {Path.GetFullPath(outputPdfPath)}");
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"Error: Input file missing - {ex.Message}");
}
catch (IOException ex)
{
Console.WriteLine($"File I/O Error: {ex.Message} (check if output PDF is open in another app)");
}
catch (Exception ex)
{
Console.WriteLine($"Conversion Failed: {ex.Message}");
}
}
}
}
III. Best Practices Summary
- Resource Safety: Always wrap
PdfDocumentin ausingstatement to avoid memory leaks - Encoding Consistency: Use
Encoding.UTF8for all text operations - Error Clarity: Catch specific exceptions (e.g.,
FileNotFoundException) to provide actionable feedback - Typography: For multi-language support, use TrueType fonts and test rendering across platforms
- Portability: Avoid hardcoding file paths—use
Path.Combine()for cross-platform compatibility
This implementation requires no external dependencies (e.g., Microsoft Office, Ghostscript) and integrates seamlessly into .NET desktop, web, or console applications.
