骑着蜗牛去火星 發表於 2026-1-15 10:37:00

如何通过 C# 将 PPT 文档转换为 PDF 格式

<p>在日常开发和办公场景中,将 PowerPoint(PPT/PPTX) 转换为 PDF 格式是高频需求。PDF 格式具有跨平台兼容性强、格式固定不易篡改、便于分发归档等优势。本文将介绍如何使用一款 .NET PowerPoint 组件通过 C# 实现 PPT 转 PDF,并提供完整代码示例。</p>
<h2 id="1-安装-net-库">1. 安装 .NET 库</h2>
<p>Spire.Presentation 是一款专门用于处理 PowerPoint 文档的 .NET 组件,无需依赖 Microsoft Office 或 PowerPoint 客户端即可完成 PPT 文档的读取、编辑和格式转换。推荐通过 NuGet 包管理器安装,步骤如下:</p>
<ol>
<li>打开 Visual Studio,创建任意 C# 项目(如Console App);</li>
<li>右键项目→“管理NuGet程序包”;</li>
<li>搜索“Spire.Presentation”,选择对应版本安装;</li>
<li>也可通过NuGet命令行安装:</li>
</ol>
<pre><code class="language-bash">Install-Package Spire.Presentation
</code></pre>
<h2 id="2-基础示例单个-powerpoint-文件转-pdf">2. 基础示例:单个 PowerPoint 文件转 PDF</h2>
<p>这是最常用的场景,支持 PPT/PPTX 格式输入,直接通过 <code>SaveToFile</code> 方法输出为 PDF 文件:</p>
<pre><code class="language-csharp">using System;
using Spire.Presentation;

namespace PptToPdfDemo
{
    class Program
    {
      static void Main(string[] args)
      {
            try
            {
                // 1. 定义文件路径
                string pptFilePath = @"D:\Demo\source.pptx"; // 输入PPT路径
                string pdfFilePath = @"D:\Demo\output.pdf";   // 输出PDF路径

                // 2. 加载PPT文档
                Presentation presentation = new Presentation();
                presentation.LoadFromFile(pptFilePath);

                // 3. 转换为PDF并保存
                // 可选参数:PDF导出选项(如压缩、权限等),此处使用默认配置
                presentation.SaveToFile(pdfFilePath, FileFormat.PDF);

                // 4. 释放资源(关键,避免内存泄漏)
                presentation.Dispose();

                Console.WriteLine("PPT转PDF成功!");
            }
            catch (Exception ex)
            {
                // 异常处理:捕获文件不存在、格式不支持、权限不足等问题
                Console.WriteLine($"转换失败:{ex.Message}");
            }
      }
    }
}
</code></pre>
<h3 id="3-批量转换转换多个-powerpoint-文件为-pdf">3. 批量转换:转换多个 PowerPoint 文件为 PDF</h3>
<p>通过遍历文件夹实现批量转换,适合处理大量 PPT 文件:</p>
<pre><code class="language-csharp">using System;
using System.IO;
using Spire.Presentation;

namespace BatchPptToPdf
{
    class Program
    {
      static void Main(string[] args)
      {
            // 源PPT文件夹路径
            string pptFolderPath = @"D:\Demo\PptFiles";
            // 输出PDF文件夹路径
            string pdfFolderPath = @"D:\Demo\PdfFiles";

            // 确保输出文件夹存在
            if (!Directory.Exists(pdfFolderPath))
            {
                Directory.CreateDirectory(pdfFolderPath);
            }

            // 遍历文件夹中的PPT/PPTX文件
            string[] pptFiles = Directory.GetFiles(pptFolderPath, "*", SearchOption.TopDirectoryOnly)
                .Where(file =&gt; file.EndsWith(".ppt", StringComparison.OrdinalIgnoreCase)
                           || file.EndsWith(".pptx", StringComparison.OrdinalIgnoreCase))
                .ToArray();

            foreach (string pptFile in pptFiles)
            {
                try
                {
                  // 获取文件名(不含扩展名),用于生成PDF文件名
                  string fileName = Path.GetFileNameWithoutExtension(pptFile);
                  string pdfFile = Path.Combine(pdfFolderPath, $"{fileName}.pdf");

                  // 加载并转换
                  using (Presentation presentation = new Presentation())
                  {
                        presentation.LoadFromFile(pptFile);
                        presentation.SaveToFile(pdfFile, FileFormat.PDF);
                  }

                  Console.WriteLine($"已转换:{pptFile} → {pdfFile}");
                }
                catch (Exception ex)
                {
                  Console.WriteLine($"转换失败 {pptFile}:{ex.Message}");
                }
            }

            Console.WriteLine("批量转换完成!");
      }
    }
}
</code></pre>
<h3 id="4-进阶示例将-powerpoint-转换为加密的-pdf">4. 进阶示例:将 PowerPoint 转换为加密的 PDF</h3>
<p>还可以在转换时直接加密保护 PDF 文件,并为 PDF 设置权限:</p>
<pre><code class="language-csharp">using Spire.Presentation;
using Spire.Presentation.External.Pdf;

