#PSTip Convert .docx to .pdf using Word.Application

The Word.Application object can be used to convert Word documents into PDF files. This requires Microsoft Word to be installed on the system on which the code is executed. Using the SaveAs method in the following code it is possible to rename and convert a file:

$Word = New-Object -ComObject "Word.Application"
($Word.Documents.Open('c:\temp\file.docx')).SaveAs([ref]'c:\temp\file.pdf',[ref]17) 
$Word.Application.ActiveDocument.Close() 

Using this technique it is also possible to convert the documents in an entire folder:

$Word = New-Object -ComObject "Word.Application"
Get-ChildItem -Path C:\Temp -File -Filter *.docx | ForEach-Object {
    $NewName = $_.FullName -replace 'docx','pdf'
    ($Word.Documents.Open($_.FullName)).SaveAs([ref]$NewName,[ref]17) 
    $Word.Application.ActiveDocument.Close()
} 

About the author: Jaap Brasser

Jaap is a Senior System Engineer in the Financial Services industry. He focuses on Microsoft and related technologies and has a passion for PowerShell. In his spare time he maintains his Blog, Twitter feed, @Jaap_Brasser, and contributes on the Official Scripting Guys Forum and Windows PowerShell TechNet forums

Related Posts