2016-11-22 164 views
0

我想創建一個PDF頁腳。 我試過以下代碼在我的pdf文件中有頁腳。頁腳不顯示在pdf

private void AddFooter(string filephysicalpath, string documentname) 
     { 
      byte[] bytes = System.IO.File.ReadAllBytes(filephysicalpath); 
      Font blackFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK); 
      using (MemoryStream stream = new MemoryStream()) 
      { 
       PdfReader reader = new PdfReader(bytes); 
       using (PdfStamper stamper = new PdfStamper(reader, stream)) 
       { 
        int pages = reader.NumberOfPages; 

        for (int i = 1; i <= pages; i++) 
        { 
         string footer = Convert.ToString(Session["Footer"]); 
         footer += "\n"; 
         footer += documentname; 
         Phrase ph = new Phrase(footer); 
         Rectangle rect = new Rectangle(10f, 10f, 0); 
         ColumnText ct = new ColumnText(stamper.GetUnderContent(i)); 
         ct.SetSimpleColumn(rect); 
         ct.AddElement(new Paragraph("line 1")); 
         ct.AddElement(new Paragraph("line 2")); 
         ct.Go();  
         // ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_JUSTIFIED, new Phrase(ph), 8f, 5f, 0); 
        } 
       } 
       bytes = stream.ToArray(); 
      } 
      System.IO.File.WriteAllBytes(filephysicalpath, bytes); 
     } 

我沒有得到這個代碼的頁腳。

+0

乍看起來沒問題,如果你使用'模子#GetOverContent(我)',它的文本還是顯示不出來? –

+0

這永遠不能工作,因爲'新的矩形(10f,10f,0)'永遠不可能是一個適合你的文本的矩形。 –

+0

我更改了代碼...... ColumnText ct = new ColumnText(stamper.GetUnderContent(i)); (新的詞組(新的詞組)(新的詞組(footer,FontFactory.GetFont(FontFactory.HELVETICA,12,Font.NORMAL))), 46,190,590,36,25,Element.ALIGN_LEFT | Element.ALIGN_BOTTOM); ct.Go();它給出正確的輸出,但它覆蓋到PDF文本我該如何解決問題 –

回答

0

這是錯誤的,原因有兩個:

矩形RECT =新的Rectangle(10F,10F,0);

理由1:

沒有辦法,這個代碼可以工作,因爲你創建與左下矩形座標(0, 0),右上座標(10, 10)和旋轉0。這是一個矩形測量值爲0.14 x 0.14英寸(或0.35 x 0.35 cm)。這絕不適合這兩條線!

理由2:

您使用硬編碼值來定義Rectangle。請查看文檔,更具體地查看FAQ條目How to position text relative to page?

您必須獲取現有頁面的尺寸,並相應地定義您的座標!

float marginLR = 36; 
float marginB = 2; 
float footerHeight = 34; 
Rectangle pagesize = reader.GetCropBox(i); 
if (pagesize == null) { 
    pagesize = reader.GetPageSize(i); 
} 
Rectangle rect = new Rectangle(
    pagesize.Left + marginLR, pagesize.Bottom + margin, 
    pagesize.Right - marginLR, pagesize.Bottom + margin + footerheight 
); 

您還可以受益於閱讀Get exact cordinates of the page to add a watermark with different page rotation using iTextSharp

+0

它爲我工作thanx#布魯諾 –