使用iTextSharp导出PDF

Posted York

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用iTextSharp导出PDF相关的知识,希望对你有一定的参考价值。

 /// <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的主要内容,如果未能解决你的问题,请参考以下文章

用Itextsharp 组件导出PDF 的文档的方法

使用iTextSharp获取复选框的导出值

c#如何将数据导出pdf文件,我用的是vs2010,里边没有水晶报表。然后用itextsharp就报字体啥的错误。

iTextSharp - 非常大的表内存泄漏

itextsharp去掉PDF加密

iTextSharp 正在生成损坏的 PDF