PowerShellでPowerPointのファイルをPDFにエクスポート

samatsu 8/11/2023 571 N/A PowerShell

普段の業務の自動化のためにPowerPointのファイルをPDFにエクスポートする処理をPowerShellで作成しました。世の中にサンプルが転がっていますが、参考までに記載しておきます。

スクリプト内の "<pptx ファイルへのパス>" と、"<pdf fileのパス>" は、実際の環境に合わせて変更してください。

# Reference URLs:
# https://gist.github.com/allenyllee/5d7c4a16ae0e33375e4a6d25acaeeda2
# https://learn.microsoft.com/ja-jp/office/vba/api/powerpoint.presentation.exportasfixedformat
# https://stackoverflow.com/questions/893675/powerpoint-2007-sp2-exportasfixedformat-in-powershell

# PoewrPoint起動
$app = New-Object -ComObject PowerPoint.Application
# ファイルを開く
$presentation = $app.Presentations.Open("<pptx ファイルへのパス>", $msoTrue, $msoFalse, $msoTrue)

# MsoTriState
$msoTrue = [Microsoft.Office.Core.MsoTristate]::msoTrue
$msoFalse = [Microsoft.Office.Core.MsoTristate]::msoFalse

# FixedFormatType PDF/XPS
$typePDF = [Microsoft.Office.Interop.PowerPoint.PpFixedFormatType]::ppFixedFormatTypePDF  
$typeXPS = [Microsoft.Office.Interop.PowerPoint.PpFixedFormatType]::ppFixedFormatTypeXPS  

# Intent
$intentScreen = [Microsoft.Office.Interop.PowerPoint.PpFixedFormatIntent]::ppPrintHandoutHorizontalFirst
$intentPrint = [Microsoft.Office.Interop.PowerPoint.PpFixedFormatIntent]::ppFixedFormatIntentPrint
$intent = $intentPrint

# FrameSlides
$framSlides = $msoFalse

# HandOver
$horizontalFirst = [Microsoft.Office.Interop.PowerPoint.PpPrintHandoutOrder]::ppPrintHandoutVerticalFirst
$verticalFirst = [Microsoft.Office.Interop.PowerPoint.PpPrintHandoutOrder]::ppPrintHandoutVerticalFirst
$handOver = $verticalFirst

# OutputType 
# see other values: https://learn.microsoft.com/ja-jp/office/vba/api/powerpoint.ppprintoutputtype
$outputType = [Microsoft.Office.Interop.PowerPoint.PpPrintOutputType]::ppPrintOutputSlides

# PrintHiddenSlides
$printHiddenSlides = $msoFalse

# PrintRange
$printRange = $presentation.PrintOptions.Ranges.Add(1, $presentation.Slides.Count)

$rangeType = [Microsoft.Office.Interop.PowerPoint.PpPrintRangeType]::ppPrintAll

# デバッグ目的でPowerPointを表示する場合はtrue
$app.Visible = $msoTrue
# PDFにエクスポート、PowerPointの不具合で、RangeTypeまで指定する必要がある
$result = $presentation.ExportAsFixedFormat("<pdf fileのパス>", $typePDF, $intent, $framSlides , $handoutOrder, $outputType, $printHiddenSlides, $printRange, $rangeType) 

$presentation.Close()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($presentation) | Out-Null
$app.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($app) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()