使用PDFSharp 1.50将RTF转PDF生成空白页,求解决方案及示例代码
RTF转PDF空白页问题解决(PDFSharp 1.50)
问题原因
你的代码存在几个关键问题:
- 直接输出RTF原始文本:RTF是带格式的标记语言,
File.ReadAllText读取的是包含大量控制标记的原始内容,DrawString无法解析这些格式,只会输出混乱的纯文本内容。 - 字体大小设置为0:
XFont("Time New Roman", 0, ...)会导致文字完全不可见,这是空白页的直接诱因之一。 - 变量名错误:
MyTragetPDFile中使用了未定义的FileName变量,正确引用应为_sFileName,这会导致PDF保存路径无效(可能引发隐性异常)。 - PDFSharp本身不支持RTF解析:PDFSharp的
XGraphics.DrawString仅能处理纯文本,解析RTF需要借助配套的MigraDoc库来处理富文本内容。
正确示例代码
以下是使用MigraDoc加载RTF并转换为PDF的完整代码:
using System; using System.IO; using System.Web; using MigraDoc.DocumentObjectModel; using MigraDoc.Rendering; using PdfSharp.Pdf; protected void ConvertRtf2Pdf() { // 源RTF文件路径 string sourceRtfPath = HttpContext.Current.Server.MapPath("~/templates/sample.rtf"); // 目标PDF文件路径 string fileName = $"SAMPLE_{DateTime.Now:yyyyMMddHHmmss}.pdf"; string targetPdfPath = HttpContext.Current.Server.MapPath($"~/export/{fileName}"); // 确保导出目录存在,避免保存失败 DirectoryInfo exportDir = new DirectoryInfo(Path.GetDirectoryName(targetPdfPath)); if (!exportDir.Exists) { exportDir.Create(); } // 使用MigraDoc加载并解析RTF内容 Document document = new Document(); Section section = document.AddSection(); using (StreamReader reader = new StreamReader(sourceRtfPath)) { section.AddParagraph().Format.LoadRtf(reader.ReadToEnd()); } // 将MigraDoc文档渲染为PDF PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfFontEmbedding.Always); renderer.Document = document; renderer.RenderDocument(); // 保存最终PDF文件 renderer.PdfDocument.Save(targetPdfPath); }
关键说明
- MigraDoc的核心作用:作为PDFSharp的配套库,MigraDoc专门用于处理富文本文档,能正确解析RTF中的字体、段落、样式等格式标记。
- 路径校验逻辑:添加目录存在性检查,避免因导出目录不存在导致的保存失败。
- 简化文件名生成:使用
DateTime.Now:yyyyMMddHHmmss直接生成无特殊字符的文件名,避免手动替换字符的繁琐操作。
内容的提问来源于stack exchange,提问作者AlDiz
相关产品推荐
相关产品推荐

