Converting RTF to PDF in C#
Source: Dev.to
Overview
RTF (Rich Text Format) is a cross‑platform format widely used for document editing and data exchange. PDF, by contrast, is ideal for document distribution and archiving because of its immutable format and robust cross‑device compatibility. In .NET development, converting RTF files to PDF is a frequent requirement. This guide shows how to implement the conversion with Free Spire.Doc for .NET, a free library for document format manipulation (note: the free version has file‑size limitations).
Installation
Install the library via the NuGet Package Manager Console:
Install-Package FreeSpire.Doc
Single‑File Conversion
using System;
using Spire.Doc;
namespace RtfToPdfConverter
{
class Program
{
static void Main(string[] args)
{
try
{
// Initialize Document object to handle RTF content
Document rtfDocument = new Document();
// Load local RTF file (replace with your file path)
string inputRtfPath = @"C:\Files\test.rtf";
rtfDocument.LoadFromFile(inputRtfPath, FileFormat.Rtf);
// Save as PDF (replace with your output path)
string outputPdfPath = @"C:\Files\test.pdf";
rtfDocument.SaveToFile(outputPdfPath, FileFormat.Pdf);
// Clean up resources
rtfDocument.Close();
Console.WriteLine($"RTF converted to PDF successfully! Output: {outputPdfPath}");
}
catch (Exception ex)
{
Console.WriteLine($"Conversion failed: {ex.Message}");
}
}
}
}
Batch Conversion (Multiple RTF Files)
using System;
using System.IO;
using Spire.Doc;
namespace BatchRtfToPdfConverter
{
class Program
{
static void Main(string[] args)
{
// Configure source (RTF) and output (PDF) directories (update paths as needed)
string sourceRtfDir = @"C:\Files\RTF_Source";
string outputPdfDir = @"C:\Files\PDF_Output";
// Create output directory if it does not exist
Directory.CreateDirectory(outputPdfDir);
try
{
// Get all .rtf files in the source directory
string[] rtfFiles = Directory.GetFiles(sourceRtfDir, "*.rtf", SearchOption.TopDirectoryOnly);
if (rtfFiles.Length == 0)
{
Console.WriteLine("No RTF files found in the source directory.");
return;
}
// Batch conversion logic
int successfulConversions = 0;
foreach (string rtfFile in rtfFiles)
{
try
{
using (Document rtfDocument = new Document()) // Automatic disposal
{
rtfDocument.LoadFromFile(rtfFile, FileFormat.Rtf);
// Generate PDF file with the same name as the original RTF
string fileName = Path.GetFileNameWithoutExtension(rtfFile);
string pdfOutputPath = Path.Combine(outputPdfDir, $"{fileName}.pdf");
rtfDocument.SaveToFile(pdfOutputPath, FileFormat.Pdf);
}
successfulConversions++;
Console.WriteLine($"Converted: {rtfFile} → {pdfOutputPath}");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to convert {rtfFile}: {ex.Message}");
}
}
// Summary of batch results
int failedConversions = rtfFiles.Length - successfulConversions;
Console.WriteLine($"\nBatch conversion complete! Success: {successfulConversions}, Failed: {failedConversions}");
}
catch (Exception ex)
{
Console.WriteLine($"Batch conversion error: {ex.Message}");
}
}
}
}
Troubleshooting
Error loading RTF file
Possible causes
- Invalid file path
- Corrupted RTF file
- Insufficient file permissions
Solutions
- Verify the file path is correct (use absolute paths for clarity).
- Confirm the RTF file can be opened in a text editor or Word.
- Ensure the application has read permissions for the file.
PDF format/layout distortion after conversion
Possible causes
- Missing fonts in the runtime environment
- Special RTF formatting (tables, images) or unsupported RTF elements
Solutions
- Install all fonts used in the original RTF file on the server/local machine.
- Simplify complex RTF formatting (e.g., avoid custom spacing) where possible.
- Test with a minimal RTF file to isolate formatting issues.
Conclusion
Free Spire.Doc for .NET provides a cost‑effective solution for small‑scale, basic RTF‑to‑PDF conversion scenarios, such as low‑volume document processing.