You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell ISE如何直接识别iTextSharp.dll中的子类?

PowerShell 5.1中iTextSharp自定义页面事件类的报错解决

报错原因

PowerShell 5.1的脚本解析机制是先解析所有类定义,再执行脚本中的命令。你代码里Add-Type加载iTextSharp.dll的语句,在PowerShell类定义的解析阶段还未执行,导致解析PdfPageEvents类时,找不到继承的iTextSharp.text.pdf.PdfPageEventHelper类型,从而触发报错。

替代VB Imports的功能

PowerShell 5.1提供using namespace指令,作用和VB的Imports类似,能简化类型名称的书写。使用时必须放在脚本最开头:

using namespace iTextSharp.text
using namespace iTextSharp.text.pdf

之后你就可以直接写PdfPageEventHelper而非完整的iTextSharp.text.pdf.PdfPageEventHelper,但这个指令无法解决类解析顺序的问题,仍需确保程序集在类定义前被加载。

彻底解决方法:用Add-Type编译C#类

由于PowerShell原生类的解析顺序限制,改用Add-Type -TypeDefinition编译C#代码定义自定义页面事件类,该方式是运行时执行,在Add-Type加载iTextSharp.dll之后执行,能正常识别父类型。完整代码如下:

$ScriptLocation = $PSScriptRoot # 替换为你的脚本实际路径
$FileOutputName = "output.pdf" # 替换为你的PDF输出路径

# 加载iTextSharp程序集
Add-Type -Path "$ScriptLocation\Includes\itextsharp.dll" -ErrorAction Stop

# 用C#定义继承PdfPageEventHelper的页面事件类
Add-Type -TypeDefinition @"
using iTextSharp.text;
using iTextSharp.text.pdf;

public class PdfPageEvents : PdfPageEventHelper {
    public string headerText;

    public PdfPageEvents(string headerText) {
        this.headerText = headerText;
    }

    public override void OnEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.DirectContent;
        Rectangle pageSize = document.PageSize;

        // 添加页眉
        Paragraph header = new Paragraph(this.headerText, new Font(Font.ARIAL, 12));
        header.Alignment = Element.ALIGN_CENTER;
        PdfPTable headerTable = new PdfPTable(1);
        headerTable.TotalWidth = pageSize.Width - document.LeftMargin - document.RightMargin;
        headerTable.AddCell(header);
        headerTable.WriteSelectedRows(0, -1, document.LeftMargin, pageSize.Height - document.TopMargin + 15, cb);
    }
}
"@ -ReferencedAssemblies "$ScriptLocation\Includes\itextsharp.dll"

# PDF生成逻辑
$pdfDocument = New-Object Document([Rectangle]::new([PageSize]::A4.Height, [PageSize]::A4.Width))
$fileStream = New-Object IO.FileStream($FileOutputName, [System.IO.FileMode]::Create)
$pdfWriter = [PdfWriter]::GetInstance($pdfDocument, $filestream)
[FontFactory]::RegisterDirectories()

$pdfDocument.Open()
$paragraph = New-Object Paragraph

$headerString = "Header Text"
$pdfWriter.PageEvent = [PdfPageEvents]::new($headerString)
$paragraph.Add("blah blah blah")
$pdfDocument.Add($paragraph)

$pdfDocument.Close()
$fileStream.Close()

这段代码无需繁琐的注释-运行-取消注释操作,直接运行即可正常生成带页眉的PDF。

内容的提问来源于stack exchange,提问作者Peter Sun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:14:59