PowerShell - 在没有 Com 对象的情况下将 Word 文档转换为 PDF

PowerShell - Convert Word doc to PDF WITHOUT Com Object

我还没找到解决办法。

请仅使用 Powershell 的解决方案。请问如何在不使用 COM 对象的情况下将 Word *.docx 文件转换为 PDF *.pdf 文件。这是通过勾选 'Run whether user is logged on or not' 选项的 Windows 任务计划到虚拟服务器上的 运行,这就是当前 COM 对象解决方案不起作用的原因(如果我改为勾选 'Run only when user is logged on' 它可以工作,但它不是一个合适的选项)。

我找到了一个 PSWriteWord powershell 模块来搜索和替换部分代码(word 模板到新的 word 文件),但它似乎不支持另存为 PDF。还有一个 PSWritePDF 模块,但它似乎没有此功能。

$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?

谢谢。

感谢@Tomalak,OpenOffice/LibreOffice 成功了,这在 Windows 任务计划中有效,勾选了“运行 用户是否登录”。

谢天谢地,我的 word 文档在格式化方面没有太多问题,因为我读过多篇文章说 OpenOffice/LibreOffice 转换不合适,因为它删除了一些格式。

# 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)