如何在powershell V5中使用Itext7,加载pdfWriter时出现异常

How to use Itext7 in powershell V5, Exception when loading pdfWriter

在使用 iText7 创建 powershell 脚本之前,我使用新的 iText7 class 创建了一个 C# 应用程序。这没有问题。

现在转成poweshell脚本报错

使用 iTextsharp 一切正常,但 Itextsharp 已停产,因此推荐使用 iText7。

我的代码有什么问题?

[string] $pdfDocuFilename = "C:\pdfTestProject1\Exports\export_" + (Get-Date -Format "yyyyMMdd_HHmmss") + ".pdf"

Add-Type -Path "C:\pdfTestProject1\dlls\BouncyCastle.Crypto.dll"
Add-Type -Path "C:\pdfTestProject1\dlls\itext.kernel.dll"
Add-Type -Path "C:\pdfTestProject1\dlls\itext.layout.dll"
Add-Type -Path "C:\pdfTestProject1\dlls\itext.io.dll"
Add-Type -Path "C:\pdfTestProject1\dlls\NLog.dll"


$pdfWriter = [iText.Kernel.Pdf.PdfWriter]::new($pdfDocuFilename)
$pdf = [iText.Kernel.Pdf.PdfDocument]::new($pdfWriter)

例外情况是:

使用“1”个参数调用“.ctor”时出现异常:"Cannot open document." 在 C:\pdfTestProject1\printPDF.ps1:26 char:1 + $pdf = [iText.Kernel.Pdf.PdfDocument]::new($pdfWriter) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : PdfException

我想要的结果:

一个人唯一想要的就是一个工作代码:-)

谢谢!

问题是缺少几个依赖项。 iText7 依赖 Common.Logging 版本 3.4.1(可以下载 here), which on turn depends on Common.Logging.Core, same version 3.4.1 (can be downloaded here)。 还要确保 BouncyCastle 依赖项是 Portable.BouncyCastle 版本 1.8.1.3(可以下载 here)。

您不需要 NLog 依赖项,至少 iText 7 不需要它来工作。

也就是说,这是在我的设置(iText 7.1.6、PowerShell 5.1)中运行良好的代码片段:

[string] $pdfDocuFilename = "C:\temp\" + (Get-Date -Format "yyyyMMdd_HHmmss") + ".pdf"

Add-Type -Path "C:\temp\Common.Logging.Core.dll"
Add-Type -Path "C:\temp\Common.Logging.dll"
Add-Type -Path "C:\temp\itext.io.dll"
Add-Type -Path "C:\temp\itext.kernel.dll"
Add-Type -Path "C:\temp\BouncyCastle.Crypto.dll"


$pdfWriter = [iText.Kernel.Pdf.PdfWriter]::new($pdfDocuFilename)
$pdf = [iText.Kernel.Pdf.PdfDocument]::new($pdfWriter)
$pdf.AddNewPage()
$pdf.Close()