iTextSharp PdfStamper添加页眉/页脚

时间:2014-09-02 18:39:23

标签: vb.net itextsharp

我正在尝试向pdf文档中的页面添加页眉或页脚。这在iTextInAction一书中作为向页面添加直接内容的正确方法进行了解释。但是,当我尝试在Adobe中打开此文档时,我收到以下错误,并且还有一些打印问题。有什么想法吗?

enter image description here

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

这是我得到过量的内容并将我的文字添加到其中

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

1 个答案:

答案 0 :(得分:2)

你的问题可能就在这一行:

stamper = New PdfStamper(reader, New IO.FileStream(outputFile, IO.FileMode.Append))

您告诉.Net将内容写入附加模式的文件。如果文件不存在则会创建文件但后续写入会生成损坏的PDF。您应该将其更改为IO.FileMode.Create

此外,当您正在使用它时,我通常会建议您更明确地使用FileStream创建,并告诉.Net(以及Windows)您对该流的进一步意图。在这种情况下,你只能写信给你,你可以说FileAccess.Write,当你写信给它时,你要确保没有其他人试图从中读取它(因为它将是无效的)因此你可以说FileShare.None

stamper = New PdfStamper(reader, New FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))

(除此之外,虽然使用IO.FileMode.Create绝对有效,但看起来真的很奇怪。大多数人将其拼写为System.IO.FileMode.Createimport System.IO然后只是我们FileMode.Create。)