xianqian

操作系统:Windows10;

通过PowerShell操作COM的Word组件对word文档进行打开另存操作,实现将word文档存为PDF文档。


 

$dirPath           = \'C:\test\'                                             # 要导成pdf的word文件所在目录地址
$wordToPdfLog      = Join-Path -Path $dirPath -ChildPath "wordToPdfLog.txt"        # 已导文件列表wordToPdfLog
$notWordFilelog    = Join-Path -Path $dirPath -ChildPath "notWordFilelog.txt"      # 目录下面不是word文件列表
$errorlog          = Join-Path -Path $dirPath -ChildPath "errorlog.txt"            # 错误日志

# 将word文件转换成pdf,并生成日志
function WordConvertToPDF($wordfile){    
    $pdffile = GetPdffile($wordfile) 
    try
    {      
        if(![String]::IsNullOrEmpty($pdffile) -and $wordfile.ToString().Contains(\'.doc\')){            
            $wordApp = New-Object -ComObject Word.Application
            $document = $wordApp.Documents.Open($wordfile)
            $document.SaveAs([ref] $pdffile, [ref] 17)
            $document.Close()
            $wordApp.Quit()
            $wordfile + "`t>>>>>`t" + $pdffile >> $wordToPdfLog     # 将转换的成功的word文件写入日志
        }
        else
        {
            $wordfile >> $notWordFilelog   # 将非word文件写入日志
        }    
    }
    catch
    {
        $wordfile >> $errorlog    # 错误日志
    } 
}


# 将.docx .doc转为.pdf
function GetPdffile($wordfile){
    $pdffile = \'\'
    if($wordfile.ToString().Contains(\'.docx\'))
    {
        $pdffile = $wordfile.ToString().Replace(\'.docx\',\'.pdf\')
    }
    else
    {
        $pdffile = $wordfile.ToString().Replace(\'.doc\',\'.pdf\')
    }            
    return $pdffile 
}

dir $dirPath | ForEach-Object {    
    WordConvertToPDF($_.FullName)    
}

 

分类:

技术点:

相关文章: