0

私は Powershell を初めて使用し、Web で次のスクリプトを見つけました: (自分のプロジェクト用に変更しました)

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

[更新] 参考: ソース ディレクトリ内のファイルは次のように命名されます。

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

Word 文書から PDF を生成するにはどうすればよいですか?

4

1 に答える 1

0

上記のコードは、ソースと宛先のパスが同じ場合に機能します。応答がなかったので、C#.Net ルートを使用することにし、コードを実装することにしました: How do I convert Word files to PDF programmatically?

于 2013-11-23T19:46:13.593 に答える