C#使用itextsharp生成PDF文件含页脚页眉

一、引用itextsharp库文件

下载链接为:https://download.csdn.net/download/xiaochenxihua/11014068

二、编写生成PDF的基础页面框架生成脚本

/***
*	Title:"智慧工厂" 项目
*		主题:PDF基础设置
*	Description:
*		功能:XXX
*	Date:2018
*	Version:1.2版本
*	Author:Coffee
*	Modify Recoder:
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace ITextSharpTest
{
    public class PDFBase : PdfPageEventHelper
    {
        #region 属性
        private String _fontFilePathForHeaderFooter = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "SIMHEI.TTF");
        /// 
        /// 页眉/页脚所用的字体
        /// 
        public String FontFilePathForHeaderFooter
        {
            get
            {
                return _fontFilePathForHeaderFooter;
            }

            set
            {
                _fontFilePathForHeaderFooter = value;
            }
        }

        private String _fontFilePathForBody = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "SIMSUN.TTC,1");

        /// 
        /// 正文内容所用的字体
        /// 
        public String FontFilePathForBody
        {
            get { return _fontFilePathForBody; }
            set { _fontFilePathForBody = value; }
        }


        private PdfPTable _header;
        /// 
        /// 页眉
        /// 
        public PdfPTable Header
        {
            get { return _header; }
            private set { _header = value; }
        }

        private PdfPTable _footer;
        /// 
        /// 页脚
        /// 
        public PdfPTable Footer
        {
            get { return _footer; }
            private set { _footer = value; }
        }


        private BaseFont _baseFontForHeaderFooter;

        /// 
        /// 页眉页脚所用的字体
        /// 
        public BaseFont BaseFontForHeaderFooter
        {
            get { return _baseFontForHeaderFooter; }
            set { _baseFontForHeaderFooter = value; }
        }

        private BaseFont _baseFontForBody;

        /// 
        /// 正文所用的字体
        /// 
        public BaseFont BaseFontForBody
        {
            get { return _baseFontForBody; }
            set { _baseFontForBody = value; }
        }

        private Document _document;

        /// 
        /// PDF的Document
        /// 
        public Document Document
        {
            get { return _document; }
            private set { _document = value; }
        }

        #endregion


        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            try
            {
                BaseFontForHeaderFooter = BaseFont.CreateFont(FontFilePathForHeaderFooter, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                BaseFontForBody = BaseFont.CreateFont(FontFilePathForBody, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Document = document;
            }
            catch (DocumentException de)
            {
                throw de;
            }
            catch (System.IO.IOException ioe)
            {
                throw ioe;
            }
        }

        #region 生成页头
        /// 
        /// 生成页眉
        /// 
        /// 
        /// 
        public virtual PdfPTable GenerateHeader(iTextSharp.text.pdf.PdfWriter writer)
        {
            return null;
        }
        #endregion

        #region 生成页脚
        /// 
        /// 生成页脚
        /// 
        /// 
        /// 
        public virtual PdfPTable GenerateFooter(iTextSharp.text.pdf.PdfWriter writer)
        {
            return null;
        }
        #endregion

        public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        {
            base.OnEndPage(writer, document);

            //输出页眉
            Header = GenerateHeader(writer);
            Header.TotalWidth = document.PageSize.Width - 20f;
            ///调用PdfTable的WriteSelectedRows方法。该方法以第一个参数作为开始行写入。
            ///第二个参数-1表示没有结束行,并且包含所写的所有行。
            ///第三个参数和第四个参数是开始写入的坐标x和y.
            Header.WriteSelectedRows(0, -1, 10, document.PageSize.Height - 20, writer.DirectContent);

            //输出页脚
            Footer = GenerateFooter(writer);
            Footer.TotalWidth = document.PageSize.Width - 20f;
            Footer.WriteSelectedRows(0, -1, 10, document.PageSize.GetBottom(50), writer.DirectContent);
        }
    }
}

三、测试生成PDF文件内容脚本

/***
*	Title:"智慧工厂" 项目
*		主题:实现PDF文件的设置_关于交接班信息
*	Description:
*		功能:XXX
*	Date:2019
*	Version:1.2版本
*	Author:Coffee
*	Modify Recoder:
*/

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;
using ITextSharpTest;
using kernal;
using Global;

namespace Control
{
	public class Export_ChangeShifts_PDF : PDFBase
    {
        private static Export_ChangeShifts_PDF _Instance;//本类实例