namespace ConvertToEncryptedPdf
{
    class Program
    {
      static void Main(string[] args)
      {
            // 定义明确的文件路径(建议替换为你的实际路径)
            string inputPptPath = @"C:\Users\Administrator\Desktop\Input.pptx";
            string outputPdfPath = @"C:\Users\Administrator\Desktop\ToEncryptedPdf.pdf";
            
            // 使用using语句自动释放Presentation资源(优于手动Dispose)
            try
            {
                using (Presentation presentation = new Presentation())
                {
                  // 加载PPT文件
                  presentation.LoadFromFile(inputPptPath);

                  // 获取PDF保存选项
                  SaveToPdfOption option = presentation.SaveToPdfOption;
                  
                  // 设置PDF密码和权限
                  // 参数说明:
                  // 1. 用户密码(打开PDF需要输入的密码):abc-123
                  // 2. 所有者密码(用于修改PDF权限的密码):owner-456(可自定义)
                  // 3. PDF权限:允许打印 + 允许填写表单
                  // 4. 加密级别:默认128位(高安全性)
                  option.PdfSecurity.Encrypt("abc-123", "owner-456",
                        PdfPermissionsFlags.Print | PdfPermissionsFlags.FillFields,
                        PdfEncryptionKeySize.Key128Bit);

                  // 保存为加密PDF
                  presentation.SaveToFile(outputPdfPath, FileFormat.PDF, pdfOptions);

                  Console.WriteLine("PPT已成功转换为加密PDF!");
                  Console.WriteLine($"输出路径:{outputPdfPath}");
                }
            }
            catch (Exception ex)
            {
                // 捕获所有可能的异常并提示
                Console.WriteLine($"转换失败:{ex.Message}");
            }

            // 暂停控制台,便于查看结果
            Console.ReadLine();
      }
    }
}
</code></pre>
<h2 id="5-关键注意事项">5. 关键注意事项</h2>
<ol>
<li>
<p><strong>格式兼容性</strong>:</p>
<ul>
<li>支持输入格式:PPT、PPTX、PPS、PPSX 等;</li>
<li>复杂PPT元素(如3D图表、自定义动画、嵌入式视频)转换后可能丢失或显示异常(。</li>
</ul>
</li>
<li>
<p><strong>资源释放</strong>:</p>
<ul>
<li>必须通过 <code>Dispose()</code> 方法释放 <code>Presentation</code> 对象,或使用 <code>using</code> 语句(推荐),否则易导致内存泄漏,尤其批量转换时需注意。</li>
</ul>
</li>
<li>
<p><strong>权限问题</strong>:</p>
<ul>
<li>确保程序对输入/输出路径有读写权限,否则会抛出 <code>UnauthorizedAccessException</code>。</li>
</ul>
</li>
</ol>
<h2 id="6-替代方案参考">6. 替代方案参考</h2>
<ol>
<li><strong>LibreOffice SDK</strong>:免费开源,需部署 LibreOffice 服务,API 较复杂;</li>
<li><strong>OpenXML SDK + iTextSharp</strong>:仅支持 PPTX(OpenXML 格式),需自行处理布局转换,开发成本高;</li>
<li><strong>GroupDocs.Conversion</strong>:有免费额度,云原生支持,但依赖网络。</li>
</ol>
<hr>
<p>本文提供了可靠的 C# PowerPoint 转 PDF 解决方案,特别适合在服务器环境或无需安装 Microsoft Office 的场景中使用。其优点包括部署简单、API 设计清晰、支持多种输出选项等。</p><br><br>
来源:https://www.cnblogs.com/jazz-z/p/19486170
頁: [1]
查看完整版本: 如何通过 C# 将 PPT 文档转换为 PDF 格式