Powershell 3:将Word转换为PDF

时间:2013-11-11 17:33:38

标签: powershell pdf-generation powershell-v3.0 word-2010

我是Powershell的新手,在网上找到了以下脚本:(我为我的项目修改了它)

# Acquire a list of DOC files in a folder
$Word = New-Object -ComObject word.application 
$formats = "Microsoft.Office.Interop.Word.WdSaveFormat" -as [type]
$Word.visible = $false
$fileTypes = "*.docx","*doc"
$complyDocPath = "i:\2014\COMPLY\DOC\"
$complyPDFPath = "i:\2014\COMPLY\PDF\"
$Files=GET-CHILDITEM $complyDocPath -include $fileTypes

Foreach ($File in $Files) {
    # open a Word document, filename from the directory
    #$Doc=$Word.Documents.Open($File.fullname) 
    $Doc=$Word.Documents.Open($File) 

    # Swap out .DOCX/.DOC with 5.PDF in the Filename
    $fileName = [system.io.path]::GetFileNameWithoutExtension($File)
    $destPath = Join-Path -path $complyPDFPath -childpath ($fileName +"5.PDF")
    Add-Type -AssemblyName "Microsoft.Office.Interop.Word"

    "Converting $File to pdf ... $destPath"

    # Save this File as a PDF in Word 2010/2013
    $Doc.SaveAs($destPath, $formats::wdFormatPDF)
    $Doc.Close($false)
}

$Word.Quit()

我收到以下错误:

Argument: '2' should be a System.Management.Automation.PSReference. Use [ref].
At line:25 char:5
+     $Doc.SaveAs($destPath, $formats::wdFormatPDF)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : NonRefArgumentToRefParameterMsg

Argument: '1' should be a System.Management.Automation.PSReference. Use [ref].
At line:26 char:5
+     $Doc.Close($false)
+     ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : NonRefArgumentToRefParameterMsg

Exception calling "Open" with "1" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
At line:14 char:5
+     $Doc=$Word.Documents.Open($File)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

对于第一个错误,我将代码更改为包含[ref],就像这些变化一样(但没有成功):

$Doc.SaveAs([ref] $destPath, $formats::wdFormatPDF)
$Doc.SaveAs($destPath, [ref] $formats::wdFormatPDF)
$Doc.SaveAs([ref] $destPath, [ref] 17)

[更新] FYI:源目录中的文件命名如下:

I:\2014\Comply\DOC\IBM=US.DOC
I:\2014\Comply\DOC\CTC.A=CA.DOC

如何从Word doc生成PDF?

1 个答案:

答案 0 :(得分:0)

以上代码适用于来源&目的地路径是一样的。由于我没有得到任何回复,我决定采用C#.Net路由并实现我找到的代码: How do I convert Word files to PDF programmatically?