        /// 
        /// 本类实例
        /// 
        /// 
        public static Export_ChangeShifts_PDF GetInstance()
        {
            if (_Instance==null)
            {
                _Instance = new Export_ChangeShifts_PDF();
            }
            return _Instance;
        }

        #region 属性

        private int _pageRowCount = 26;                                         //每页展示的数据行数
        private int _pageColCount = 4;                                          //每页展示的列数

        /// 
        /// 每页的数据行数
        /// 
        public int PageRowCount
        {
            get { return _pageRowCount; }
            set { _pageRowCount = value; }
        }

        /// 
        /// 每页展示的列数
        /// 
        public int PageColCount
        {
            get
            {
                return _pageColCount;
            }

            set
            {
                _pageColCount = value;
            }
        }

        #endregion

        #region   需要导出为PDF的数据内容
        /// 
        /// 导出为PDF文件的数据
        /// 
        private DataTable _dtExportPDFDatas = null;

        /// 
        /// 需要导出为PDF文件的数据集合
        /// 
        /// 
        private DataTable ExportPDFDatas()
        {
            DataTable dtAllInfoData = new DataTable();
            dtAllInfoData.Columns.Add("Number");                                //数据序号
            dtAllInfoData.Columns.Add("OperaterName");                          //操作者
            dtAllInfoData.Columns.Add("HandoverTime");                          //交接班时间
            dtAllInfoData.Columns.Add("HandoverContents");                      //交接班内容

            DataRow row = null;
            int TotalNumbers=0;                                                 //当前导出系统交接班信息的总数
            List _View_System_OperationInfo_Datas = new List();//当前需要导出的系统交接班信息集合
          
            TotalNumbers = Ctrl_CommonView_System_OperationInfoOperation.GetInstance().QueryView_System_OperationInfoTotalNumbers();//系统操作总数
            _View_System_OperationInfo_Datas = Ctrl_CommonView_System_OperationInfoOperation.GetInstance().QueryAllView_System_OperationInfoOfIndex(0, TotalNumbers);
            

            for (int i = 0; i < TotalNumbers; i++)
            {
                row = dtAllInfoData.NewRow();
                row["Number"] = i+1;
                row["OperaterName"] = _View_System_OperationInfo_Datas[i].OperaterName;
                row["HandoverTime"] = _View_System_OperationInfo_Datas[i].HandoverTime;
                row["HandoverContents"] = _View_System_OperationInfo_Datas[i].HandoverContents;

                dtAllInfoData.Rows.Add(row);
            }
            return dtAllInfoData;
        }

        #endregion

        #region    生成页眉

        /// 
        /// 生成页眉
        /// 
        /// 文件流
        /// 
        public override PdfPTable GenerateHeader(iTextSharp.text.pdf.PdfWriter writer)
        {
            BaseFont baseFont = BaseFontForHeaderFooter;
            iTextSharp.text.Font font_logo = new iTextSharp.text.Font(baseFont, 30, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font font_header1 = new iTextSharp.text.Font(baseFont, 18, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font font_header2 = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font font_headerContent = new iTextSharp.text.Font(baseFont, 8, iTextSharp.text.Font.NORMAL);


            float[] widths = new float[] { 200,280,80,70, 50, 40,15,10,15 };

            PdfPTable header = new PdfPTable(widths);
            PdfPCell cell = new PdfPCell();


            cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_LEFT);
            cell.Phrase = new Paragraph("测试XXX科技有限公司"+"\n"+"XXX型号设备", font_header2);
            header.AddCell(cell);

            cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_CENTER);
            cell.Phrase = new Paragraph("交接班信息记录", font_header1);
            header.AddCell(cell);


            cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_RIGHT);
            cell.Phrase = new Paragraph("导出日期:", font_header2);
            header.AddCell(cell);

            cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_LEFT);
            cell.Phrase = new Paragraph(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), font_headerContent);
            header.AddCell(cell);

            cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_RIGHT);
            cell.Phrase = new Paragraph("导出人员:", font_header2);
            header.AddCell(cell);

            cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_CENTER);
            cell.Phrase = new Paragraph(GlobalParaMgr.userName, font_headerContent);
            header.AddCell(cell);

            cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_RIGHT);
            cell.Phrase = new Paragraph("第", font_header2);
            header.AddCell(cell);

            cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_CENTER);
            cell.Phrase = new Paragraph(writer.PageNumber.ToString(), font_headerContent);
            header.AddCell(cell);

            cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_RIGHT);
            cell.Phrase = new Paragraph("页", font_header2);
            header.AddCell(cell);
            return header;
        }

        #region   生成只有底边的Cell
        /// 
        /// 生成只有底边的cell
        /// 
        /// 
        /// 水平对齐方式
        /// 
        private PdfPCell GenerateOnlyBottomBorderCell(int bottomBorder,int horizontalAlignment)
        {
            PdfPCell cell = GenerateOnlyBottomBorderCell(bottomBorder, horizontalAlignment, iTextSharp.text.Element.ALIGN_BOTTOM);
            cell.PaddingBottom = 5;
            return cell;
        }

        /// 
        /// 生成只有底边的cell
        /// 
        /// 
        /// 水平对齐方式
        /// 垂直对齐方式
        /// 
        private PdfPCell GenerateOnlyBottomBorderCell(int bottomBorder, int horizontalAlignment, int verticalAlignment)
        {
            PdfPCell cell = GenerateOnlyBottomBorderCell(bottomBorder);
            cell.HorizontalAlignment = horizontalAlignment;
            cell.VerticalAlignment = verticalAlignment; ;
            return cell;
        }

        /// 
        /// 生成只有底边的cell
        /// 
        /// 
        /// 
        private PdfPCell GenerateOnlyBottomBorderCell(int bottomBorder)
        {
            PdfPCell cell = new PdfPCell();
            cell.BorderWidthBottom = 2;
            cell.BorderWidthLeft = 0;
            cell.BorderWidthTop = 0;
            cell.BorderWidthRight = 0;
            return cell;
        }
        #endregion

        #endregion

        #region   生成页脚
        public override PdfPTable GenerateFooter(iTextSharp.text.pdf.PdfWriter writer)
        {
            BaseFont baseFont = BaseFontForHeaderFooter;
            iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL);

            PdfPTable footer = new PdfPTable(3);
            AddFooterCell(footer, "审阅:", font);
            AddFooterCell(footer, "审批:", font);
            AddFooterCell(footer, "日期:", font);
            return footer;
        }

        private void AddFooterCell(PdfPTable foot, String text, iTextSharp.text.Font font)
        {
            PdfPCell cell = new PdfPCell();
            cell.BorderWidthTop = 2;
            cell.BorderWidthRight = 0;
            cell.BorderWidthBottom = 0;
            cell.BorderWidthLeft = 0;
            cell.Phrase = new Phrase(text, font);
            cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
            foot.AddCell(cell);
        }
        #endregion

        #region   导出PDF

        /// 
        /// 导出PDF
        /// 
        /// 导出路径
        public void ExportPDF(String path)
        {
            Export_ChangeShifts_PDF pdfReport = new Export_ChangeShifts_PDF();
            Document document = new Document(PageSize.A4.Rotate(), -90, -90, 60, 10);//此处设置的偏移量是为了加大页面的可用范围,可以使用默认.
            PdfWriter pdfWriter = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create, FileAccess.Write));
            pdfWriter.PageEvent = pdfReport;//此处一定要赋值,才能触发页眉和页脚的处理
            document.Open();
            pdfReport.AddBody(document);
            document.Close();
        }

        /// 
        /// 导出PDF
        /// 
        /// 导出路径
        public  byte[] ExportPDF()
        {
            Export_ChangeShifts_PDF pdfReport = new Export_ChangeShifts_PDF();
            Document document = new Document(PageSize.A4.Rotate(), -90, -90, 60, 10);//此处设置的偏移量是为了加大页面的可用范围,可以使用默认.
            MemoryStream ms = new MemoryStream();
            PdfWriter pdfWriter = PdfWriter.GetInstance(document, ms);
            pdfWriter.PageEvent = pdfReport;//此处一定要赋值,才能触发页眉和页脚的处理
            document.Open();
            pdfReport.AddBody(document);
            document.Close();
            byte[] buff = ms.ToArray();
            return buff;
        }
        #endregion

        #region   添加内容

        /// 
        /// 循环添加所有数据到每一页中
        /// 
        /// 
        private void AddBody(Document document)
        {
            _dtExportPDFDatas = ExportPDFDatas();
            int count = (_dtExportPDFDatas.Rows.Count + (PageRowCount - 1)) / PageRowCount;
            for (int i = 0; i < count; i++)
            {
                AddBodySinglePage(i + 1);
                document.NewPage();
            }
        }

        /// 
        /// 添加每页的数据信息
        /// 
        /// 页码
        private void AddBodySinglePage(int pageNumber)
        {
            BaseFont baseFont = BaseFontForBody;
            iTextSharp.text.Font font_columnHeader = new iTextSharp.text.Font(baseFont, 11f, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font font_contentNormal = new iTextSharp.text.Font(baseFont, 9.5f, iTextSharp.text.Font.NORMAL);
            iTextSharp.text.Font font_contentSmall = new iTextSharp.text.Font(baseFont, 7f, iTextSharp.text.Font.NORMAL);

            //此处是为了当列数很多时,便于循环生成所要的表格列宽比例
            int columnCount = PageColCount;
            float[] widths = new float[columnCount];
            for (int i = 0; i < columnCount; i++)
            {
               
                if (i == 3)
                {
                    widths[i] = 3F;
                }
                else
                {
                    widths[i] = 0.7F;
                }
               
            }


            PdfPTable bodyTable = new PdfPTable(widths);
            bodyTable.SpacingBefore = 10;//与头部的距离

            //添加表头
            AddBodyHeader(bodyTable, font_columnHeader);

            //添加对应每页的数据
            AddSinglePageData(bodyTable, font_contentNormal, font_contentSmall, pageNumber);

            Document.Add(bodyTable);
        }

       

        #region   添加内容标题

        /// 
        /// 添加Body的列标题
        /// 
        /// 
        /// 
        private void AddBodyHeader(PdfPTable bodyTable, iTextSharp.text.Font font_columnHeader)
        {
            //采用Rowspan和Colspan来控制单元格的合并与拆分,类似于HTML的Table. 
            AddColumnHeaderCell(bodyTable, "序号", font_columnHeader, 1, 2);
            AddColumnHeaderCell(bodyTable, "操作者", font_columnHeader, 1, 2);
            AddColumnHeaderCell(bodyTable, "交接班时间", font_columnHeader, 1, 2);
            AddColumnHeaderCell(bodyTable, "交接班内容", font_columnHeader, 1, 2);
        }
        #endregion

        #region 添加报表正文

        /// 
        /// 添加对应每页的数据
        /// 
        /// 表格
        /// 普通字体
        /// 小字体,当内容显示不下,需要使用小字体来显示时,可以使用.
        /// 页码
        private void AddSinglePageData(PdfPTable bodyTable,
                                   iTextSharp.text.Font fontNormal,
                                   iTextSharp.text.Font fontSmall, int pageNumber)
        {
            int count = _dtExportPDFDatas.Rows.Count;//数据总量
            int startIndex = (pageNumber - 1) * PageRowCount;//开始索引
            int endIndex = pageNumber * PageRowCount;//结束索引
            int startIndex1 = count - startIndex;//下一页的开始索引
            int surplusNumbers = count - endIndex;//剩下的数量

            //Log.Write("pageNumber="+ pageNumber + "  count=" + count+ " startIndex=" + startIndex+ "  endIndex=" + endIndex+ "  startIndex1=" + startIndex1+ "  surplusNumbers=" + surplusNumbers);

            if (surplusNumbers > PageRowCount)
            {
                for (int i = startIndex; i < endIndex; i++)
                {
                    AddBodyContent(bodyTable, fontNormal, fontSmall, i);
                }

            }
            else
            {
                if (surplusNumbers > 0)
                {
                    for (int i = startIndex; i < endIndex; i++)
                    {
                        AddBodyContent(bodyTable, fontNormal, fontSmall, i);
                    }
                }
                else
                {
                    for (int i = startIndex; i < startIndex + startIndex1; i++)
                    {
                        AddBodyContent(bodyTable, fontNormal, fontSmall, i);
                    }
                }

            }
        }

        /// 
        /// 添加报表正文
        /// 
        /// 
        /// 普通字体
        /// 小字体,当内容显示不下,需要使用小字体来显示时,可以使用.
        /// 索引便于从数据库中按页拉取数据时使用.
        public void AddBodyContent(PdfPTable bodyTable,
                                   iTextSharp.text.Font fontNormal,
                                   iTextSharp.text.Font fontSmall,
                                   int index)
        {

            DataRow row = _dtExportPDFDatas.Rows[index];
            AddBodyContentCell(bodyTable, String.Format("{0}", row["Number"]), fontNormal);                 //数据序号
            AddBodyContentCell(bodyTable, String.Format("{0}", row["OperaterName"]), fontNormal);           //操作者
            AddBodyContentCell(bodyTable, String.Format("{0}", row["HandoverTime"]), fontNormal);           //交接班时间
            AddBodyContentCell(bodyTable, String.Format("{0}", row["HandoverContents"]), fontNormal);       //交接班内容

        }

        private static void AddBodyContentCell(PdfPTable bodyTable, String text, iTextSharp.text.Font font, int rowspan = 2, bool needRightBorder = true)
        {
            PdfPCell cell = new PdfPCell();
            float defaultBorder = 0.5f;
            cell.BorderWidthLeft = defaultBorder;
            cell.BorderWidthTop = 0;
            cell.BorderWidthRight = needRightBorder ? defaultBorder : 0;
            cell.BorderWidthBottom = defaultBorder;
            cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
            cell.VerticalAlignment = iTextSharp.text.Element.ALIGN_BASELINE;
            cell.Rowspan = rowspan;
            cell.PaddingBottom = 4;
            cell.Phrase = new Phrase(text, font);
            cell.FixedHeight = 18f;
            bodyTable.AddCell(cell);
        }
        #endregion

        #region 添加列标题单元格

        /// 
        /// 添加列标题单元格
        /// 
        /// 表格行的单元格列表
        /// 标题
        /// 字段
        /// 列空间
        /// 行空间
        /// 是否需要左边框
        /// 是否需要右边框
        public void AddColumnHeaderCell(PdfPTable table,
                                                String header,
                                                iTextSharp.text.Font font,
                                                int colspan,
                                                int rowspan,
                                                bool needLeftBorder = true,
                                                bool needRightBorder = true)
        {
            PdfPCell cell = GenerateColumnHeaderCell(header, font, needLeftBorder, needRightBorder);
            if (colspan >= 1)
            {
                cell.Colspan = colspan;
            }

            if (rowspan >= 1)
            {
                cell.Rowspan = rowspan;
            }

            table.AddCell(cell);
        }

        /// 
        /// 添加列标题单元格
        /// 
        /// 表格
        /// 标题
        /// 字段
        /// 是否需要左边框
        /// 是否需要右边框
        public void AddColumnHeaderCell(PdfPTable table,
                                                String header,
                                                iTextSharp.text.Font font,
                                                bool needLeftBorder = true,
                                                bool needRightBorder = true)
        {
            PdfPCell cell = GenerateColumnHeaderCell(header, font, needLeftBorder, needRightBorder);
            table.AddCell(cell);
        }
        #endregion

        #region 生成列标题单元格
        /// 
        /// 生成列标题单元格
        /// 
        /// 标题
        /// 字段
        /// 是否需要左边框
        /// 是否需要右边框
        /// 
        private PdfPCell GenerateColumnHeaderCell(String header,
                                                        iTextSharp.text.Font font,
                                                        bool needLeftBorder = true,
                                                        bool needRightBorder = true)
        {
            PdfPCell cell = new PdfPCell();
            float border = 0.5f;
            cell.BorderWidthBottom = border;
            if (needLeftBorder)
            {
                cell.BorderWidthLeft = border;
            }
            else
            {
                cell.BorderWidthLeft = 0;
            }

            cell.BorderWidthTop = border;
            if (needRightBorder)
            {
                cell.BorderWidthRight = border;
            }
            else
            {
                cell.BorderWidthRight = 0;
            }

            cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
            cell.VerticalAlignment = iTextSharp.text.Element.ALIGN_BASELINE;
            cell.PaddingBottom = 4;
            cell.Phrase = new Phrase(header, font);
            return cell;
        }
        #endregion

        #endregion

    }//Class_end
}

 调用导出PDF示例:

  //导出对应的所有交接班信息PDF文件
  Export_ChangeShifts_PDF.GetInstance().ExportPDF("C:\");

生成的PDF文件效果如下所示:

C#使用itextsharp生成PDF文件含页脚页眉_第1张图片

 

参考内容:https://download.csdn.net/download/xxdddail/8943371

 

你可能感兴趣的:(C#基,itextsharp,PDF)