Enterprise IT Solutions/Microsoft

[PowerShell] 워드 파일을 PDF로 일괄 변환하는 스크립트

iseop 2021. 12. 7. 23:01   인쇄용 버전

고등학생 시절 학습자료를 워드 파일(혹은 RTF)로 정리하다 간혹 다른 사람에게 주기 위해 PDF로 바꿀 필요가 있었습니다. 그 때 요긴하게 사용했던 스크립트입니다.

코드에는 *.docx로 되어 있는데, 워드로 열 수 있는 확장자면 필요에 따라 바꾸시면 됩니다.

실행할 때는 변환하려는 워드 파일들이 있는 디렉터리에서 하면 됩니다.

 

function Export-WordToPDF {
  param(
  [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
  [Alias("FullName")]
  $path,
  $pdfpath = $null)

  process {
    if (!$pdfpath) {
      $pdfpath = [System.IO.Path]::ChangeExtension($path, '.pdf')
    }
    $word = New-Object -ComObject Word.Application
    $word.Visible = $true
    $doc = $word.Documents.Open($path)
    $null = $word.ActiveDocument.ExportAsFixedFormat($pdfpath, 17, $false, 1)
    $word.ActiveDocument.Close()
    $word.Quit()
  }
}

$b=Get-ChildItem -path . -Recurse -Filter *.docx | measure-object | select -exp count

for($a = 0; $a -lt $b+1; $a++) {
  Get-ChildItem -path . -Recurse -Filter *.docx | select -index $a | Export-WordToPDF
}

# Remove remainders
# Get-ChildItem -path . -Recurse -Filter *.docx | foreach { $_.Delete() }
# Get-ChildItem -path . -Recurse -Filter *.docx | select -exp Name