使用 C# 将 RTF 文档转换为 PDF 格式

RTF(Rich Text Format)作为跨平台富文本格式,常用于文档编辑与数据交换,而 PDF 因格式稳定、跨设备兼容性强,更适合文档分发和归档。在 .NET 开发中,实现 RTF 到 PDF 的转换是常见需求,本文将介绍如何使用免费库 Free Spire.Doc for .NET 实现该转换过程。

安装: Free Spire.Doc 是一款支持 RTF、Word 等文档的格式转换的免费 .NET 库 (有篇幅限制),可直接通过 NuGet 包管理器安装:

bash 复制代码
Install-Package FreeSpire.Doc

RTF 转 PDF 核心实现代码

场景1:单个RTF文件转换为PDF(基础版)

核心逻辑为"加载RTF文件 → 保存为PDF格式",代码简洁易实现:

csharp 复制代码
using System;
using Spire.Doc;

namespace RtfToPdfConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // 初始化Document对象
                Document document = new Document();

                // 加载本地RTF文件(替换为实际文件路径)
                string rtfFilePath = @"C:\Files\test.rtf";
                document.LoadFromFile(rtfFilePath, FileFormat.Rtf);

                // 保存为PDF文件(替换为输出路径)
                string pdfFilePath = @"C:\Files\test.pdf";
                document.SaveToFile(pdfFilePath, FileFormat.Pdf);

                // 释放资源
                document.Close();

                Console.WriteLine("RTF转PDF成功!输出路径:" + pdfFilePath);
            }
            catch (Exception ex)
            {
                Console.WriteLine("转换失败:" + ex.Message);
            }
        }
    }
}

场景2:批量转换RTF文件(进阶版)

针对多文件转换场景,可遍历指定目录下的RTF文件批量处理:

csharp 复制代码
using System;
using System.IO;
using Spire.Doc;

namespace BatchRtfToPdfConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            // 源RTF文件目录、PDF输出目录(替换为实际路径)
            string sourceDir = @"C:\Files\RTF_Source";
            string outputDir = @"C:\Files\PDF_Output";

            // 检查并创建输出目录
            if (!Directory.Exists(outputDir))
            {
                Directory.CreateDirectory(outputDir);
            }

            try
            {
                // 获取目录下所有RTF文件
                string[] rtfFiles = Directory.GetFiles(sourceDir, "*.rtf");
                if (rtfFiles.Length == 0)
                {
                    Console.WriteLine("源目录下未找到RTF文件!");
                    return;
                }

                // 批量转换
                int successCount = 0;
                foreach (string rtfFile in rtfFiles)
                {
                    try
                    {
                        Document document = new Document();
                        document.LoadFromFile(rtfFile, FileFormat.Rtf);

                        // 生成同名PDF文件
                        string fileName = Path.GetFileNameWithoutExtension(rtfFile);
                        string pdfFile = Path.Combine(outputDir, $"{fileName}.pdf");

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

                        successCount++;
                        Console.WriteLine($"成功转换:{rtfFile} → {pdfFile}");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"转换失败 {rtfFile}:{ex.Message}");
                    }
                }

                Console.WriteLine($"\n批量转换完成!成功:{successCount} 个,失败:{rtfFiles.Length - successCount} 个");
            }
            catch (Exception ex)
            {
                Console.WriteLine("批量转换异常:" + ex.Message);
            }
        }
    }
}

常见问题与解决方案

问题1:加载 RTF 文件时报错
  • 可能原因:文件路径错误/文件损坏
  • 解决方案:检查路径正确性,验证 RTF 文件可正常打开
转换后 PDF 格式错乱
  • 可能原因:RTF 含特殊格式/字体
  • 解决方案:确保运行环境安装了 RTF 中使用的字体

Free Spire.Doc for .NET 为 RTF 到 PDF 的转换提供了可行的免费解决方案,适合文档规模较小、基础转换场景。

相关推荐
泛凡(Linyongui)6 小时前
基于 CW32L010 的智能厨卫调温旋钮方案--低成本 EC21 编码旋钮全解析
单片机·嵌入式硬件·c#
暴走约伯8 小时前
【VFX工具链源码拆解 02】告别机械劳动(上):一键统改百个子粒子颜色与批量重命名
3d·unity·c#·材质
信息安全失业大专人员9 小时前
每日了解一个智能体-WorkBuddy
开发语言·ai·c#·智能体
呆呆敲代码的小Y10 小时前
【实战精选面试题】C# 面试题详细解答,按难易程度排序
android·java·游戏·c#·游戏开发·unity面试题·c#面试题
淡海水11 小时前
09-01-内存-Unity资源生命周期全景
unity·c#·游戏引擎·.netcore·gc
云月呀13 小时前
《死亡回忆录》藏汉双语版电子版 PDF,穆迪博士 150 例濒死体验访谈,一部关于生死的温柔读本
pdf·死亡回忆录
椒颜皮皮虾྅14 小时前
让 C# 读懂整张图:DeploySharp 驱动 PaddleOCR v4/v5/v6,打通 OCR 全流程
开发语言·人工智能·深度学习·学习·c#·ocr·cuda
昂好的day14 小时前
C# 同步异步与多线程:Thread / Task / 线程池一次讲透(上篇)
开发语言·windows·c#
吃一碗粉只付一碗钱1 天前
12-给SPA友好的401和403响应
c#·状态模式
xiaolinudao1231 天前
给pdf文件盖骑缝章的软件有哪些
pdf