Friday, August 07, 2015

Convert Word documents to PDF in bulk using SharePoint 2013 Word Automation Services - PowerShell Script


Find below the PowerShell script to save PDF version of Word documents in a SharePoint 2013 document library. Take note of the input parameters and corresponding value in the script below, so that you can set your own value for this script to run properly


# Uncomment the line below if running this script within Windows PowerShell ISE
#Add-PSSnapin Microsoft.SharePoint.PowerShell

# Input parameters for the script
# Input the SharePoint list Name - replace Shared Documents with your Document Library Name
$listUrl="Shared Documents"

# Get the Word Automation Service Proxy
$wasp = Get-SPServiceApplicationProxy | where { $_.TypeName -eq "Word Automation Services Proxy" }

#Create the Conversion job
$conversionJob = New-Object Microsoft.Office.Word.Server.Conversions.ConversionJob($wasp)

# Get the web url
# Input the SharePoint URL - replace sharepoint.test.com with your sharepoint site url
$web = Get-SPWeb "http://sharepoint.test.com/"

# Set the credentials to use when running the conversion job.
$conversionJob.UserToken = $web.CurrentUser.UserToken

# Conversion Job Name
$conversionJob.Name = "ConvertDOCXtoPDF1"
$conversionJob.Settings.OutputFormat = [Microsoft.Office.Word.Server.Conversions.SaveFormat]::PDF
$conversionJob.Settings.UpdateFields = $true
$conversionJob.Settings.OutputSaveBehavior = [Microsoft.Office.Word.Server.Conversions.SaveBehavior]::AlwaysOverwrite

#Get list
$list = $web.Lists[$listUrl]

# Replace the variable "SubFolderName" with your own folder name or remove SubFolders[..] if querying all files in root folder
foreach ($itm in $list.RootFolder.SubFolders["SubFolderName"].Files){
    # Replace .docx with .doc or other Word file extensions depending on the Word formats you are trying to convert
    if($itm.Name.ToLower().EndsWith(".docx") -eq $true) {
        Write-Host $($itm.ServerRelativeUrl)
        # Note the job below will convert all Word files to PDF and save it into the same location as where source Word document are. Modify code below to save to alternate location
        $conversionJob.AddFile($($web.Site.MakeFullUrl($itm.ServerRelativeUrl)), $($web.Site.MakeFullUrl($itm.ServerRelativeUrl).ToLower().Replace(".docx", ".pdf")))
               
    }
}
# Start the conversion job
$conversionJob.Start()