in Lifehacki

Skrypt Powershell eksportujący dokumenty Word do PDF

Skrypt pozwala na masowe wyeksportowanie plików .doc i docx z katalogu podanego jako parametr -i do podkatalogu /PDF. Nie zapisuje pliku Word po eksporcie oraz generuje zakładki na podstawie nagłówków (zob. linie 28 i 32).

Sposób użycia:

printpdf.ps1 -i C:\directory\to\export

Nie jestem autorem całego skryptu, bowiem większość została zebrana z różnych odpowiedzi na Stackoverflow na zapytanie “batch pdf printing”.

Param(
    [string]$i
 )
$input_dir = $i
$output_dir = "$($input_dir)\PDF"
# Create output directory if not exist
If(!(test-path $output_dir))
{
New-Item -ItemType Directory -Path $output_dir -Force 
}
Add-type -AssemblyName Microsoft.Office.Interop.Word
# This filter will find .doc as well as .docx documents
Get-ChildItem -Path $input_dir -Filter *.doc? | ForEach-Object {
    
  $wdSourceFile = $_.FullName
  $wdExportFile = "$($input_dir)\PDF\$($_.BaseName).pdf"
  "Opening " + $_

  $wdExportFormat = [Microsoft.Office.Interop.Word.WdExportFormat]::wdExportFormatPDF
  $wdOpenAfterExport = $false
  $wdExportOptimizeFor = [Microsoft.Office.Interop.Word.WdExportOptimizeFor]::wdExportOptimizeForPrint
  $wdExportRange = [Microsoft.Office.Interop.Word.WdExportRange]::wdExportAllDocument
  $wdStartPage = 0
  $wdEndPage = 0
  $wdExportItem = [Microsoft.Office.Interop.Word.WdExportItem]::wdExportDocumentContent
  $wdIncludeDocProps = $true
  $wdKeepIRM = $true
  $wdCreateBookmarks = [Microsoft.Office.Interop.Word.WdExportCreateBookmarks]::wdExportCreateHeadingBookmarks
  $wdDocStructureTags = $true
  $wdBitmapMissingFonts = $true
  $wdUseISO19005_1 = $false
  $wdSaveOpt = [Microsoft.Office.Interop.Word.WdSaveOptions]::wdDoNotSaveChanges

  $wdApplication = $null;
  $wdDocument = $null;

  try
  {
       $wdApplication = New-Object -ComObject "Word.Application"
       $wdDocument = $wdApplication.Documents.Open($wdSourceFile)
       $wdDocument.ExportAsFixedFormat(
       $wdExportFile,
       $wdExportFormat,
       $wdOpenAfterExport,
       $wdExportOptimizeFor,
       $wdExportRange,
       $wdStartPage,
       $wdEndPage,
       $wdExportItem,
       $wdIncludeDocProps,
       $wdKeepIRM,
       $wdCreateBookmarks,
       $wdDocStructureTags,
       $wdBitmapMissingFonts,
       $wdUseISO19005_1
       )
  }
  catch
  {
       $wshShell = New-Object -ComObject WScript.Shell
       $wshShell.Popup($_.Exception.ToString(), 0, "Error", 0)
       $wshShell = $null
  }
  finally
  {
       if ($wdDocument)
       {
          $wdDocument.Close($wdSaveOpt)
          $wdDocument = $null
       }
       if ($wdApplication)
       {
          $wdApplication.Quit()
          $wdApplication = $null
       }
       [GC]::Collect()
       [GC]::WaitForPendingFinalizers()
  }
    "Document printed to \PDF\$($_.BaseName).pdf"
}