iTextSharp 生成pdf时自动生成页眉页脚

羽化
2016-04-13 / 0 评论 / 477 阅读 / 正在检测是否收录...

用iTextSharp生成pdf的时候往往需要添加页眉页脚,本人开始使用手动生成页眉页脚。也就是在每次document.NewPage();前进行document.Add(**)进行插入需要的页眉页脚。具体如下

iTextSharp.text.Image instance = iTextSharp.text.Image.GetInstance(directoryName + "/Nymoi Logo.jpg");
instance.ScaleToFit(80f, 20f);
iTextSharp.text.Paragraph element = new iTextSharp.text.Paragraph("www.nymoi.com", font10) { Alignment = 2 };
document.Add(instance);
document.Add(element);

这样就手动添加了,但是当页面的内容超出当页范围的时候,会自动创建一页,这个时候就无法手动添加页眉页脚。所以需要通过pdf模板来实现该功能

新建一个HeaderAndFooterEvent的cs文件必须继承PdfPageEventHelper, IPdfPageEvent接口

namespace NymoiAnalyzer.UI
{
    public class HeaderAndFooterEvent : PdfPageEventHelper, IPdfPageEvent
    {
        public static PdfTemplate tpl = null; //模版
        public static bool PAGE_NUMBER = false; //为True时就生成 页眉和页脚

        iTextSharp.text.Font font = BaseFontAndSize("msyh",8, Font.NORMAL, BaseColor.GRAY);

        iTextSharp.text.Font font8 = BaseFontAndSize("msyh",8, Font.BOLD, BaseColor.GRAY);
        iTextSharp.text.Font font8Blk = BaseFontAndSize("msyh", 8, Font.NORMAL, BaseColor.BLACK);

        iTextSharp.text.Font font16 = BaseFontAndSize("begok", 16, Font.BOLD, BaseColor.BLACK);


        //重写 关闭一个页面时
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            if (PAGE_NUMBER)
            {
                Phrase header1 = new Phrase("NYMOI", font16);
                Phrase header2 = new Phrase("www.nymoi.com", font8Blk);

                Phrase footer1 = new Phrase("NYMOI Analyzer 4.0 ", font);
                Phrase footer2 = new Phrase("PAGE " + writer.PageNumber, font);
                PdfContentByte cb = writer.DirectContent;

                //模版 显示总共页数
                cb.AddTemplate(tpl, document.Right - 54 + document.LeftMargin, document.Bottom - 8); //调节模版显示的位置

                //页眉显示的位置
                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, header1, 30 + document.LeftMargin, document.Top+10, 0);
                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, header2, document.Right - 45 + document.LeftMargin, document.Top+10, 0);

                //页脚显示的位置
                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, footer1, 30 + document.LeftMargin, document.Bottom, 0);
                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, footer2, document.Right - 60 + document.LeftMargin, document.Bottom , 0);
                
            }
        }

        //重写 打开一个新页面时
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            if (PAGE_NUMBER)
            {
                writer.PageCount = writer.PageNumber - 1;
            }
        }
        //关闭PDF文档时发生该事件
        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            BaseFont bf = BaseFont.CreateFont(Path.GetDirectoryName(Application.ExecutablePath) + "\\Fonts\\msyh.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            tpl.BeginText();
            //tpl.SetFontAndSize(bf, 16); //生成的模版的字体、颜色
            //tpl.ShowText((writer.PageNumber - 2).ToString()); //模版显示的内容
            tpl.EndText();
            tpl.ClosePath();
        }
        //定义字体 颜色
        public static Font BaseFontAndSize(string fontName, Int32 size, int style, BaseColor baseColor)
        {
            BaseFont baseFont = null;

            Font font = null;
            string file_name = "";
            int fontStyle;

            if (fontName == "msyh")
            {
                baseFont = BaseFont.CreateFont(Path.GetDirectoryName(Application.ExecutablePath) + "\\Fonts\\msyh.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }else if(fontName == "begok")
            {
                baseFont = BaseFont.CreateFont(Path.GetDirectoryName(Application.ExecutablePath) + "\\Fonts\\Begok regular.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            }
            

            if (style < -1)
            {
                fontStyle = Font.NORMAL;
            }
            else
            {
                fontStyle = style;
            }
            font = new Font(baseFont, size, fontStyle, baseColor);
            return font;
        }

        //定义输出文本
        public static Paragraph InsertTitleContent(string text)
        {

            iTextSharp.text.Font font = BaseFontAndSize( "msyh",16, Font.BOLD, BaseColor.BLACK);

            //BaseFont bfSun = BaseFont.CreateFont(@"c:\windows\fonts\STZHONGS.TTF", BaseFont.IDENTITY_H, false); //调用的字体
            //Font font = new Font(bfSun, 15);

            Paragraph paragraph = new Paragraph(text, font); //新建一行
            paragraph.Alignment = Element.ALIGN_CENTER; //居中
            paragraph.SpacingBefore = 5;
            paragraph.SpacingAfter = 5;
            paragraph.SetLeading(1, 2); //每行间的间隔
            return paragraph;
        }
    }
}

在新建pdf并打开的时候插入如下代码:

PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfFilePath, FileMode.Create));
writer.PageEvent = new HeaderAndFooterEvent();
HeaderAndFooterEvent.PAGE_NUMBER = true;//不实现页眉跟页脚
HeaderAndFooterEvent.tpl = writer.DirectContent.CreateTemplate(100, 100); //模版的宽度和高度
PdfContentByte cb = writer.DirectContent;
cb.AddTemplate(HeaderAndFooterEvent.tpl, 266, 714);//调节模版显示的位置

这样就可以了,但是在页眉页脚中无法使用图片,希望哪位实现了,告诉我一下。

0

评论 (0)

取消