2014-09-02 187 views
0

我想添加页眉或页脚到PDF文档中的页面。这在iTextInAction书中解释为将直接内容添加到页面的正确方法。但是,当我尝试在Adobe中打开此文档时,出现以下错误,并且还打印了一些问题。有任何想法吗?iTextSharp PdfStamper添加页眉/页脚

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 

这是我得到的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 

回答

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.Create或者import System.IO,然后就在我们FileMode.Create。)