using iTextSharp.text; using iTextSharp.text.pdf; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace Common { 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; //文档大小 /// /// 正文字体 /// private static Font font; /// /// 页眉页脚字体 /// public static string HeaderFooterFontName = "黑体"; /// /// 页头页脚字号 /// public static int HeaderFooterFontSize = 10; /// /// 页头页尾字体颜色 /// public static BaseColor HeaderFooterFontColor = BaseColor.BLACK; /// /// 左边页眉 /// public static string HeaderLeft { get; set; } /// /// 右边页眉 /// public static string HeaderRight { get; set; } /// /// 左边页脚 /// public static string FooterLeft { get; set; } /// /// 右边页脚 /// public static string FooterRight { get; set; } #endregion #region 设置页面大小 /// /// 设置页面大小 /// /// 页面大小(如"A4") public static void SetPageSize(string type) { switch (type.Trim()) { case "A4": rect = PageSize.A4; break; case "A8": rect = PageSize.A8; break; } } #endregion #region 设置字体 /// /// 设置字体 /// /// 字体大小 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 生成页眉页脚 /// /// 关闭一个页面时发生 /// 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); } } /// /// 打开一个新页面时发生 /// 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 = 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 = "SIMFANG.TTF"; break; default: file_name = "SIMFANG.TTF"; //file_name = "SIMYOU.TTF"; break; } baseFont = BaseFont.CreateFont(@"c:/windows/fonts/" + file_name, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); return baseFont; } #endregion #region 添加段落 /// /// 添加段落 /// /// 内容 /// 对齐方式(1为居中,0为居左,2为居右) /// 段后空行数(0为默认值) /// 段前空行数(0为默认值) /// 行间距(0为默认值) 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 添加图片 /// /// 添加图片 /// 对齐方式 (0/1/2) /// 页边距 /// 页边距 /// 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; } /// /// 在PDF生成表格 /// public static void CreateTable(DataTable dt, Document document) { iTextSharp.text.pdf.PdfPTable datatable = new PdfPTable(5); float[] headerwidths = { 20, 50, 40, 40, 50}; datatable.SetWidths(headerwidths); datatable.WidthPercentage = 100; datatable.HeaderRows = 1; //datatable.PaddingTop = 5; string[] array = new string[] { "序号", "项目", "结果", "单位", "参考区间" }; for (int i = 0; i < array.Length; i++) { Phrase ph = new Phrase(array[i], font); iTextSharp.text.pdf.PdfPCell cell1 = new PdfPCell(ph); cell1.HorizontalAlignment = Element.ALIGN_CENTER; cell1.BackgroundColor = new iTextSharp.text.BaseColor(0xC0, 0xC0, 0xC0); datatable.AddCell(cell1); } foreach (DataRow R in dt.Rows) { datatable.AddCell(new Phrase(R["sequenceNo"].ToString(), font)); datatable.AddCell(new Phrase(R["itemName"].ToString(), font)); datatable.AddCell(new Phrase(R["result"].ToString(), font)); datatable.AddCell(new Phrase(R["unit"].ToString(), font)); datatable.AddCell(new Phrase(R["range"].ToString(), font)); } document.Add(datatable); } #endregion } }