【问题标题】:iTextSharp to merge PDF files in PowerShelliTextSharp 在 PowerShell 中合并 PDF 文件
【发布时间】:2015-10-14 10:48:37
【问题描述】:

我有一个包含数千个 PDF 文件的文件夹。我需要根据文件名过滤这些文件(这会将它们分组为 2 个或更多 PDF),然后将另外 2 个 PDF 合并为 1 个 PDF。

我可以将文件分组,但不确定将这些文件合并为 1 个 PDF 的最佳方式。我研究了 iTextSharp,但无法让它在 PowerShell 中工作。

iTextSharp 是最好的方法吗?对此代码的任何帮助将不胜感激。

非常感谢 保罗

【问题讨论】:

  • This question and answer 在 PowerShell 和 iTextSharp 以及合并方面都有一个良好的开端。
  • 是的 - 我看到了这个问题\答案。看起来“合并 PDF”功能不起作用,我无法理解从 C# 到 PowerShell 的转换.......

标签: powershell pdf itextsharp


【解决方案1】:

已经看到其中一些带有 PowerShell 标记的问题也带有 itextsharp 标记,并且一直想知道为什么在 .NET 中给出答案,这可能会非常令人困惑,除非提出问题的人是精通PowerShell开始。无论如何,这里有一个简单的 PowerShell 脚本可以帮助您入门:

$workingDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path;
$pdfs = ls $workingDirectory -recurse | where {-not $_.PSIsContainer -and $_.Extension -imatch "^\.pdf$"};

[void] [System.Reflection.Assembly]::LoadFrom(
    [System.IO.Path]::Combine($workingDirectory, 'itextsharp.dll')
);

$output = [System.IO.Path]::Combine($workingDirectory, 'output.pdf');
$fileStream = New-Object System.IO.FileStream($output, [System.IO.FileMode]::OpenOrCreate);
$document = New-Object iTextSharp.text.Document;
$pdfCopy = New-Object iTextSharp.text.pdf.PdfCopy($document, $fileStream);
$document.Open();

foreach ($pdf in $pdfs) {
    $reader = New-Object iTextSharp.text.pdf.PdfReader($pdf.FullName);
    $pdfCopy.AddDocument($reader);
    $reader.Dispose();  
}

$pdfCopy.Dispose();
$document.Dispose();
$fileStream.Dispose();

测试:

  1. 创建一个空目录。
  2. 将以上代码复制到目录下的Powershell脚本文件中。
  3. 将 itextsharp.dll 复制到目录中。
  4. 在目录下放一些PDF文件。

不确定您打算如何根据文件名对 PDF 进行分组过滤,或者这是否是您的意图(无法判断您是否只是按扩展名挑选 PDF),但这不应该太难添加。

祝你好运。 :)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 2013-03-09
  • 2023-03-22
  • 1970-01-01
  • 2014-12-14
  • 2011-04-24
  • 2011-01-15
相关资源
最近更新 更多