使用 C# 将 PowerPoint (PPT/PPTX) 转换为 PDF

发布: (2026年1月14日 GMT+8 11:30)
7 min read
原文: Dev.to

Source: Dev.to

请提供您希望翻译的正文内容,我将按照要求保留原始链接、格式和代码块,仅翻译文本部分为简体中文。

将 PowerPoint (PPT/PPTX) 转换为 PDF(C#)使用 Spire.Presentation

在日常开发和办公工作流中,将 PowerPoint 文件转换为 PDF 是一个高优先级的需求。PDF 的跨平台兼容性、固定布局以及便于分发的特性,使其成为共享和长期存储的首选格式。

Spire.Presentation 是一个轻量级、高性能的 .NET 组件,用于 PowerPoint 处理。其主要优势在于 无需依赖 Microsoft Office 或 PowerPoint 的安装,即可在服务器和桌面环境中读取、编辑和转换 PPT 文件。

1. 安装 NuGet 包

通过 Visual Studio UI

  1. 打开 Visual Studio 并创建一个 C# 项目(控制台应用、Windows Forms 等)。
  2. Solution Explorer → Manage NuGet Packages 上右键单击项目。
  3. Browse 选项卡中搜索 Spire.Presentation 并安装最新的稳定版本。

通过 Package Manager Console

Install-Package Spire.Presentation

2. 简单的 PPT → PDF 转换

下面的示例演示了使用 SaveToFile 方法进行单文件转换,该方法原生支持 PDF 输出。

using System;
using Spire.Presentation;

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

                // 加载 PowerPoint 文件
                Presentation presentation = new Presentation();
                presentation.LoadFromFile(pptFilePath);

                // 转换为 PDF(默认设置)
                presentation.SaveToFile(pdfFilePath, FileFormat.PDF);

                // 释放资源
                presentation.Dispose();

                Console.WriteLine("PPT 转换为 PDF 成功!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"转换失败: {ex.Message}");
            }
        }
    }
}

3. 批量转换(文件夹 → 文件夹)

当需要处理大量演示文稿时,可以遍历目录并逐个转换文件。

using System;
using System.IO;
using System.Linq;
using Spire.Presentation;

namespace BatchPptToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            // 源文件夹 & 目标文件夹
            string pptFolderPath = @"D:\Demo\PptFiles";
            string pdfFolderPath = @"D:\Demo\PdfFiles";

            // 确保输出文件夹存在
            Directory.CreateDirectory(pdfFolderPath);

            // 获取所有 .ppt 和 .pptx 文件(不区分大小写)
            string[] pptFiles = Directory.GetFiles(pptFolderPath, "*.*", SearchOption.TopDirectoryOnly)
                .Where(f => f.EndsWith(".ppt", StringComparison.OrdinalIgnoreCase) ||
                            f.EndsWith(".pptx", StringComparison.OrdinalIgnoreCase))
                .ToArray();

            foreach (string pptFile in pptFiles)
            {
                try
                {
                    string fileName = Path.GetFileNameWithoutExtension(pptFile);
                    string pdfFile = Path.Combine(pdfFolderPath, $"{fileName}.pdf");

                    // 使用 'using' 自动释放
                    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("批量转换完成!");
        }
    }
}
   }
}

4. 转换过程中加密 PDF

Spire.Presentation 还允许您使用密码保护生成的 PDF 并设置权限。

using System;
using Spire.Presentation;
using Spire.Presentation.External.Pdf;

namespace ConvertToEncryptedPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            // Paths (replace with your own)
            string inputPptPath  = @"C:\Users\Administrator\Desktop\Input.pptx";
            string outputPdfPath = @"C:\Users\Administrator\Desktop\EncryptedOutput.pdf";

            try
            {
                using (Presentation presentation = new Presentation())
                {
                    // Load the PowerPoint file
                    presentation.LoadFromFile(inputPptPath);

                    // Configure PDF encryption options
                    SaveToPdfOption pdfOption = new SaveToPdfOption
                    {
                        // Set a password required to open the PDF
                        EncryptionPassword = "YourStrongPassword",

                        // Optional: restrict printing, copying, etc.
                        // Permissions = PdfPermissions.Print | PdfPermissions.Copy,

                        // Set the encryption level (e.g., 128‑bit AES)
                        EncryptionLevel = PdfEncryptionLevel.AES128
                    };

                    // Save the encrypted PDF
                    presentation.SaveToFile(outputPdfPath, FileFormat.PDF, pdfOption);
                }

                Console.WriteLine("Encrypted PDF created successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Encryption failed: {ex.Message}");
            }
        }
    }
}

