0

我需要在使用 iTextSharp 生成的 PDF 的页脚处放置一个超链接。

我知道如何使用 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);
4

1 回答 1

2

Document对象通常可以让您使用抽象的东西ParagraphChunk但这样做会失去绝对定位。PdfWriterand对象为您提供绝对定位,PdfContentByte但您需要使用较低级别的对象,如原始文本。

幸运的是,有一个快乐的中间对象,称为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();

    }
}
于 2013-04-11T13:31:40.227 回答