我想添加頁眉或頁腳到PDF文檔中的頁面。這在iTextInAction書中解釋爲將直接內容添加到頁面的正確方法。但是,當我嘗試在Adobe中打開此文檔時,出現以下錯誤,並且還打印了一些問題。有任何想法嗎?iTextSharp PdfStamper添加頁眉/頁腳
Dim reader As PdfReader = Nothing
Dim stamper As PdfStamper = Nothing
Try
reader = New PdfReader(inputFile)
stamper = New PdfStamper(reader, New IO.FileStream(outputFile, IO.FileMode.Append))
Dim fontSz As Single = 10.0F
Dim font As New Font(font.FontFamily.HELVETICA, fontSz, 1, BaseColor.GRAY)
Dim chunk As New Chunk(headerText, font)
Dim rect As Rectangle = reader.GetPageSizeWithRotation(1)
在這裏,我只是調整文字的大小,以確保它的頁面邊界
While chunk.GetWidthPoint() > rect.Width
fontSz -= 1.0F
font = New Font(font.FontFamily.HELVETICA, fontSz, 1, BaseColor.GRAY)
chunk = New Chunk(wm.ToString(), font)
End While
這是我得到的overcontent和我的文本添加到內適合它
For pageNo As Int32 = 1 To reader.NumberOfPages
Dim phrase As New Phrase(chunk)
Dim x As Single = (rect.Width/2) - (phrase.Chunks(0).GetWidthPoint()/2)
Dim y As Single = If(wm.WatermarkPosition = "Header", rect.Height - font.Size, 1.0F)
Dim canvas As PdfContentByte = stamper.GetOverContent(pageNo)
canvas.BeginText()
ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, phrase, x, y, 0)
canvas.EndText()
Next
Catch ex As iTextSharp.text.pdf.BadPasswordException
Throw New InvalidOperationException("Page extraction is not supported for this pdf document. It must be allowed in order to add a watermark.")
Finally
reader.Close()
stamper.Close()
End Try