摘要

  • Spire.Presentation 在未安装 Microsoft Office 的情况下也能工作。
  • 通过 NuGet 安装 (Install-Package Spire.Presentation)。
  • 使用 Presentation.LoadFromFile + SaveToFile(..., FileFormat.PDF) 进行单文件转换。
  • 实现文件夹遍历以进行批量处理。
  • 使用 SaveToPdfOption 对 PDF 加密并控制权限。

这些代码片段已准备好可直接复制、粘贴并在任何 .NET 项目中运行。祝编码愉快!

Source:

PPT‑to‑PDF 转换并加密(C#)

// Get PDF options from the presentation
var pdfOptions = presentation.SaveToPdfOption;

// -------------------------------------------------------------------
// Configure PDF encryption and permissions
// -------------------------------------------------------------------
// 1. User Password   : Required to open the PDF file (abc‑123)
// 2. Owner Password  : Required to modify PDF permissions (owner‑456, customizable)
// 3. Permissions      : Allow printing and form filling
// 4. Encryption Level: 128‑bit AES (industry‑standard high security)
pdfOptions.PdfSecurity.Encrypt(
    userPassword: "abc-123",
    ownerPassword: "owner-456",
    permissions: PdfPermissionsFlags.Print | PdfPermissionsFlags.FillFields,
    keySize: PdfEncryptionKeySize.Key128Bit
);

// Save the encrypted PDF file
presentation.SaveToFile(outputPdfPath, FileFormat.PDF, pdfOptions);

Console.WriteLine("PPT converted to encrypted PDF successfully!");
Console.WriteLine($"Output Path: {outputPdfPath}");
// ---------------------------------------------------------------
// Main program (excerpt)
try
{
    // ... (load presentation, set outputPdfPath, etc.)

    // (code from above)
}
catch (Exception ex)
{
    Console.WriteLine($"Conversion failed: {ex.Message}");
}

// Pause the console to view results (press Enter to exit)
Console.ReadLine();

支持的输入格式

  • PPT、PPTX、PPS、PPSX 等。

限制

  • 复杂的 PowerPoint 元素(例如 3D 图表、自定义动画、嵌入视频)可能 无法在 PDF 中完美呈现,因为它们依赖于 PowerPoint 的专有渲染引擎。

资源释放

  • 始终使用 Dispose() 释放 Presentation 对象,或将其放在 using 语句块中。
    这可以防止内存泄漏,尤其是在长时间运行的批量转换任务中。

权限检查清单

  • 确保应用程序对输入文件夹拥有 读取 权限。
  • 确保对输出文件夹拥有 写入 权限。
  • 缺少相应权限会触发 UnauthorizedAccessException

解决方案比较

解决方案优点缺点
LibreOffice SDK免费且开源需要部署 LibreOffice 服务;API 复杂;在服务器环境中稳定性差
OpenXML SDK + iTextSharp无外部依赖仅支持 PPTX(OpenXML)格式;需要手动处理布局;开发成本高
GroupDocs.Conversion云原生支持;提供免费配额依赖网络连接;不适用于离线场景;大规模使用成本高
Spire.Presentation(本文)零 Office 依赖;API 简单;灵活的输出自定义;适合服务器端批处理、桌面应用和企业文档管理(未列出——详情见文章)

为什么选择 Spire.Presentation?

  • 零 Office 依赖 – 无需在服务器上安装 Microsoft Office。
  • API 简单 – 几行代码即可完成加载、转换和加密。
  • 输出灵活 – 可自定义 PDF 安全性、布局和渲染选项。
  • 生产就绪 – 可靠的批处理、桌面工具和企业级文档管理系统。
Back to Blog

相关文章

阅读更多 »

在 C# 中将 RTF 转换为 PDF

概述 RTF(Rich Text Format)是一种跨平台的格式,广泛用于文档编辑和数据交换。相比之下,PDF 则是文档分发的理想选择……