zoukankan      html  css  js  c++  java
  • 基于iTextSharp的PDF操作(PDF打印,PDF下载)

    基于iTextSharpPDF操作(PDF打印,PDF下载)

    准备

    1. iTextSharp的简介

    iTextSharp是一个移植于java平台的iText项目,被封装成c#的组件来用于C#生成PDF文档,目前,也有不少操作PDF的类库,(国产的有福盺的,免费试用,用于商业用途收费)但是功能普遍没有iText强大,而且使用没有iText广泛。还有他就是开源的。目前比较新的是5.5版本的。

    2. 使用工具

    硬件:

    PC机:一台

    软件:

    Windows操作系统

    Isual studio 2013  (可以是任意版本)

    .Net frameWork 4.5  (可以是任意版本)

    iTextSharp 5.5  可以到官网下载(iTextSharp)http://sourceforge.net/projects/itextsharp/

     

    下载后,解压得到iTextSharp.dll文件

    基本知识

    1. 主要对象

    1).Document 对象:

    Document 对象主要用于操作页面的大小,就是页面的尺寸。页面的尺寸一般有以下几种:

    A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA 和 FLSE,例如,需要创建一个A4纸张大小的PDF文档:

    Document document = new Document(PageSize.A4);

    这个文档漠然是纵向的,如果满足不了你横向文档的需要,可以加上rotate属性。

    有的时候,我们需要生成特定颜色的,特定大小的PDF文档,可以使用下面的方法

    Rectangle pageSize = new Rectangle(120, 520);     //120*520规格

    pageSize.BackgroundColor = new Color(0xFF, 0xFF, 0xDE);   //背景色

    Document document = new Document(pageSize);          //新建Documen对象

     

    页边距:

    Document document = new Document(PageSize.A5, 36, 72, 108, 180);//默认单位为磅。

     

    2).PdfWriter对象:

    创建了Documen对象后,我们就要对PDF文档进行操作(合并,删除,更改,添加内容等)。这个时候必须创建PdfWriter对象实例。PdfWriter类对对象继承自iTextSharp.text.DocWriter抽象类。如果需要创建Ext文件,则需要iTextSharp.text.TeX.TeXWriter这个类。

     //注意FileMode-Create表示如果目标文件不存在,则创建,如果已存在,则覆盖。

                PdfWriter writer = PdfWriter.GetInstance(document,

                    new FileStream(strFileName, FileMode.Create));

    如代码所示,创建成功了一个PDF的PdfWriter实例。 FileMode.Create:表示如果目标文件不存在,则创建,如果已存在,则覆盖。FileMode.New 表示新建,FileMode.Append表示追加,如果你是操作PDF模版,你可以使用Append。

    PdfPTable对象,

    我们需要用到的属性:

         /// <param name="sdr_Context">List</param>

            /// <param name="title">标题名称</param>

            /// <param name="fontpath_Title">标题字体路径</param>

            /// <param name="fontsize_Title">标题字体大小</param>

            /// <param name="fontStyle_Title">标题样式</param>

            /// <param name="fontColor_Title">标题颜色</param>

            /// <param name="fontpath_Col">列头字体路径</param>

            /// <param name="fontsize_Col">列头字体大小</param>

            /// <param name="fontStyle_Col">列头字体样式</param>

            /// <param name="fontColor_Col">列头字体颜色</param>

            /// <param name="col_Width">表格总宽度</param>

            /// <param name="arr_Width">每列的宽度</param>

            /// <param name="pdf_Filename">在服务器端保存PDF时的文件名</param>

            /// <param name="FontPath">正文字体路径</param>

            /// <param name="FontSize">正文字体大小</param>

            ///  <param name="fontStyle_Context">正文字体样式</param>

            ///  <param name="fontColor_Context">正文字体颜色</param>

     

    方法(长长的,可以封装成对象):

         public void exp_Pdf( List<Customer> sdr_Context, string title, string fontpath_Title, float fontsize_Title, int fontStyle_Title, 

                BaseColor fontColor_Title, string fontpath_Col, float fontsize_Col, int fontStyle_Col, BaseColor fontColor_Col, float col_Width, 

                int[] arr_Width, string pdf_Filename, string FontPath, float FontSize, int fontStyle_Context, BaseColor fontColor_Context)

    2.基本属性设置

    字体颜色等

      //在服务器端保存PDF时的文件名

        string strFileName = pdf_Filename + ".pdf";

                //初始化一个目标文档类 

                Document document = new Document(PageSize.A4.Rotate(), 0, 0, 10, 10);

                //调用PDF的写入方法流

                //注意FileMode-Create表示如果目标文件不存在,则创建,如果已存在,则覆盖。

                PdfWriter writer = PdfWriter.GetInstance(document,

                    new FileStream(strFileName, FileMode.Create));

     

      //标题字体

                    BaseFont basefont_Title = BaseFont.CreateFont(

                      fontpath_Title,

                      BaseFont.IDENTITY_H,

                      BaseFont.NOT_EMBEDDED);

                    Font font_Title = new Font(basefont_Title, fontsize_Title, fontStyle_Title, fontColor_Title);

     

       //表格列字体

                    BaseFont basefont_Col = BaseFont.CreateFont(

                      fontpath_Col,

                      BaseFont.IDENTITY_H,

                      BaseFont.NOT_EMBEDDED);

                    Font font_Col = new Font(basefont_Col, fontsize_Col, fontStyle_Col, fontColor_Col);

     

     

     //正文字体

                    BaseFont basefont_Context = BaseFont.CreateFont(

                      FontPath,

                      BaseFont.IDENTITY_H,

                      BaseFont.NOT_EMBEDDED);

                    Font font_Context = new Font(basefont_Context, FontSize, fontStyle_Context, fontColor_Context);

     

    3.打开文档

     //打开目标文档对象document.PageNumber

                    document.Open();

     

     //添加标题

                    Paragraph p_Title = new Paragraph(title, font_Title);

                    p_Title.Alignment = Element.ALIGN_CENTER;

                    p_Title.IndentationLeft = 200;

                    p_Title.PaddingTop = 300;

                    p_Title.ExtraParagraphSpace = 300;

                    p_Title.SpacingAfter = 100;

                    document.Add(p_Title);

    4.生成表格

      //根据数据表内容创建一个PDF格式的表

                    PdfPTable table = new PdfPTable(5);         //1     

                    table.TotalWidth = col_Width;//表格总宽度

                    table.LockedWidth = true;//锁定宽度

                    table.SetWidths(arr_Width);//设置每列宽度

                    //构建列头

                    //设置列头背景色

                    table.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY;

                    //设置列头文字水平、垂直居中

                    table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;

                    table.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;

                    // 告诉程序这行是表头,这样页数大于1时程序会自动为你加上表头。

                    table.HeaderRows = 1;

             

                            table.AddCell(new Phrase("222222", font_Col));

                            table.AddCell(new Phrase("222222", font_Col));

                            table.AddCell(new Phrase("222222", font_Col));

                            table.AddCell(new Phrase("222222", font_Col));

                            table.AddCell(new Phrase("222222", font_Col));

                        // 添加数据

                        //设置标题靠左居中

                        table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;

                        // 设置表体背景色

                        table.DefaultCell.BackgroundColor = BaseColor.WHITE;

                        for (int i = 0; i < sdr_Context.Count(); i++)

                        {

                            table.AddCell(new Phrase(sdr_Context[i].Id.ToString(), font_Context));

                            table.AddCell(new Phrase(sdr_Context[i].Name, font_Context));

                            table.AddCell(new Phrase(sdr_Context[i].Place, font_Context));

                            table.AddCell(new Phrase(sdr_Context[i].Address, font_Context));

                            table.AddCell(new Phrase(sdr_Context[i].Address, font_Context));

                        }

     

     

    5.把表格加进文档

     

    document.Add(table);

    6.关闭文档

     //关闭目标文件

                    document.Close();

                    //关闭写入流

                    writer.Close();

    7.直接打印预览

        MemoryStream PDFData = new MemoryStream(data);

                System.Web.HttpContext.Current.Response.Clear();

                System.Web.HttpContext.Current.Response.ClearContent();

                System.Web.HttpContext.Current.Response.ClearHeaders();

                System.Web.HttpContext.Current.Response.ContentType = "application/pdf";

                System.Web.HttpContext.Current.Response.Charset = string.Empty;

                System.Web.HttpContext.Current.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);

                System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition",

                "inline; filename=" + strFileName.Replace(" ", "").Replace(":", "-") + ".pdf");

                System.Web.HttpContext.Current.Response.OutputStream.Write(PDFData.ToArray(), 0, PDFData.ToArray().Length);

                System.Web.HttpContext.Current.Response.OutputStream.Flush();

                System.Web.HttpContext.Current.Response.OutputStream.Close();

    8.如果需要下载

                try

                {

                    //这里是你文件在项目中的位置,根目录下就这么写 

                    String FullFileName = strFileName;

                    FileInfo DownloadFile = new FileInfo(FullFileName);

                    //System.Web.HttpContext.Current.Response.Clear();

                    //System.Web.HttpContext.Current.Response.ClearHeaders();

                    //System.Web.HttpContext.Current.Response.Buffer = true;

                    //System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";

                    //System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename="

                    //    + System.Web.HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));

                    //System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());

                    //System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName);

                }

                catch (Exception)

                {

                    throw;

                }

                finally

                {

                    System.Web.HttpContext.Current.Response.Flush();

                    System.Web.HttpContext.Current.Response.End();

                }

    9.实现第X页 共X

    旧的的iTextSharp版本和新的版本不一样,主要是通过页眉和页脚实现。

      public class HeaderAndFooterEvent : PdfPageEventHelper, IPdfPageEvent

        {

            public static PdfTemplate tpl;

            public static bool PAGE_NUMBER = false;

            iTextSharp.text.Font font = BaseFontAndSize("黑体", 10, Font.NORMAL, BaseColor.BLACK);

            //关闭PDF文档时

            public override void OnCloseDocument(PdfWriter writer, Document document)

            {

                BaseFont bf = BaseFont.CreateFont(@"c:\windows\FONTS\simsun.ttc,1", BaseFont.IDENTITY_H, false); //调用的字体

                tpl.BeginText();

                tpl.SetFontAndSize(bf, 10);//生成的模版的字体、颜色

                tpl.ShowText((writer.PageNumber - 1).ToString());//模版显示的内容

                tpl.EndText();

                tpl.ClosePath();

                

            }

            //重写 关闭一个页面时

            public override void OnEndPage(PdfWriter writer, Document document)

            {

                if (PAGE_NUMBER)

                {          

                  // Phrase header = new Phrase("PDF测试生成页眉分析报告", font);

                   Phrase header = new Phrase("第" + (writer.PageNumber) + "页/共  页", font);

                   PdfContentByte cb = writer.DirectContent;   //模版 显示总共页数

                   cb.AddTemplate(tpl, document.Right - 140 + document.LeftMargin - 70, document.Top + 40);//调节模版显示的位置

                    //页眉显示的位置

                    ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, header,

                           document.Right - 140 + document.LeftMargin-80, document.Top +40, 0);           

                }

            }

            //重写 打开一个新页面时

            public override void OnStartPage(PdfWriter writer, Document document)

            {

                if (PAGE_NUMBER)

                {

                    writer.PageCount = writer.PageNumber;

                }

            }

          

            //定义字体 颜色

            public static Font BaseFontAndSize(string font_name, int size, int style, BaseColor baseColor)

            {

                BaseFont baseFont;

                

                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;

            }

            //定义输出文本

            public static Paragraph InsertTitleContent(string text)

            {

                iTextSharp.text.Font font = BaseFontAndSize("华文中宋", 16, Font.BOLD,BaseColor.BLACK);

                

                //BaseFont bfSun = BaseFont.CreateFont(@"c:windowsfontsSTZHONGS.TTF", BaseFont.IDENTITY_H, false); //调用的字体

                //Font font = new Font(bfSun, 15);

                Paragraph paragraph = new Paragraph(text, font);//新建一行

                paragraph.Alignment = Element.ALIGN_CENTER;//居中

                paragraph.SpacingBefore = 5;

                paragraph.SpacingAfter = 5;

                paragraph.SetLeading(1, 2);//每行间的间隔

                return paragraph;

            }

        }

     

     

     

    运行结果:

     

     

     

     

     

    注:如需要源代码,请关注百度贴吧,然后发帖支持作者(软件频道)http://tieba.baidu.com/f?kw=%C8%ED%BC%FE%C6%B5%B5%C0&fr=index,最后找作者要代码:QQ:763630473

  • 相关阅读:
    Sign APK without putting keystore info in build.gradle
    Sign APK without putting keystore info in build.gradle
    Sketch教程
    Sketch教程
    简要分析unity3d中剪不断理还乱的yield
    简要分析unity3d中剪不断理还乱的yield
    iOS开发系列--地图与定位总结
    iOS开发系列--地图与定位总结
    Launch Screen在iOS7/8中的实现
    linux 命令随笔 ls cd pwd mkdir rm mv cp cat nl
  • 原文地址:https://www.cnblogs.com/dengjiahai/p/4567348.html
Copyright © 2011-2022 走看看