2014-09-02 186 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。)