Skip to main content

Command Palette

Search for a command to run...

RTF to PDF Conversion via C#

Published
3 min read

RTF (Rich Text Format), a cross-platform rich text format, is commonly used for document editing and data exchange. In contrast, PDF is more suitable for document distribution and archiving due to its stable format and strong cross-device compatibility. In .NET development, implementing RTF to PDF conversion is a common requirement. This article will introduce how to achieve this conversion process using the free library - Free Spire.Doc for .NET.

Installation: Free Spire.Doc is a free .NET library (with limitations) that supports format conversion for documents such as RTF and Word. It can be installed directly via the NuGet Package Manager:

Install-Package FreeSpire.Doc

Core Implementation Code for RTF to PDF Conversion

Scenario 1: Convert a Single RTF File to PDF (Basic Version)

The core logic is "Load RTF file → Save as PDF format", and the code is concise and easy to implement:

using System;
using Spire.Doc;

namespace RtfToPdfConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Initialize the Document object
                Document document = new Document();

                // Load a local RTF file (replace with the actual file path)
                string rtfFilePath = @"C:\Files\test.rtf";
                document.LoadFromFile(rtfFilePath, FileFormat.Rtf);

                // Save as a PDF file (replace with the output path)
                string pdfFilePath = @"C:\Files\test.pdf";
                document.SaveToFile(pdfFilePath, FileFormat.Pdf);

                // Release resources
                document.Close();

                Console.WriteLine("RTF to PDF conversion succeeded! Output path: " + pdfFilePath);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Conversion failed: " + ex.Message);
            }
        }
    }
}

Scenario 2: Batch Convert RTF Files (Advanced Version)

For multi-file conversion scenarios, you can traverse all RTF files in a specified directory for batch processing:

using System;
using System.IO;
using Spire.Doc;

namespace BatchRtfToPdfConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            // Source RTF file directory and PDF output directory (replace with actual paths)
            string sourceDir = @"C:\Files\RTF_Source";
            string outputDir = @"C:\Files\PDF_Output";

            // Check and create the output directory if it does not exist
            if (!Directory.Exists(outputDir))
            {
                Directory.CreateDirectory(outputDir);
            }

            try
            {
                // Get all RTF files in the directory
                string[] rtfFiles = Directory.GetFiles(sourceDir, "*.rtf");
                if (rtfFiles.Length == 0)
                {
                    Console.WriteLine("No RTF files found in the source directory!");
                    return;
                }

                // Batch conversion
                int successCount = 0;
                foreach (string rtfFile in rtfFiles)
                {
                    try
                    {
                        Document document = new Document();
                        document.LoadFromFile(rtfFile, FileFormat.Rtf);

                        // Generate a PDF file with the same name
                        string fileName = Path.GetFileNameWithoutExtension(rtfFile);
                        string pdfFile = Path.Combine(outputDir, $"{fileName}.pdf");

                        document.SaveToFile(pdfFile, FileFormat.Pdf);
                        document.Close();

                        successCount++;
                        Console.WriteLine($"Successfully converted: {rtfFile}{pdfFile}");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to convert {rtfFile}: {ex.Message}");
                    }
                }

                Console.WriteLine($"\nBatch conversion completed! Success: {successCount} files, Failed: {rtfFiles.Length - successCount} files");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Batch conversion exception: " + ex.Message);
            }
        }
    }
}

Common Issues and Solutions

Issue 1: Error When Loading RTF File

  • Possible Causes: Incorrect file path / Corrupted file
  • Solution: Check the correctness of the path and verify that the RTF file can be opened normally

Issue 2: PDF Format Disruption After Conversion

  • Possible Causes: RTF contains special formats/fonts
  • Solution: Ensure that the fonts used in the RTF are installed in the runtime environment

Free Spire.Doc for .NET provides a viable free solution for RTF to PDF conversion, suitable for scenarios with small document sizes and basic conversion requirements.

More from this blog