前言
前段时间公司需要实现一个PDF文件下载功能,涉及到页眉页脚,段落,图片的生成。遂使用itextsharp来实现这一功能,但是itextsharp功能强大,类库繁多,特别是5.0版本后关于页眉页脚生成的介绍并不多,研究了好久,才弄成功,写下这篇博客做个记录。

先来看下最后实现的效果:

请输入图片描述

下面来看代码
添加引用:

帮助类的代码,这个类可以直接使用,如果你需要增加或者完善某功能,可以对其进行修改。
此类使用方法下面做介绍:

public class HeaderAndFooterEvent : PdfPageEventHelper, IPdfPageEvent
    {
        #region 静态字段

        public static PdfTemplate tpl = null;
        public static bool PAGE_NUMBER = false;//为True时就生成 页眉和页脚  
        public static iTextSharp.text.Rectangle rect = PageSize.A4;   //文档大小

        /// <summary>
        /// 正文字体
        /// </summary>
        private static Font font;

        /// <summary>
        /// 页眉页脚字体
        /// </summary>
        public static string HeaderFooterFontName = "黑体";

        /// <summary>
        /// 页头页脚字号
        /// </summary>
        public static int HeaderFooterFontSize = 10;

        /// <summary>
        /// 页头页尾字体颜色
        /// </summary>
        public static BaseColor HeaderFooterFontColor = BaseColor.BLACK;

        /// <summary>
        /// 左边页眉
        /// </summary>
        public static string HeaderLeft { get; set; }
        /// <summary>
        /// 右边页眉
        /// </summary>
        public static string HeaderRight { get; set; }
        /// <summary>
        /// 左边页脚
        /// </summary>
        public static string FooterLeft { get; set; }
        /// <summary>
        /// 右边页脚
        /// </summary>
        public static string FooterRight { get; set; }

        #endregion

        #region 设置页面大小
        /// <summary>
        /// 设置页面大小
        /// </summary>
        /// <param name="type">页面大小(如"A4")</param>
        public static void SetPageSize(string type)
        {
            switch (type.Trim())
            {
                case "A4":
                    rect = PageSize.A4;
                    break;
                case "A8":
                    rect = PageSize.A8;
                    break;
            }
        }
        #endregion

        #region 设置字体
        /// <summary>
        /// 设置字体
        /// </summary>
        /// <param name="size">字体大小</param>
        public static void SetFont(BaseColor color, string fontName = "华文中宋", float size = 12, int style = Font.NORMAL)
        {
            font = new Font(BaseFontAndSize(fontName), size, style, color);
        }
        #endregion

        #region 生成页眉页脚

        /// <summary>
        /// 关闭一个页面时发生  
        /// </summary>
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            if (PAGE_NUMBER)
            {
                Font HeaderFooterFont = FontAndSize(HeaderFooterFontName, HeaderFooterFontSize, Font.NORMAL, HeaderFooterFontColor);
                Phrase header_left = new Phrase(HeaderLeft, HeaderFooterFont);
                Phrase header_right = new Phrase(HeaderRight, HeaderFooterFont);

                Phrase footer_left = new Phrase(FooterLeft, HeaderFooterFont);
                Phrase footer_center = new Phrase("第" + (writer.PageNumber) + "页/共     页", HeaderFooterFont);
                Phrase footer_right = new Phrase(FooterRight, HeaderFooterFont);



                PdfContentByte cb = writer.DirectContent;

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

                //页眉显示的位置  
                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, header_right,
                       document.Right - 50 + document.LeftMargin, document.Top + 15, 0);

                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, header_left,
                       document.Right - 500 + document.LeftMargin, document.Top + 15, 0);

                //页脚显示的位置  
                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, footer_left,
                       document.Right - 535 + document.LeftMargin, document.Bottom - 15, 0);

                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, footer_center,
                       document.Right - 300 + document.LeftMargin, document.Bottom - 15, 0);

                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, footer_right,
                       document.Right - 80 + document.LeftMargin, document.Bottom - 15, 0);
            }
        }

        /// <summary>
        /// 打开一个新页面时发生 
        /// </summary>
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            if (PAGE_NUMBER)
            {
                writer.PageCount = writer.PageNumber - 1;
            }
        }

        /// <summary>
        /// 关闭PDF文档时发生该事件
        /// </summary>
        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            BaseFont bf = BaseFontAndSize(HeaderFooterFontName);
            tpl.BeginText();
            tpl.SetFontAndSize(bf, HeaderFooterFontSize);
            tpl.ShowText((writer.PageNumber - 1).ToString());//总页数 
            tpl.EndText();
            tpl.ClosePath();
        }
        #endregion

        #region 私有方法

        private static Font FontAndSize(string font_name, int size, int style, BaseColor baseColor)
        {
            BaseFont baseFont;
            BaseFont.AddToResourceSearch("iTextAsian.dll");
            BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
            Font font = null;
            string file_name = "";
            int fontStyle;
            switch (font_name)
            {
                case "黑体":
                    file_name = "SIMHEI.TTF";
                    break;
                case "华文中宋":
                    file_name = "STZHONGS.TTF";
                    break;
                case "宋体":
                    file_name = "SIMYOU.TTF";
                    break;
                default:
                    file_name = "SIMYOU.TTF";
                    break;
            }
            baseFont = BaseFont.CreateFont(@"c:/windows/fonts/" + file_name, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            if (style < -1)
            {
                fontStyle = Font.NORMAL;
            }
            else
            {
                fontStyle = style;
            }
            font = new Font(baseFont, size, fontStyle, baseColor);
            return font;
        }
        private static BaseFont BaseFontAndSize(string font_name)
        {
            BaseFont baseFont;
            BaseFont.AddToResourceSearch("iTextAsian.dll");
            BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
            string file_name = "";
            switch (font_name)
            {
                case "黑体":
                    file_name = "SIMHEI.TTF";
                    break;
                case "华文中宋":
                    file_name = "STZHONGS.TTF";
                    break;
                case "宋体":
                    file_name = "SIMYOU.TTF";
                    break;
                default:
                    file_name = "SIMYOU.TTF";
                    break;
            }
            baseFont = BaseFont.CreateFont(@"c:/windows/fonts/" + file_name, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            return baseFont;
        }

        #endregion

        #region 添加段落

        /// <summary>
        /// 添加段落
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="Alignment">对齐方式(1为居中,0为居左,2为居右)</param>
        /// <param name="SpacingAfter">段后空行数(0为默认值)</param>
        /// <param name="SpacingBefore">段前空行数(0为默认值)</param>
        /// <param name="MultipliedLeading">行间距(0为默认值)</param>
        public static Paragraph AddParagraph(string content, int Alignment, float SpacingAfter, float SpacingBefore, float MultipliedLeading)
        {
            Paragraph pra = new Paragraph(content, font);
            pra.Alignment = Alignment;
            pra.SpacingAfter = SpacingAfter;
            pra.SpacingBefore = SpacingBefore;
            pra.MultipliedLeading = MultipliedLeading;
            return pra;
        }

        public static Paragraph AddParagraph(string content, int Alignment, float MultipliedLeading)
        {
            Paragraph pra = new Paragraph(content, font);
            pra.Alignment = Alignment;
            pra.MultipliedLeading = MultipliedLeading;
            return pra;
        }

        public static void AddPhrase(PdfWriter writer, Document document, string content, float marginLift, float marginBottom)
        {
            Phrase phrase = new Phrase(content, font);

            PdfContentByte cb = writer.DirectContent;
            ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, phrase,
                       marginLift + document.LeftMargin, marginBottom, 0);

        }

        #endregion

        #region 添加图片
        /// <summary>
        /// 添加图片
        /// <param name="Alignment">对齐方式 (0/1/2)</param>
        /// <param name="marginRight">页边距</param>
        /// <param name="marginBottom">页边距</param>
        /// </summary>
        public static iTextSharp.text.Image AddImage(string path, int Alignment, float marginRight, float marginBottom)
        {
            Image img = Image.GetInstance(new Uri(path));
            img.Alignment = Alignment;
            //等比缩放,宽与高的缩放系数哪个大就取哪一个(比如高的系数是0.8,宽的是0.7,则取0.7。这样图片就不会超出页面范围)
            if (img.Width > img.Height)
            {
                //这里计算图片的缩放系数,因为图片width>height,所以将图片旋转90度以适应页面,计算缩放系数的时候宽与高对调
                float PageHeight = PageSize.A4.Height - marginBottom * 3;
                double percentHeight = Math.Round((PageHeight / img.Width), 2);

                float PageWidth = PageSize.A4.Width - marginRight * 2;
                double percentWidth = Math.Round((PageWidth / img.Height), 2);

                double percent = percentHeight > percentWidth ? percentWidth : percentHeight;
                img.ScalePercent((float)percent * 100);
                img.RotationDegrees = 90f;
            }
            else
            {
                float PageHeight = PageSize.A4.Height - marginBottom * 3;
                double percentHeight = Math.Round((PageHeight / img.Height), 2);

                float PageWidth = PageSize.A4.Width - marginRight * 2;
                double percentWidth = Math.Round((PageWidth / img.Width), 2);

                double percent = percentHeight > percentWidth ? percentWidth : percentHeight;
                img.ScalePercent((float)percent * 100);
            }
            return img;
        }
        #endregion

    }

