我想在我的 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()
答案 0 :(得分:2)
问题
Dim cb As PdfContentByte = stamper.GetOverContent(0)
是它请求页面OverContent
的{{1}},而iText中的页码从0
开始。因此,使用
1
相反。