在 C# 中将 RTF 转换为 PDF
发布: (2026年1月7日 GMT+8 11:11)
4 min read
原文: Dev.to
Source: Dev.to
请提供您希望翻译的正文内容,我将把它翻译成简体中文并保留原始的格式、Markdown 语法以及代码块和链接。谢谢!
概述
RTF(富文本格式)是一种跨平台的格式,广泛用于文档编辑和数据交换。相比之下,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 文件已损坏
- 文件权限不足
解决方案
- 验证文件路径是否正确(为清晰起见使用绝对路径)。
- 确认 RTF 文件可以在文本编辑器或 Word 中打开。
- 确保应用程序对该文件具有读取权限。
PDF 格式/布局在转换后失真
可能的原因
- 运行环境中缺少字体
- 特殊的 RTF 格式(表格、图像)或不受支持的 RTF 元素
解决方案
- 在服务器/本地机器上安装原始 RTF 文件使用的所有字体。
- 在可能的情况下简化复杂的 RTF 格式(例如,避免自定义间距)。
- 使用最小的 RTF 文件进行测试,以定位格式问题。
结论
免费版 Spire.Doc for .NET 为小规模、基础的 RTF‑to‑PDF 转换场景(例如低量文档处理)提供了一种具成本效益的解决方案。