2013-04-11 94 views
0

我需要把一個超鏈接在使用iTextSharp的生成我的PDF頁腳。超鏈接使用iTextSharp的

我知道如何使用PdfPageEventHelper打印頁腳中的一些文本,但不把一個超鏈接。

public class PdfHandlerEvents: PdfPageEventHelper 
    { 
     private PdfContentByte _cb; 
     private BaseFont _bf; 

     public override void OnOpenDocument(PdfWriter writer, Document document) 
     { 
      _cb = writer.DirectContent; 
     } 

     public override void OnEndPage(PdfWriter writer, Document document) 
     { 
      base.OnEndPage(writer, document); 

      _bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); 
      Rectangle pageSize = document.PageSize; 

      _cb.SetRGBColorFill(100, 100, 100); 

      _cb.BeginText(); 
      _cb.SetFontAndSize(_bf, 10); 
      _cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "More information", pageSize.GetRight(200), pageSize.GetBottom(30), 0); 
      _cb.EndText(); 
     } 
    } 

如何使文字「更多信息」超鏈接?

編輯:

從克里斯的回答後下面,我也想出如何在頁腳打印圖像,這裏是代碼:

  Image pic = Image.GetInstance(@"C:\someimage.jpg"); 
      pic.SetAbsolutePosition(0, 0); 
      pic.ScalePercent(25); 

      PdfTemplate tpl = _cb.CreateTemplate(pic.Width, pic.Height); 
      tpl.AddImage(pic); 
      _cb.AddTemplate(tpl, 0, 0); 

回答

2

Document對象一般可讓您與工作抽象的東西,如ParagraphChunk但在這樣做,你失去了絕對定位。 PdfWriterPdfContentByte對象爲您提供絕對定位,但您需要使用原始文本等較低級別的對象。

幸運的是被稱爲ColumnText一個幸福中路地面物體應該做你要找的東西。您可以將ColumnText視爲基本上的表格,大多數人將其用作單列表格,因此實際上可以將其視爲添加對象的矩形。有關任何問題,請參閱下面的代碼中的評論。

public class PdfHandlerEvents : PdfPageEventHelper { 
    private PdfContentByte _cb; 
    private BaseFont _bf; 

    public override void OnOpenDocument(PdfWriter writer, Document document) { 
     _cb = writer.DirectContent; 
    } 

    public override void OnEndPage(PdfWriter writer, Document document) { 
     base.OnEndPage(writer, document); 

     _bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); 
     iTextSharp.text.Rectangle pageSize = document.PageSize; 

     //Create our ColumnText bound to the canvas 
     var ct = new ColumnText(_cb); 
     //Set the dimensions of our "box" 
     ct.SetSimpleColumn(pageSize.GetRight(200), pageSize.GetBottom(30), pageSize.Right, pageSize.Bottom); 
     //Create a new chunk with our text and font 
     var c = new Chunk("More Information", new iTextSharp.text.Font(_bf, 10)); 
     //Set the chunk's action to a remote URL 
     c.SetAction(new PdfAction("http://www.aol.com")); 
     //Add the chunk to the ColumnText 
     ct.AddElement(c); 
     //Tell the ColumnText to draw itself 
     ct.Go(); 

    } 
} 
+0

真棒克里斯,它的工作原理,我從這個代碼做了很多新的技巧!謝謝! – 2013-04-11 23:15:04