iTextSharp5.0页眉页脚及Asp.net预览的实现(PDF导出)

iTextSharp5.0后没有了HeaderFooter的类,导致页眉页脚难以实现。经查资料后,发现可以通过PdfPageEventHelper里面的OnEndPage来实现。先看看实现的效果图。


页眉和页脚部分使用PdfPTable来达成,下面是实现代码

[html]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using iTextSharp.text;  
  7. using iTextSharp.text.pdf;  
  8.   
  9. namespace ITextSharpTest  
  10. {  
  11.     public class PDFBase : PdfPageEventHelper  
  12.     {  
  13.         #region 属性  
  14.         private String _fontFilePathForHeaderFooter = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "SIMHEI.TTF");  
  15.         /// <summary>  
  16.         /// 页眉/页脚所用的字体  
  17.         /// </summary>  
  18.         public String FontFilePathForHeaderFooter  
  19.         {  
  20.             get  
  21.             {  
  22.                 return _fontFilePathForHeaderFooter;  
  23.             }  
  24.   
  25.             set  
  26.             {  
  27.                 _fontFilePathForHeaderFooter = value;  
  28.             }  
  29.         }  
  30.   
  31.         private String _fontFilePathForBody = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "SIMSUN.TTC,1");  
  32.         /// <summary>  
  33.         /// 正文内容所用的字体  
  34.         /// </summary>  
  35.         public String FontFilePathForBody  
  36.         {  
  37.             get { return _fontFilePathForBody; }  
  38.             set { _fontFilePathForBody = value; }  
  39.         }  
  40.   
  41.   
  42.         private PdfPTable _header;  
  43.         /// <summary>  
  44.         /// 页眉  
  45.         /// </summary>  
  46.         public PdfPTable Header  
  47.         {  
  48.             get { return _header; }  
  49.             private set { _header = value; }  
  50.         }  
  51.   
  52.         private PdfPTable _footer;  
  53.         /// <summary>  
  54.         /// 页脚  
  55.         /// </summary>  
  56.         public PdfPTable Footer  
  57.         {  
  58.             get { return _footer; }  
  59.             private set { _footer = value; }  
  60.         }  
  61.   
  62.   
  63.         private BaseFont _baseFontForHeaderFooter;  
  64.         /// <summary>  
  65.         /// 页眉页脚所用的字体  
  66.         /// </summary>  
  67.         public BaseFont BaseFontForHeaderFooter  
  68.         {  
  69.             get { return _baseFontForHeaderFooter; }  
  70.             set { _baseFontForHeaderFooter = value; }  
  71.         }  
  72.   
  73.         private BaseFont _baseFontForBody;  
  74.         /// <summary>  
  75.         /// 正文所用的字体  
  76.         /// </summary>  
  77.         public BaseFont BaseFontForBody  
  78.         {  
  79.             get { return _baseFontForBody; }  
  80.             set { _baseFontForBody = value; }  
  81.         }  
  82.   
  83.         private Document _document;  
  84.         /// <summary>  
  85.         /// PDF的Document  
  86.         /// </summary>  
  87.         public Document Document  
  88.         {  
  89.             get { return _document; }  
  90.             private set { _document = value; }  
  91.         }  
  92.   
  93.         #endregion  
  94.   
  95.   
  96.         public override void OnOpenDocument(PdfWriter writer, Document document)  
  97.         {  
  98.             try  
  99.             {  
  100.                 BaseFontForHeaderFooter = BaseFont.CreateFont(FontFilePathForHeaderFooter, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);  
  101.                 BaseFontForBody = BaseFont.CreateFont(FontFilePathForBody, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);  
  102.                 Document = document;  
  103.             }  
  104.             catch (DocumentException de)  
  105.             {  
  106.   
  107.             }  
  108.             catch (System.IO.IOException ioe)  
  109.             {  
  110.   
  111.             }  
  112.         }  
  113.   
  114.         #region GenerateHeader  
  115.         /// <summary>  
  116.         /// 生成页眉  
  117.         /// </summary>  
  118.         /// <param name="writer"></param>  
  119.         /// <returns></returns>  
  120.         public virtual PdfPTable GenerateHeader(iTextSharp.text.pdf.PdfWriter writer)  
  121.         {  
  122.             return null;  
  123.         }  
  124.         #endregion  
  125.   
  126.         #region GenerateFooter  
  127.         /// <summary>  
  128.         /// 生成页脚  
  129.         /// </summary>  
  130.         /// <param name="writer"></param>  
  131.         /// <returns></returns>  
  132.         public virtual PdfPTable GenerateFooter(iTextSharp.text.pdf.PdfWriter writer)  
  133.         {  
  134.             return null;  
  135.         }  
  136.         #endregion  
  137.   
  138.         public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)  
  139.         {  
  140.             base.OnEndPage(writer, document);  
  141.   
  142.             //输出页眉  
  143.             Header = GenerateHeader(writer);  
  144.             Header.TotalWidth = document.PageSize.Width - 20f;  
  145.             ///调用PdfTable的WriteSelectedRows方法。该方法以第一个参数作为开始行写入。  
  146.             ///第二个参数-1表示没有结束行,并且包含所写的所有行。  
  147.             ///第三个参数和第四个参数是开始写入的坐标x和y.  
  148.             Header.WriteSelectedRows(0, -1, 10, document.PageSize.Height - 20, writer.DirectContent);  
  149.   
  150.             //输出页脚  
  151.             Footer = GenerateFooter(writer);  
  152.             Footer.TotalWidth = document.PageSize.Width - 20f;  
  153.             Footer.WriteSelectedRows(0, -1, 10, document.PageSize.GetBottom(50), writer.DirectContent);  
  154.         }  
  155.     }  
  156. }  

注:为了便于使用,做了一个PDFBase,后续只需要继承即可。

[html]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using iTextSharp.text;  
  8. using iTextSharp.text.pdf;  
  9.   
  10. namespace ITextSharpTest  
  11. {  
  12.     /// <summary>  
  13.     /// PDF报表  
  14.     /// </summary>  
  15.     public class PDFReport : PDFBase  
  16.     {  
  17.         #region 属性  
  18.         private int _pageRowCount = 12;  
  19.         /// <summary>  
  20.         /// 每页的数据行数  
  21.         /// </summary>  
  22.         public int PageRowCount  
  23.         {  
  24.             get { return _pageRowCount; }  
  25.             set { _pageRowCount = value; }  
  26.         }  
  27.         #endregion  
  28.   
  29.         /// <summary>  
  30.         /// 模拟数据。实际时可能需要从数据库或网络中获取.  
  31.         /// </summary>  
  32.         private DataTable _dtSimulateData = null;  
  33.   
  34.         private DataTable GenerateSimulateData()  
  35.         {  
  36.             DataTable dtSimulateData = new DataTable();  
  37.             dtSimulateData.Columns.Add("Order", typeof(int));//序号  
  38.             dtSimulateData.Columns.Add("No");//料号  
  39.             dtSimulateData.Columns.Add("Name");//名称  
  40.             dtSimulateData.Columns.Add("Type");//类型  
  41.             dtSimulateData.Columns.Add("GetTime");//领取时间  
  42.             dtSimulateData.Columns.Add("BackTime");//归还时间  
  43.             dtSimulateData.Columns.Add("Remark");//备注  
  44.             DataRow row = null;  
  45.             String[] types = new string[] { "文具", "辅料", "生活用品", "测试用具", "实体机" };  
  46.             DateTime getDate = DateTime.Now;  
  47.             DateTime backDate = DateTime.Now;  
  48.             for (int i = 0; i < 100; i++)  
  49.             {  
  50.                 row = dtSimulateData.NewRow();  
  51.                 row["Order"] = i + 1;  
  52.                 row["No"] = (10000 + i + 1).ToString();  
  53.                 row["Name"] = Guid.NewGuid().ToString().Substring(0, 5);//造出随机名称  
  54.                 row["Type"] = types[(i * 3) % 5];  
  55.                 row["GetTime"] = getDate.AddDays(i).ToString("yyyy-MM-dd");  
  56.                 row["BackTime"] = ((i + i) % 3 == 0) ? "" : (backDate.AddDays(i + (i * 3) % 8).ToString("yyyy-MM-dd"));//造出没有归还时间的数据  
  57.                 row["Remark"] = "XXXXXXX";  
  58.                 dtSimulateData.Rows.Add(row);  
  59.             }  
  60.             return dtSimulateData;  
  61.         }  
  62.   
  63.         #region GenerateHeader  
  64.         /// <summary>  
  65.         /// 生成页眉  
  66.         /// </summary>  
  67.         /// <param name="fontFilePath"></param>  
  68.         /// <param name="pageNumber"></param>  
  69.         /// <returns></returns>  
  70.         public override PdfPTable GenerateHeader(iTextSharp.text.pdf.PdfWriter writer)  
  71.         {  
  72.             BaseFont baseFont = BaseFontForHeaderFooter;  
  73.             iTextSharp.text.Font font_logo = new iTextSharp.text.Font(baseFont, 30, iTextSharp.text.Font.BOLD);  
  74.             iTextSharp.text.Font font_header1 = new iTextSharp.text.Font(baseFont, 16, iTextSharp.text.Font.BOLD);  
  75.             iTextSharp.text.Font font_header2 = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.BOLD);  
  76.             iTextSharp.text.Font font_headerContent = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL);  
  77.   
  78.             float[] widths = new float[] { 55, 300, 50, 90, 15, 20, 15 };  
  79.   
  80.             PdfPTable header = new PdfPTable(widths);  
  81.             PdfPCell cell = new PdfPCell();  
  82.             cell.BorderWidthBottom = 2;  
  83.             cell.BorderWidthLeft = 2;  
  84.             cell.BorderWidthTop = 2;  
  85.             cell.BorderWidthRight = 2;  
  86.             cell.FixedHeight = 35;  
  87.             cell.Phrase = new Phrase("LOGO", font_logo);  
  88.             cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;  
  89.             cell.VerticalAlignment = iTextSharp.text.Element.ALIGN_CENTER;  
  90.             cell.PaddingTop = -1;  
  91.             header.AddCell(cell);  
  92.   
  93.             cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_LEFT);  
  94.             cell.Phrase = new Paragraph("PDF报表示例", font_header1);  
  95.             header.AddCell(cell);  
  96.   
  97.   
  98.             cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_RIGHT);  
  99.             cell.Phrase = new Paragraph("日期:", font_header2);  
  100.             header.AddCell(cell);  
  101.   
  102.             cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_LEFT);  
  103.             cell.Phrase = new Paragraph("2015-07-27", font_headerContent);  
  104.             header.AddCell(cell);  
  105.   
  106.             cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_RIGHT);  
  107.             cell.Phrase = new Paragraph("第", font_header2);  
  108.             header.AddCell(cell);  
  109.   
  110.             cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_CENTER);  
  111.             cell.Phrase = new Paragraph(writer.PageNumber.ToString(), font_headerContent);  
  112.             header.AddCell(cell);  
  113.   
  114.             cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_RIGHT);  
  115.             cell.Phrase = new Paragraph("页", font_header2);  
  116.             header.AddCell(cell);  
  117.             return header;  
  118.         }  
  119.   
  120.         #region GenerateOnlyBottomBorderCell  
  121.         /// <summary>  
  122.         /// 生成只有底边的cell  
  123.         /// </summary>  
  124.         /// <param name="bottomBorder"></param>  
  125.         /// <param name="horizontalAlignment">水平对齐方式<see cref="iTextSharp.text.Element"/></param>  
  126.         /// <returns></returns>  
  127.         private PdfPCell GenerateOnlyBottomBorderCell(int bottomBorder,  
  128.                                                             int horizontalAlignment)  
  129.         {  
  130.             PdfPCell cell = GenerateOnlyBottomBorderCell(bottomBorder, horizontalAlignment, iTextSharp.text.Element.ALIGN_BOTTOM);  
  131.             cell.PaddingBottom = 5;  
  132.             return cell;  
  133.         }  
  134.   
  135.         /// <summary>  
  136.         /// 生成只有底边的cell  
  137.         /// </summary>  
  138.         /// <param name="bottomBorder"></param>  
  139.         /// <param name="horizontalAlignment">水平对齐方式<see cref="iTextSharp.text.Element"/></param>  
  140.         /// <param name="verticalAlignment">垂直对齐方式<see cref="iTextSharp.text.Element"/</param>  
  141.         /// <returns></returns>  
  142.         private PdfPCell GenerateOnlyBottomBorderCell(int bottomBorder,  
  143.                                                             int horizontalAlignment,  
  144.                                                             int verticalAlignment)  
  145.         {  
  146.             PdfPCell cell = GenerateOnlyBottomBorderCell(bottomBorder);  
  147.             cell.HorizontalAlignment = horizontalAlignment;  
  148.             cell.VerticalAlignment = verticalAlignment; ;  
  149.             return cell;  
  150.         }  
  151.   
  152.         /// <summary>  
  153.         /// 生成只有底边的cell  
  154.         /// </summary>  
  155.         /// <param name="bottomBorder"></param>  
  156.         /// <returns></returns>  
  157.         private PdfPCell GenerateOnlyBottomBorderCell(int bottomBorder)  
  158.         {  
  159.             PdfPCell cell = new PdfPCell();  
  160.             cell.BorderWidthBottom = 2;  
  161.             cell.BorderWidthLeft = 0;  
  162.             cell.BorderWidthTop = 0;  
  163.             cell.BorderWidthRight = 0;  
  164.             return cell;  
  165.         }  
  166.         #endregion  
  167.   
  168.         #endregion  
  169.   
  170.         #region GenerateFooter  
  171.         public override PdfPTable GenerateFooter(iTextSharp.text.pdf.PdfWriter writer)  
  172.         {  
  173.             BaseFont baseFont = BaseFontForHeaderFooter;  
  174.             iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL);  
  175.   
  176.             PdfPTable footer = new PdfPTable(3);  
  177.             AddFooterCell(footer, "审阅:", font);  
  178.             AddFooterCell(footer, "审批:", font);  
  179.             AddFooterCell(footer, "制表:张三", font);  
  180.             return footer;  
  181.         }  
  182.   
  183.         private void AddFooterCell(PdfPTable foot, String text, iTextSharp.text.Font font)  
  184.         {  
  185.             PdfPCell cell = new PdfPCell();  
  186.             cell.BorderWidthTop = 2;  
  187.             cell.BorderWidthRight = 0;  
  188.             cell.BorderWidthBottom = 0;  
  189.             cell.BorderWidthLeft = 0;  
  190.             cell.Phrase = new Phrase(text, font);  
  191.             cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;  
  192.             foot.AddCell(cell);  
  193.         }  
  194.         #endregion  
  195.   
  196.         #region ExportPDF  
  197.         /// <summary>  
  198.         /// 导出PDF  
  199.         /// </summary>  
  200.         /// <param name="path">导出路径</param>  
  201.         public static void ExportPDF(String path)  
  202.         {  
  203.             PDFReport pdfReport = new PDFReport();  
  204.             Document document = new Document(PageSize.A4.Rotate(), -90, -90, 60, 10);//此处设置的偏移量是为了加大页面的可用范围,可以使用默认.  
  205.             PdfWriter pdfWriter = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));  
  206.             pdfWriter.PageEvent = pdfReport;//此处一定要赋值,才能触发页眉和页脚的处理  
  207.             document.Open();  
  208.             pdfReport.AddBody(document);  
  209.             document.Close();  
  210.         }  
  211.   
  212.         /// <summary>  
  213.         /// 导出PDF  
  214.         /// </summary>  
  215.         /// <param name="path">导出路径</param>  
  216.         public static byte[] ExportPDF()  
  217.         {  
  218.             PDFReport pdfReport = new PDFReport();  
  219.             Document document = new Document(PageSize.A4.Rotate(), -90, -90, 60, 10);//此处设置的偏移量是为了加大页面的可用范围,可以使用默认.  
  220.             MemoryStream ms = new MemoryStream();  
  221.             PdfWriter pdfWriter = PdfWriter.GetInstance(document, ms);  
  222.             pdfWriter.PageEvent = pdfReport;//此处一定要赋值,才能触发页眉和页脚的处理  
  223.             document.Open();  
  224.             pdfReport.AddBody(document);  
  225.             document.Close();  
  226.             byte[] buff = ms.ToArray();  
  227.             return buff;  
  228.         }  
  229.         #endregion  
  230.   
  231.         #region AddBody  
  232.         private void AddBody(Document document)  
  233.         {  
  234.             _dtSimulateData = GenerateSimulateData();  
  235.             int count = (_dtSimulateData.Rows.Count + (PageRowCount - 1)) / PageRowCount;  
  236.             for (int i = 0; i < count; i++)  
  237.             {  
  238.                 AddBodySinglePage(i + 1);  
  239.                 document.NewPage();  
  240.             }  
  241.         }  
  242.   
  243.         private void AddBodySinglePage(int pageNumber)  
  244.         {  
  245.             BaseFont baseFont = BaseFontForBody;  
  246.             iTextSharp.text.Font font_columnHeader = new iTextSharp.text.Font(baseFont, 11f, iTextSharp.text.Font.BOLD);  
  247.             iTextSharp.text.Font font_contentNormal = new iTextSharp.text.Font(baseFont, 9.5f, iTextSharp.text.Font.NORMAL);  
  248.             iTextSharp.text.Font font_contentSmall = new iTextSharp.text.Font(baseFont, 8f, iTextSharp.text.Font.NORMAL);  
  249.   
  250.             int columnCount = 6;//此处是为了当列数很多时,便于循环生成所要的列宽比例  
  251.             float[] widths = new float[columnCount];  
  252.             for (int i = 0; i < columnCount; i++)  
  253.             {  
  254.                 widths[i] = 1;  
  255.             }  
  256.             //需要加宽的再进行额外处理  
  257.             widths[3] = 2;//时间  
  258.             widths[4] = 3;//备注  
  259.   
  260.             PdfPTable bodyTable = new PdfPTable(widths);  
  261.             bodyTable.SpacingBefore = 10;//与头部的距离  
  262.   
  263.             AddBodyHeader(bodyTable, font_columnHeader);  
  264.             AddBodyContent(bodyTable, font_contentNormal, font_contentSmall, pageNumber);  
  265.   
  266.             Document.Add(bodyTable);  
  267.         }  
  268.   
  269.         #region AddBodyHeader  
  270.         /// <summary>  
  271.         /// 添加Body的列标题  
  272.         /// </summary>  
  273.         /// <param name="document"></param>  
  274.         /// <param name="font_columnHeader"></param>  
  275.         private void AddBodyHeader(PdfPTable bodyTable, iTextSharp.text.Font font_columnHeader)  
  276.         {  
  277.             //采用Rowspan和Colspan来控制单元格的合并与拆分,类似于HTML的Table.  
  278.             AddColumnHeaderCell(bodyTable, "料号", font_columnHeader, 1, 2);  
  279.             AddColumnHeaderCell(bodyTable, "名称", font_columnHeader, 1, 2);  
  280.             AddColumnHeaderCell(bodyTable, "种类", font_columnHeader, 1, 2);  
  281.             AddColumnHeaderCell(bodyTable, "时间", font_columnHeader, 2, 1);//表头下还有两列表头  
  282.             AddColumnHeaderCell(bodyTable, "备注", font_columnHeader, 1, 2, true, true);  
  283.   
  284.             //时间  
  285.             AddColumnHeaderCell(bodyTable, "领取", font_columnHeader);  
  286.             AddColumnHeaderCell(bodyTable, "归还", font_columnHeader, true, true);  
  287.         }  
  288.         #endregion  
  289.   
  290.         #region AddBodyContent Function  
  291.         /// <summary>  
  292.         /// 添加报表正文  
  293.         /// </summary>  
  294.         /// <param name="bodyTable"></param>  
  295.         /// <param name="fontNormal">普通字体</param>  
  296.         /// <param name="fontSmall">小字体,当内容显示不下,需要使用小字体来显示时,可以使用.</param>  
  297.         /// <param name="pageNumber">页码。便于从数据库中按页拉取数据时使用.</param>  
  298.         public void AddBodyContent(PdfPTable bodyTable,  
  299.                                    iTextSharp.text.Font fontNormal,  
  300.                                    iTextSharp.text.Font fontSmall,  
  301.                                    int pageNumber)  
  302.         {  
  303.             String filterExpression = String.Format("Order>{0} AND Order<={1}",  
  304.                                                     (pageNumber - 1) * PageRowCount,  
  305.                                                      pageNumber * PageRowCount);  
  306.             DataRow[] rows = _dtSimulateData.Select(filterExpression);  
  307.             foreach (var row in rows)  
  308.             {  
  309.                 AddBodyContentRow(bodyTable, fontNormal, fontSmall, row);  
  310.             }  
  311.         }  
  312.   
  313.         private void AddBodyContentRow(PdfPTable bodyTable, iTextSharp.text.Font fontNormal, iTextSharp.text.Font fontSmall, DataRow row)  
  314.         {  
  315.             AddBodyContentCell(bodyTable, String.Format("{0}", row["No"]), fontNormal);//料号  
  316.             AddBodyContentCell(bodyTable, String.Format("{0}", row["Name"]), fontNormal);//名称  
  317.             AddBodyContentCell(bodyTable, String.Format("{0}", row["Type"]), fontNormal);//种类  
  318.             AddBodyContentCell(bodyTable, String.Format("{0}", row["GetTime"]), fontSmall, 1);//时间-领取  
  319.             String backTime = String.Format("{0}", row["BackTime"]);  
  320.             AddBodyContentCell(bodyTable, backTime, fontSmall);//时间-归还  
  321.             AddBodyContentCell(bodyTable, String.Format("{0}", row["Remark"]), fontSmall, 2, true);//备注    
  322.   
  323.             AddBodyContentCell(bodyTable, (String.IsNullOrWhiteSpace(backTime)) ? "消耗品不需归还" : "", fontSmall, 1);//时间-领取(下方说明)  
  324.         }  
  325.   
  326.         private static void AddBodyContentCell(PdfPTable bodyTable,  
  327.                                                String text,  
  328.                                                iTextSharp.text.Font font,  
  329.                                                int rowspan = 2,  
  330.                                                bool needRightBorder = false)  
  331.         {  
  332.             PdfPCell cell = new PdfPCell();  
  333.             float defaultBorder = 0.5f;  
  334.             cell.BorderWidthLeft = defaultBorder;  
  335.             cell.BorderWidthTop = 0;  
  336.             cell.BorderWidthRight = needRightBorder ? defaultBorder : 0;  
  337.             cell.BorderWidthBottom = defaultBorder;  
  338.             cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;  
  339.             cell.VerticalAlignment = iTextSharp.text.Element.ALIGN_BASELINE;  
  340.             cell.Rowspan = rowspan;  
  341.             cell.PaddingBottom = 4;  
  342.             cell.Phrase = new Phrase(text, font);  
  343.             cell.FixedHeight = 18f;  
  344.             bodyTable.AddCell(cell);  
  345.         }  
  346.         #endregion  
  347.   
  348.         #region AddColumnHeaderCell Function  
  349.         /// <summary>  
  350.         /// 添加列标题单元格  
  351.         /// </summary>  
  352.         /// <param name="table">表格行的单元格列表</param>  
  353.         /// <param name="header">标题</param>  
  354.         /// <param name="font">字段</param>  
  355.         /// <param name="colspan">列空间</param>  
  356.         /// <param name="rowspan">行空间</param>  
  357.         /// <param name="needLeftBorder">是否需要左边框</param>  
  358.         /// <param name="needRightBorder">是否需要右边框</param>  
  359.         public void AddColumnHeaderCell(PdfPTable table,  
  360.                                                 String header,  
  361.                                                 iTextSharp.text.Font font,  
  362.                                                 int colspan,  
  363.                                                 int rowspan,  
  364.                                                 bool needLeftBorder = true,  
  365.                                                 bool needRightBorder = false)  
  366.         {  
  367.             PdfPCell cell = GenerateColumnHeaderCell(header, font, needLeftBorder, needRightBorder);  
  368.             if (colspan > 1)  
  369.             {  
  370.                 cell.Colspan = colspan;  
  371.             }  
  372.   
  373.             if (rowspan > 1)  
  374.             {  
  375.                 cell.Rowspan = rowspan;  
  376.             }  
  377.   
  378.             table.AddCell(cell);  
  379.         }  
  380.   
  381.         /// <summary>  
  382.         /// 添加列标题单元格  
  383.         /// </summary>  
  384.         /// <param name="table">表格</param>  
  385.         /// <param name="header">标题</param>  
  386.         /// <param name="font">字段</param>  
  387.         /// <param name="needLeftBorder">是否需要左边框</param>  
  388.         /// <param name="needRightBorder">是否需要右边框</param>  
  389.         public void AddColumnHeaderCell(PdfPTable table,  
  390.                                                 String header,  
  391.                                                 iTextSharp.text.Font font,  
  392.                                                 bool needLeftBorder = true,  
  393.                                                 bool needRightBorder = false)  
  394.         {  
  395.             PdfPCell cell = GenerateColumnHeaderCell(header, font, needLeftBorder, needRightBorder);  
  396.             table.AddCell(cell);  
  397.         }  
  398.         #endregion  
  399.   
  400.         #region GenerateColumnHeaderCell  
  401.         /// <summary>  
  402.         /// 生成列标题单元格  
  403.         /// </summary>  
  404.         /// <param name="header">标题</param>  
  405.         /// <param name="font">字段</param>  
  406.         /// <param name="needLeftBorder">是否需要左边框</param>  
  407.         /// <param name="needRightBorder">是否需要右边框</param>  
  408.         /// <returns></returns>  
  409.         private PdfPCell GenerateColumnHeaderCell(String header,  
  410.                                                         iTextSharp.text.Font font,  
  411.                                                         bool needLeftBorder = true,  
  412.                                                         bool needRightBorder = false)  
  413.         {  
  414.             PdfPCell cell = new PdfPCell();  
  415.             float border = 0.5f;  
  416.             cell.BorderWidthBottom = border;  
  417.             if (needLeftBorder)  
  418.             {  
  419.                 cell.BorderWidthLeft = border;  
  420.             }  
  421.             else  
  422.             {  
  423.                 cell.BorderWidthLeft = 0;  
  424.             }  
  425.   
  426.             cell.BorderWidthTop = border;  
  427.             if (needRightBorder)  
  428.             {  
  429.                 cell.BorderWidthRight = border;  
  430.             }  
  431.             else  
  432.             {  
  433.                 cell.BorderWidthRight = 0;  
  434.             }  
  435.   
  436.             cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;  
  437.             cell.VerticalAlignment = iTextSharp.text.Element.ALIGN_BASELINE;  
  438.             cell.PaddingBottom = 4;  
  439.             cell.Phrase = new Phrase(header, font);  
  440.             return cell;  
  441.         }  
  442.         #endregion  
  443.   
  444.         #endregion  
  445.     }  
  446. }  
注:代码对关键调用作了注释。
Asp.net中的调用

[html]  view plain  copy
  1. public partial class _default : System.Web.UI.Page  
  2.    {  
  3.        protected void Page_Load(object sender, EventArgs e)  
  4.        {  
  5.            if (!IsPostBack)  
  6.            {  
  7.                byte[] buff = PDFReport.ExportPDF();  
  8.                Response.ContentType = "application/pdf";  
  9.                Response.BinaryWrite(buff);  
  10.            }  
  11.        }  
  12.    }  

WinForm中的调用

[html]  view plain  copy
  1. private void btnExportPdf_Click(object sender, EventArgs e)  
  2.       {  
  3.           try  
  4.           {  
  5.   
  6.               String path = textBoxPath.Text;  
  7.               if (String.IsNullOrWhiteSpace(path))  
  8.               {  
  9.                   MessageBox.Show("请输入路径");  
  10.                   return;  
  11.               }  
  12.   
  13.               if (!Directory.Exists(Path.GetDirectoryName(path)))  
  14.               {  
  15.                   MessageBox.Show("指定的目录不存在");  
  16.                   return;  
  17.               }  
  18.   
  19.               if (".PDF" != Path.GetExtension(path).ToUpper())  
  20.               {  
  21.                   path = path + ".pdf";  
  22.               }  
  23.               PDFReport.ExportPDF(path);  
  24.               MessageBox.Show("导出成功");  
  25.           }  
  26.           catch (Exception ex)  
  27.           {  
  28.               MessageBox.Show(ex.Message);  
  29.           }  
  30.       }  

源码下载http://download.csdn.NET/detail/xxdddail/8943371

转载请注明出处http://blog.csdn.net/xxdddail/article/details/47128319

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值