C#로 PowerPoint (PPT/PPTX)를 PDF로 변환
Source: Dev.to
C#와 Spire.Presentation을 이용한 PowerPoint (PPT/PPTX) → PDF 변환
일상적인 개발 및 사무 작업에서 PowerPoint 파일을 PDF로 변환하는 것은 매우 중요한 요구 사항입니다. PDF는 플랫폼 간 호환성, 고정 레이아웃, 배포 용이성 때문에 공유 및 장기 보관에 가장 많이 사용되는 형식입니다.
Spire.Presentation은 가볍고 고성능인 .NET PowerPoint 처리 컴포넌트입니다. 가장 큰 장점은 Microsoft Office 또는 PowerPoint가 설치되어 있을 필요가 없다는 점이며, 서버와 데스크톱 환경 모두에서 PPT 파일을 읽고, 편집하고, 변환할 수 있습니다.
1. NuGet 패키지 설치
Visual Studio UI 사용
- Visual Studio를 열고 C# 프로젝트(콘솔 앱, Windows Forms 등)를 생성합니다.
- Solution Explorer → Manage NuGet Packages에서 프로젝트를 오른쪽 클릭합니다.
- 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("배치 변환이 완료되었습니다!");
}
}
}
Source: …
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}");
}
}
}
}
Summary
- Spire.Presentation은 Microsoft Office가 설치되지 않아도 작동합니다.
- NuGet을 통해 설치합니다 (
Install-Package Spire.Presentation). - 단일 파일 변환을 위해
Presentation.LoadFromFile와SaveToFile(..., FileFormat.PDF)를 사용합니다. - 배치 처리를 위해 폴더 순회를 구현합니다.
- PDF를 암호화하고 권한을 제어하려면
SaveToPdfOption을 적용합니다.
이 스니펫은 .NET 프로젝트 어디서든 복사·붙여넣기·실행할 수 있습니다. 즐거운 코딩 되세요!
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 차트, 사용자 지정 애니메이션, 삽입된 비디오)는 PowerPoint 고유 렌더링 엔진에 의존하기 때문에 PDF에서 완벽하게 렌더링되지 않을 수 있습니다.
리소스 해제
Presentation객체는Dispose()를 사용하거나using문으로 감싸서 항상 해제하십시오.
이는 특히 장시간 실행되는 배치 변환 작업에서 메모리 누수를 방지합니다.
권한 체크리스트
- 애플리케이션이 입력 폴더에 대한 읽기 권한을 가지고 있는지 확인하십시오.
- 출력 폴더에 대한 쓰기 권한을 가지고 있는지 확인하십시오.
- 권한이 없을 경우
UnauthorizedAccessException이 발생합니다.
솔루션 비교
| 솔루션 | 장점 | 단점 |
|---|---|---|
| LibreOffice SDK | 무료이며 오픈소스 | LibreOffice 서비스 배포 필요; 복잡한 API; 서버 환경에서 안정성 부족 |
| OpenXML SDK + iTextSharp | 외부 종속성 없음 | PPTX(OpenXML) 형식만 지원; 레이아웃을 직접 처리해야 함; 개발 비용 높음 |
| GroupDocs.Conversion | 클라우드 네이티브 지원; 무료 할당량 제공 | 네트워크 연결에 의존; 오프라인 시나리오에 부적합; 대규모 사용 시 비용 발생 |
| Spire.Presentation (이 문서) | 오피스 종속성 제로; 간단한 API; 유연한 출력 맞춤화; 서버‑사이드 배치 처리, 데스크톱 앱, 엔터프라이즈 문서 관리에 이상적 | (목록에 없음 – 자세한 내용은 기사 참고) |
왜 Spire.Presentation을 선택할까요?
- 오피스 종속성 제로 – 서버에 Microsoft Office를 설치할 필요가 없습니다.
- 간단한 API – 몇 줄의 코드만으로 로드, 변환, 암호화를 처리할 수 있습니다.
- 유연한 출력 – PDF 보안, 레이아웃, 렌더링 옵션을 자유롭게 맞춤 설정할 수 있습니다.
- 프로덕션 준비 – 배치 처리, 데스크톱 유틸리티, 엔터프라이즈 수준 문서 관리 시스템에 신뢰성을 제공합니다.