码迷,mamicode.com
首页 > 其他好文 > 详细

使用iTextSharp导出PDF

时间:2017-06-06 14:23:45      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:export   bfc   pre   alignment   addheader   name   bin   window   tpc   

 /// <summary>
        /// 导出至PDF
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="fileName">文件名</param>
        /// <param name="dicTableHeader">字段表头名对照</param>
        public static void Export(DataTable dt, string fileName, Dictionary<string, string> dicTableHeader)
        {
            Document document = new Document();
            using (MemoryStream pdfStream = new MemoryStream())
            {
                PdfWriter pdfWriter = PdfWriter.GetInstance(document, pdfStream);
                document.Open();
                BaseFont bfChinese = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, new BaseColor(0, 0, 0));
                Font fontHeader = new Font(bfChinese, 12, Font.BOLD, new BaseColor(0, 0, 0));

                int columCount = dicTableHeader.Count;
                PdfPTable table = new PdfPTable(columCount);

                foreach (var item in dicTableHeader)
                {
                    PdfPCell cell = new PdfPCell(new Phrase(item.Value, fontHeader));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(cell);
                }

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    foreach (var item in dicTableHeader)
                    {
                        table.AddCell(new Phrase(dt.Rows[i][item.Key].ToString(), fontChinese));
                    }
                }
                document.Add(table);

                document.Close();
                pdfWriter.Close();

                HttpContext curContext = HttpContext.Current;
                curContext.Response.Clear();
                curContext.Response.ClearContent();
                curContext.Response.ClearHeaders();
                curContext.Response.ContentType = "application/octet-stream";
                curContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8) + ".pdf");
                curContext.Response.BinaryWrite(pdfStream.ToArray());
                curContext.Response.Flush();
                curContext.Response.End();
            }

        }

 

使用iTextSharp导出PDF

标签:export   bfc   pre   alignment   addheader   name   bin   window   tpc   

原文地址:http://www.cnblogs.com/tangchun/p/6950919.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!