Created
March 31, 2016 08:42
-
-
Save mp4096/2248e458c70b03c3f243648847736237 to your computer and use it in GitHub Desktop.
Batch convert Word files to PDF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Batch convert all .doc/.docx files encountered in folder and all its subfolders | |
# The produced PDF files are stored in the invocation folder | |
# | |
# Adapted from http://stackoverflow.com/questions/16534292/basic-powershell-batch-convert-word-docx-to-pdf | |
# Thanks to MFT, takabanana, ComFreek | |
# | |
# If PowerShell exits with an error, check if unsigned scripts are allowed in your system. | |
# You can allow them by calling PowerShell as an Administrator and typing | |
# ``` | |
# Set-ExecutionPolicy Unrestricted | |
# ``` | |
# Get invocation path | |
$curr_path = Split-Path -parent $MyInvocation.MyCommand.Path | |
# Create a Word object | |
$word_app = New-Object -ComObject Word.Application | |
# Get all objects of type .doc? in $curr_path and its subfolders | |
Get-ChildItem -Path $curr_path -Recurse -Filter *.doc? | ForEach-Object { | |
Write-Host "Processing" $_.FullName "..." | |
# Open it in Word | |
$document = $word_app.Documents.Open($_.FullName) | |
# Create a name for the PDF document; they are stored in the invocation folder! | |
# If you want them to be created locally in the folders containing the source Word file, replace $curr_path with $_.DirectoryName | |
$pdf_filename = "$($curr_path)\$($_.BaseName).pdf" | |
# Save as PDF -- 17 is the literal value of `wdFormatPDF` | |
$document.SaveAs([ref] $pdf_filename, [ref] 17) | |
# Close Word file | |
$document.Close() | |
} | |
# Exit and release the Word object | |
$word_app.Quit() | |
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word_app) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment