C#에서 RTF를 PDF로 변환하기

발행: (2026년 1월 7일 오후 12:11 GMT+9)
4 min read
원문: Dev.to

Source: Dev.to

개요

RTF(Rich Text Format)는 문서 편집 및 데이터 교환에 널리 사용되는 크로스‑플랫폼 형식입니다. 반면 PDF는 불변 형식과 강력한 기기 간 호환성 덕분에 문서 배포 및 보관에 이상적입니다. .NET 개발에서는 RTF 파일을 PDF로 변환하는 경우가 자주 있습니다. 이 가이드는 Free Spire.Doc for .NET을 사용하여 변환을 구현하는 방법을 보여줍니다 (참고: 무료 버전은 파일‑크기 제한이 있습니다).

설치

NuGet 패키지 관리자 콘솔을 통해 라이브러리를 설치합니다:

Install-Package FreeSpire.Doc

단일‑파일 변환

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}");
            }
        }
    }
}

배치 변환 (여러 RTF 파일)

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}");
            }
        }
    }
}

문제 해결

RTF 파일 로드 오류

가능한 원인

  • 잘못된 파일 경로
  • 손상된 RTF 파일
  • 파일 권한 부족

해결 방법

  1. 파일 경로가 올바른지 확인합니다(명확성을 위해 절대 경로 사용).
  2. RTF 파일을 텍스트 편집기나 Word에서 열 수 있는지 확인합니다.
  3. 애플리케이션에 파일 읽기 권한이 있는지 확인합니다.

변환 후 PDF 형식/레이아웃 왜곡

가능한 원인

  • 런타임 환경에 폰트가 누락됨
  • 특수 RTF 서식(표, 이미지) 또는 지원되지 않는 RTF 요소

해결 방법

  1. 원본 RTF 파일에 사용된 모든 폰트를 서버/로컬 머신에 설치합니다.
  2. 가능한 경우 복잡한 RTF 서식을 단순화합니다(예: 사용자 지정 간격을 피함).
  3. 최소 RTF 파일로 테스트하여 서식 문제를 분리합니다.

결론

Free Spire.Doc for .NET은 소규모, 기본적인 RTF‑to‑PDF 변환 시나리오(예: 저용량 문서 처리)에서 비용 효율적인 솔루션을 제공합니다.

Back to Blog

관련 글

더 보기 »