Skip to content

Instantly share code, notes, and snippets.

@regob
Last active November 7, 2023 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save regob/5dd6f19411c771ef967149b9f0741f33 to your computer and use it in GitHub Desktop.
Save regob/5dd6f19411c771ef967149b9f0741f33 to your computer and use it in GitHub Desktop.
Convert Word .docx and PowerPoint .pptx files to PDF
# e.g Convert-Documents-Doc . ./pdf
# converts all .doc and .docx files in DocumentPath to pdf and saves them to ResultDir
function Convert-Documents-Doc {
param (
[Parameter(Mandatory)] $DocumentPath,
[Parameter(Mandatory)] $ResultDir
)
$word_app = New-Object -ComObject Word.Application
$result_dir = Resolve-Path $ResultDir
# This filter will find .doc as well as .docx documents
Get-ChildItem -Path $DocumentPath -Filter *.doc? | ForEach-Object {
$document = $word_app.Documents.Open($_.FullName)
$document.PrintRevisions = False
$document.ShowRevisions = False
$pdf_filename = "$result_dir/$($_.BaseName).pdf"
Write-Output "Saving $pdf_filename"
$document.SaveAs([ref] $pdf_filename, [ref] 17)
$document.Close()
}
$word_app.Quit()
}
# e.g Convert-Documents-Ppt . ./pdf
# converts all .pptx files in DocumentPath to pdf and saves them to ResultDir
function Convert-Documents-Ppt {
param (
[Parameter(Mandatory)] $DocumentPath,
[Parameter(Mandatory)] $ResultDir
)
$result_dir = Resolve-Path $ResultDir
# workaround for ppSaveAsPDF not found
$SaveOption = 32 # [Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType]::ppSaveAsPDF
$PowerPoint = New-Object -ComObject “PowerPoint.Application”
Get-ChildItem -Path $DocumentPath -Filter *.pptx | ForEach-Object {
$Presentation = $PowerPoint.Presentations.Open($_.FullName)
$pdf_filename = "$result_dir/$($_.BaseName).pdf"
Write-Output "Saving $pdf_filename"
$Presentation.SaveAs($pdf_filename, $SaveOption)
$Presentation.Close()
}
$PowerPoint.Quit()
}
Export-ModuleMember -Function Convert-Documents-Doc
Export-ModuleMember -Function Convert-Documents-Ppt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment