Home > Back-end >  PowerShell - Convert Word doc to PDF WITHOUT Com Object
PowerShell - Convert Word doc to PDF WITHOUT Com Object

Time:11-01

I haven't been able to find a solution yet.

Only solutions using Powershell please. How can a Word *.docx file be converted to a PDF *.pdf file please without using a COM object. This is to run on a virtual server via a Windows Task Schedule with 'Run whether user is logged on or not' option ticked which is why the current COM object solution is not working (if I instead tick 'Run only when user is logged on' it works but it is not a suitable option).

I found a PSWriteWord powershell module to do the search and replace portion of the code (word template to new word file) but it does not appear to support save as PDF. There is also a PSWritePDF module but again it does not appear to have this functionality.

$filePath   = "C:\Temp6"
$origFile   = "$filePath\Template.docx"
$newFile    = "$filePath\ReplacedText.docx"

# Get the original document
$WordDocument = Get-WordDocument -FilePath $origFile

# Search and replace some text
ForEach ($Paragraph in $WordDocument.Paragraphs) {
    $Paragraph.ReplaceText('[given_name]','Jane')
    $Paragraph.ReplaceText('[surname]','Doe')
}

# Save as new document
Save-WordDocument -WordDocument $WordDocument -FilePath $newFile 

# Quick check to confirm Word application is not left open
Get-Process -name WinWord -ErrorAction SilentlyContinue

# How to convert/save as PDF WITHOUT COM Object?

Thank you.

CodePudding user response:

Thanks @Tomalak, OpenOffice/LibreOffice did the trick, this works in a Windows Task Schedule with "Run whether user is logged on or not" ticked.

Thankfully my word document didn't have much in the way of formatting, as I have read multiple posts saying OpenOffice/LibreOffice conversion isn't suitable as it strips out some formatting.

# Set an alias for LibreOffice (OpenOffice)
Set-Alias -Name soffice "C:\Program Files\LibreOffice\program\soffice.exe"

# Export docx to pdf using LibreOffice (OpenOffice)
# Wait for the process to complete by using & and | Out-<StreamType>
& soffice --headless --convert-to pdf:writer_pdf_Export --outdir "$($filePath)" "$($newFile)" | Out-Null

# Remove the temporary word document
Remove-Item -Path $($newFile)
  • Related