如何用PowerShell提取PDF中的指定附件pdfDocument.xml?
用PowerShell提取PDF中指定附件的方法
完全可以用PowerShell实现这个需求,下面是具体的实现步骤:
准备依赖
需要用到.NET的iTextSharp库处理PDF文件,你可以从NuGet下载对应的iTextSharp.dll和itextsharp.xmlworker.dll文件,将它们放到PowerShell脚本所在的目录。
提取指定附件的PowerShell脚本
# 加载iTextSharp程序集 Add-Type -Path ".\iTextSharp.dll" Add-Type -Path ".\itextsharp.xmlworker.dll" # 定义PDF路径、目标附件名称和输出路径 $pdfPath = "C:\path\to\your\target.pdf" $targetAttachment = "pdfDocument.xml" $savePath = "C:\path\to\save\pdfDocument.xml" # 打开PDF文档 $pdfReader = New-Object iTextSharp.text.pdf.PdfReader($pdfPath) try { # 遍历所有附件 foreach ($item in $pdfReader.Attachments.Values) { # 匹配目标附件 if ($item.Name -eq $targetAttachment) { # 将附件内容写入本地文件 [System.IO.File]::WriteAllBytes($savePath, $item.Contents) Write-Host "已成功提取附件:$targetAttachment" break } } } finally { # 关闭PDF阅读器 $pdfReader.Close() }
注意事项
- 如果PDF有打开密码,创建
PdfReader时需传入密码:New-Object iTextSharp.text.pdf.PdfReader($pdfPath, [System.Text.Encoding]::UTF8.GetBytes("your-password")) - 确保下载的iTextSharp版本与你的PowerShell环境(.NET版本)兼容
- 若执行脚本时出现权限问题,尝试以管理员身份运行PowerShell
内容的提问来源于stack exchange,提问作者Royce
相关产品推荐
相关产品推荐

