iTextSharp:试图使 TextField 透明:PdfContentByte 没什么

iTextSharp: Trying to make TextField transparent: PdfContentByte is nothing

我想在我的 PDF 中添加文本字段。 这些文本字段的背景应该是透明的。

我在网上找到了一个示例,它展示了如何通过以下方式执行此操作:

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("TransparencyPDF.pdf"));
document.open();
PdfContentByte cb = writer.getDirectContent();
        
PdfGState gs1 = new PdfGState();
gs1.setFillOpacity(0.5f);
        
cb.setGState(gs1);

但是,在我的代码中,我没有 PDFWriter。我有一个 PDFStamper。 但是它的属性看起来完全一样,所以我就这样采用了:

Dim cb As PdfContentByte = stamper.GetOverContent(0)
Dim gs As New PdfGState
gs.FillOpacity = 0.5
cb.SetGState(gs)

最后一行抛出错误“System.NullReferenceException: cb is nothing.”

我做错了什么?

谢谢。

这是我的全部代码:

Dim stamper As PdfStamper = New PdfStamper(New PdfReader(sInputFile), File.Create(sOutputFile))

Dim iPageNumer As Integer = 1

Dim tf As TextField
tf = New TextField(stamper.Writer, New iTextSharp.text.Rectangle(iLowerLeftX, iLowerLeftY, iUpperRightX, iUpperRightY), n.Name)
Dim bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, False)
With tf
    .Alignment = Element.ALIGN_LEFT And Element.ALIGN_MIDDLE '  Element.ALIGN_CENTER And Element.ALIGN_MIDDLE
    .BackgroundColor = GrayColor.WHITE
    .BorderColor = Color.RED
    .BorderStyle = PdfBorderDictionary.STYLE_SOLID
    .DefaultText = "This is a new text field."
    .Font = bf
    .FontSize = 7
    .MaxCharacterLength = 25
    .Options = TextField.BORDER_WIDTH_MEDIUM ' TextField.REQUIRED Or TextField.MULTILINE
    .Rotation = 0 '90
    .Text = "" 'This is the assigned value."
End With

stamper.AddAnnotation(tf.GetTextField(), iPageNumer)

Dim cb As PdfContentByte = stamper.GetOverContent(0)
Dim gs As New PdfGState
gs.FillOpacity = 0.5
cb.SetGState(gs) 'This line throws the error. cb is nothing. Why?

stamper.Close()

的问题
Dim cb As PdfContentByte = stamper.GetOverContent(0)

是它请求第 0 页的 OverContent,而 iText 中的页码从 1 开始。因此,使用

Dim cb As PdfContentByte = stamper.GetOverContent(1)

相反。