前言
前段时间公司需要实现一个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();

C#使用itextsharp生成PDF文件相关推荐

  1. 生成PDF文件方案--学习中

    PDF文件是目前比较流行的电子文档格式,在办公自动化(OA)等软件的开发中,经常要用到该格式,但介绍如何制作PDF格式文件的资料非常少,在网上搜来搜去,都转贴的是同一段"暴力"破解 ...

  2. NET|C#生成PDF文件

    转自: 项目需要在线生成PDF文件,我首先考虑采用itextsharp控件来实现.具体方法参考 https://sourceforge.net/projects/itextsharp/ 1.首先利用n ...

  3. python使用fpdf生成pdf文件章节(chapter),包含:页眉、页脚、章节主题、数据排版等;

    python使用fpdf生成pdf文件章节(chapter),包含:页眉.页脚.章节主题.数据排版等: #仿真数据 The year 1866 was marked by a bizarre deve ...

  4. python使用fpdf生成pdf文件:配置多种语言字体写入多种文字

    python使用fpdf生成pdf文件:配置多种语言字体写入多种文字 目录

  5. 一步快速将Smartform output转成生成PDF文件

    世间竟有如此盖世神功!最简单的smart form output转化成 PDF文件的方式.   Form打印预览界面在事务栏输入T-code:PDF!,注意!为半角英文状态下的感叹号. 输入T-cod ...

  6. 安装texlive并用latex编写一段中文,最后生成pdf文件

    安装texlive并用latex编写一段中文,最后生成pdf文件 **#一.下载安装(**链接https://tug.org/texlive/) ##1.第一步 ##2.第二步 ##3.第三步 ##4 ...

  7. 小容量单片机生成pdf文件

    工作上要求使用小容量单片机生成直接生成pdf文件. 经过一段时间的摸索,其中参考了libharu,库太大,不适合在单片机上使用 页参考了与非网上一位前辈的库,占用的RAM太大,不适合小容量单片机, 主 ...

  8. php输出PDF的文件流_怎么用PHP在HTML中生成PDF文件

    译文:使用PHP在html中生成PDF 译者:dwqs 利用PHP编码生成PDF文件是一个非常耗时的工作.在早期,开发者使用PHP并借助FPDF来生成PDF文件.但是如今,已经有很多函数库可以使用了, ...

  9. python数据生成pdf,Python生成pdf文件的方法

    摘要:这篇Python开发技术栏目下的"Python生成pdf文件的方法",介绍的技术点是"python生成pdf文件.python生成pdf.生成pdf文件.Pytho ...

最新文章

  1. 技术分享连载(六十九)
  2. javaweb回顾第二篇tomcat和web程序部署
  3. Testing and Test-First Programming
  4. 深度学习之基于Inception_ResNet_V2和CNN实现交通标志识别
  5. SQL Server Profiler 常见问题总结
  6. 撤消git update-index --assume-unchanged file
  7. Angular CLI: 全局脚本
  8. Java学习笔记(20)
  9. vue-router 中踏过的坑
  10. 新手linux版本,六款适用于新手的非Ubuntu Linux发行版
  11. cad怎么导出jpg图片格式?
  12. 什么是功率因数补偿/校正
  13. mac/macbook触摸板/鼠标/键盘失灵
  14. 阅读这篇文章,假设你不知道的傅里叶变换,然后来掐死我
  15. 【数学知识】非线性方程求解的二分法以及牛顿迭代法
  16. ensp WLAN二层零漫游
  17. PKU C++课程期末编程题解答
  18. 产品之 2B、2C与2G
  19. 华为ModelArts自定义镜像(PyTorch镜像)
  20. 南信与南邮谁的计算机专业更强,南京信息工程大学和南京邮电大学,谁更强!网友:“不相上下”!...

热门文章

  1. 五年Java程序员进阶架构师的一些心得以及职业生涯规划
  2. iOS开发面试攻略(KVO、KVC、多线程、锁、runloop、计时器)
  3. ts重点学习136-声明合并
  4. 如何进行质量管理(转载)
  5. java中小数的处理:高精度运算用bigDecimal类,精度保留方法,即舍入方式的指定
  6. STM32项目设计:基于STM32指纹密码锁
  7. android 笔记本推荐 2015年,5千内适合Android开发的笔记本电脑大推荐
  8. MODIS数据下载方法
  9. SDUT数据结构实验之链表一:顺序建立链表
  10. LTE RACH过程