user1255441
user1255441

Reputation: 151

powershell word to pdf

I modified what someone else had on this forum, based on a successful use of powershell Excel to pdf with no success. Any ideas on my failing in the following code? My goal is to be able to convert an entire folder of doc and docx documents to pdf without opening the native applications. Thanks in advance:

# Acquire a list of DOC files in a folder
$Word = New-Object -ComObject word.application 
$path = "c:\Users\Desktop\Test" 
$formats = "Microsoft.Office.Interop.Word.WdFixedFormatType" -as [type]
$Word.visible = $false
$fileTypes = "*.docx","*doc"
$Files = GET-CHILDITEM $path -include $fileTypes

Foreach ($File in $Files) {
    $filepath = Join-Path -path $path -childpath ($File.basename +".pdf")
    $Doc = $Word.open($File.fullname, 3)
    $Doc.Saved= $true
    "Converting $File to pdf ... $destPath"
    # Save this File as a PDF in Word 2010/2013
    $Doc.ExportAsFixedFormat($formats::wdTypePDF, $path)
    $Doc.FullName -replace '\.doc?$', '.pdf'
    $Doc.Close()
}
$Word.Quit()

Upvotes: 2

Views: 4088

Answers (1)

ArcSet
ArcSet

Reputation: 6860

$path = 'C:\tests'

$wd = New-Object -ComObject Word.Application
Get-ChildItem -Path $path -Include *.doc, *.docx -Recurse |
    ForEach-Object {
        $doc = $wd.Documents.Open($_.Fullname)
        $pdf = $_.FullName -replace $_.Extension, '.pdf'
        $doc.ExportAsFixedFormat($pdf,17,$false,0,3,1,1,0,$false, $false,0,$false, $true)
        $doc.Close()
    }
$wd.Quit()

This will Go trough the folder and then look for .doc and .docx files

It then opens each file creates a new save name and exports to PDF

You can learn more about the ExportAsFixedFormat from https://msdn.microsoft.com/en-us/library/bb256835(v=office.12).aspx

Upvotes: 3

Related Questions