Batch convert a folder of DOCX files to PDF
Use this handy PowerShell script to convert all Microsoft Word DOCX files in a directory into Adobe Acrobat PDF files.
This simple PowerShell script will read through a directory and convert all Microsoft Word files (.doc, .docm and .docx) into PDF files. Simply change the code to reflect the target directory.
$path = "c:\path\to\files" #Target directory for converting Word files
$word_app = New-Object -ComObject Word.Application
#Convert .doc and .docx to .pdf
Get-ChildItem -Path $path -Filter *.doc? | ForEach-Object {
$document = $word_app.Documents.Open($_.FullName)
$pdf_filename = "$($_.DirectoryName)\$($_.BaseName).pdf"
$document.SaveAs([ref] $pdf_filename, [ref] 17)
$document.Close()
}
$word_app.Quit()
A -Recurse
function can be added if required.
PDF files will be output to the same directory as their progenitor .doc/.docx files and will share the same file name.
Comments
11 responses to “Batch convert a folder of DOCX files to PDF”
Hello,
Thank you so much for this script, it works perfect under windows 10 with office 2016, you saved me hours of work! I have thousands of docx files to convert to pdf for work and this just saved my day.
Ok, so I didn’t have 1000s of PDFs like the other commenter, but I did have 74 and this script has just saved me a couple of hours work!
Thank you.
Lifesaver!
Hi!
Thanks a ton for saving valuable time :D
Thanks, super helpful, on my system I needed to remove the [ref] from this line
$document.SaveAs([ref] $pdf_filename, [ref] 17)
as I was getting errors like this:
Argument: ‘1’ should not be a System.Management.Automation.PSReference. Do not use [ref].
At C:\Users\lfitzgerald\Documents\ian\convert.ps1:8 char:21
+ $document.SaveAs <<<< ([ref] $pdf_filename, [ref] 17)
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : RefArgumentToNonRefParameterMsg
Once I changed it to: $document.SaveAs($pdf_filename, 17) it all worked correctly.
Thanks again.
Excellent. Many thanks. Now adding Powershell scripting to the toolbox.
Hey guys, I keep getting this error
You cannot call a method on a null-valued expression.
At line:6 char:5
+ $document = $word_app.Documents.Open($_.FullName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Hi, first.. many thanks its save my slot of times.
How can this script convert also from the subfolders…
My doc file is in c:\docs
I want also to convert files inside c:\docs\projects
and more folder inside c:\docs
Can you pls show me what I need to add to this script?
When using OMPM, you would use the “\*” as many as 9 times to have it search the underlying folders, i.e. fldr=C:\Temp\*\*\*\*\*\*\*
Try that.
I am thinking that this is what Adam meant when he made reference to adding a -Recurse function. Probably after Get-ChildItem.
Which one is best word to pdf converter online ?