PowerShell > Word > PDF

I have some code i took from stackoverflow or somewhere like that, that takes HTML and pushes it through word and out to pdf. Been working fine for a long time.

Today on a PC with the latest build of office it is throwing an error. Is this something missing from the latest version of office, is there a new/better way to achieve this?

Exception setting “visible”: “Unable to cast COM object of type ‘Microsoft.Office.Interop.Word.ApplicationClass’ to interface type
‘Microsoft.Office.Interop.Word._Application’. This operation failed because the QueryInterface call on the COM component for the interface with IID
‘{00020970-0000-0000-C000-000000000046}’ failed due to the following error: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A
(TYPE_E_CANTLOADLIBRARY)).”

Code:

[ref]$SaveFormat = "microsoft.office.interop.word.WdSaveFormat" -as [type]
        $word = New-Object -ComObject word.application
        $word.visible = $false
        $doc = $word.documents.open($html)
        $doc.PageSetup.Orientation = [Int][bool]$Landscape
        $doc.saveas([ref]$docx, [ref]$SaveFormat::wdFormatDocumentDefault)
        $doc.close()
        $word.Quit()
        $word = $null
        [gc]::collect()
        [gc]::WaitForPendingFinalizers()

Your code works fine for me on what I think is the latest version of Office (it’s O365 so should be updating automatically). It does save as a DOCX rather than PDF though?

Someone in a previous thread was using wkHTMLtoPDF to convert HTML to PDF directly, and it seems to work well. If you don’t need the intermediate .DOCX file, that might be an option for you.

Interesting, thank you.

Can you share the version of the WinWord.exe you have?

On a non working system, It is this version. 16.0.14701.20262 on my laptop I have 16.0.13029.20344 and it works.

Version 2111 (Build 14701.20262 Click-to-Run)

That’s odd.

I setup a second pc with that version and had the same issue.

Will see if i can repro it again.

FWIW, you code worked fine for me as well on version 16.0.13801.21072