下面是使用方法:

在你需要生成文件的地方实例化Document和PdfWriter 对象:

Document document = new Document(HeaderAndFooterEvent.rect);
//此处使用的是http请求的流,你也可以使用文件流Stream
PdfWriter writer = PdfWriter.GetInstance(document, HttpContext.Current.Response.OutputStream);
document.Open();
writer.PageEvent = new HeaderAndFooterEvent();

实现页眉和页脚:

HeaderAndFooterEvent.PAGE_NUMBER = true;//实现页眉跟页脚  
HeaderAndFooterEvent.tpl = writer.DirectContent.CreateTemplate(500, 500); //定义模板

HeaderAndFooterEvent.HeaderLeft = "Aviation Meteorological Center";
HeaderAndFooterEvent.HeaderRight = "民航气象中心";
HeaderAndFooterEvent.FooterLeft = "TEL:010-87922095";
HeaderAndFooterEvent.FooterRight = _dtm.ToString("yyyy-MM-dd HH:mm:ss") + "(UTC)";

首页

//每次在添加文本内容之前可以先设置字体,有效期持续到重新设置之前
HeaderAndFooterEvent.SetFont(BaseColor.BLACK, "宋体", 25, Font.BOLD);
//添加一个空段落来占位,五个参数分别为:内容,对齐方式(1为居中,0为居左,2为居右),段后空行数,段前空行数,行间距
document.Add(HeaderAndFooterEvent.AddParagraph(" ", 1, 200, 0, 1.5f));

