$ErrorActionPreference = 'Stop' $root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path $docDir = Join-Path $root 'doc' $source = Get-ChildItem -LiteralPath $docDir -Filter '*.docx' | Sort-Object Length -Descending | Select-Object -First 1 if (-not $source) { throw 'doc目录中未找到待导出的DOCX文件' } $docxPath = $source.FullName $pdfPath = Join-Path $docDir ($source.BaseName + '.pdf') $tempDocxPath = Join-Path $PSScriptRoot 'revised-manual-for-pdf.docx' Copy-Item -LiteralPath $docxPath -Destination $tempDocxPath -Force $word = $null $doc = $null try { $word = New-Object -ComObject Word.Application $word.Visible = $false $word.DisplayAlerts = 0 $doc = $word.Documents.Open($tempDocxPath, $false, $false) if ($doc.TablesOfContents.Count -gt 0) { for ($index = 1; $index -le $doc.TablesOfContents.Count; $index++) { try { $doc.TablesOfContents.Item($index).Update() } catch { } } } $doc.Save() $doc.ExportAsFixedFormat($pdfPath, 17) Write-Output "DOCX=$docxPath" Write-Output "PDF=$pdfPath" } finally { if ($doc) { try { $doc.Close($false) } catch { } } if ($word) { try { $word.Quit() } catch { } } if ($doc) { [void][Runtime.InteropServices.Marshal]::ReleaseComObject($doc) } if ($word) { [void][Runtime.InteropServices.Marshal]::ReleaseComObject($word) } [GC]::Collect() [GC]::WaitForPendingFinalizers() if (Test-Path -LiteralPath $tempDocxPath) { Remove-Item -LiteralPath $tempDocxPath -Force -ErrorAction SilentlyContinue } }