//这个方法为上一个方法的重载,三个参数分别为:内容,对齐方式,行间距
document.Add(HeaderAndFooterEvent.AddParagraph("飞行气象文件", 1, 1.5f));
HeaderAndFooterEvent.SetFont(BaseColor.BLACK, "宋体", 18, Font.BOLD);
document.Add(HeaderAndFooterEvent.AddParagraph("Meteorological Aviation Report", 1, 1.5f));

然后就是新建页了,每需要一页的时候就 document.NewPage(); 就可以了,当然,如果你在其中一页添加的内容超过了此页的篇幅,则会自动追加一页。下面演示怎么新建一页并添加内容:

document.NewPage();

HeaderAndFooterEvent.SetFont(BaseColor.DARK_GRAY, "宋体", 15, Font.BOLD);
document.Add(HeaderAndFooterEvent.AddParagraph("飞行气象文件", 1, 1.5f));
HeaderAndFooterEvent.SetFont(BaseColor.DARK_GRAY, "宋体", 12);
document.Add(HeaderAndFooterEvent.AddParagraph("航班号:      " ));

下面演示添加图片:
添加图片比较简单,当图片的宽度超过高度时,会进行旋转并按照比例缩放,从而尽量铺满整个页面。如果你不需要旋转,可以对帮助类进行修改。

document.NewPage();

//四个参数分别为:图片路径,对齐方式,文档的右边距,下边距;边距这两个参数用于计算图片的缩放尺寸。
document.Add("图片路径", 0, document.RightMargin, document.Bottom));

到现在,大功告成
只需要关闭文档和流就行了。

writer.Flush();
writer.CloseStream = true;
document.Close();

标签: itextsharp

添加新评论