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

iTextSharp生成pdf的一个简单例子

时间:2016-12-30 02:33:30      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:min   nim   oid   表格   cli   writer   生成文件   ctc   cat   

效果图:技术分享

代码:

  /// <summary>
        /// Compare页面生成pdf功能。
        /// </summary>
        /// <param name="country">国家</param>
        /// <param name="pns">pn</param>
        /// <param name="language">语言</param>
        /// <returns>响应对象</returns>
        public string ComparePdf(string country, string[] pns, string language)
        {
            var result = "";
            //生成pdf
            Document document = new Document();

            //这样写:是生成一个文件到某目录中
            //var directory = HttpContext.Current.Server.MapPath("~/pdf");
            //string host = HttpContext.Current.Request.Url.Host;
            //int port = HttpContext.Current.Request.Url.Port;
            //if (!Directory.Exists(directory))
            //{
            //    Directory.CreateDirectory(directory);
            //}
            //var fileName = "";
            //foreach (var item in pns)
            //{
            //    fileName += "_" + item + "_";
            //}
            //fileName = "Compare" + fileName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
            //var pdfPath = directory + "\\" + fileName;
            //var fileStream = new FileStream(pdfPath, FileMode.Create);
            //PdfWriter pw = PdfWriter.GetInstance(document, fileStream);

         //这样写:是生成文件到内存中去
            var memoryStream = new MemoryStream();
            PdfWriter pw = PdfWriter.GetInstance(document, memoryStream);//生成到内存中

            //数据
            var list = Compare(country, pns, language);
            document.Open();//打开文件
            //写入数据
            //注册字体
            string fontpath = HttpContext.Current.Server.MapPath("~/App_Data");
            BaseFont customfont = BaseFont.CreateFont(fontpath + "\\Lato-Regular.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
            var baseFont = new Font(customfont, 14 * 0.667f, Font.NORMAL, new Color(68, 68, 68));
            var leftFont = new Font(customfont, 14 * 0.667f, Font.BOLD, new Color(68, 68, 68));
            #region 头部
            PdfPTable tableLogo = new PdfPTable(3);
            tableLogo.DefaultCell.Border = Rectangle.NO_BORDER;
            tableLogo.DefaultCell.MinimumHeight = 40f;
            float[] headWidths = new float[] { 60f, 60f, 150f };
            tableLogo.SetWidths(headWidths);
            //logo
            var logo = iTextSharp.text.Image.GetInstance("http://d1fyvoqprbjuee.cloudfront.net/smartfindimages/logo.png");
            logo.ScaleToFit(130 * 0.667f, 43 * 0.667f);
            var logoCell = new PdfPCell();
            logoCell.PaddingLeft = -1f;
            logoCell.MinimumHeight = 45f;
            logoCell.HorizontalAlignment = Element.ALIGN_LEFT;
            logoCell.Border = 0;
            logoCell.AddElement(logo);
            tableLogo.AddCell(logoCell);

             var headFont = new Font(customfont, 26 * 0.667f, Font.BOLD, new Color(68, 68, 68));
            var sCell = new PdfPCell(new Paragraph("SmartFind", headFont));
            sCell.Border = 0;
            sCell.PaddingLeft = 3f;
            sCell.PaddingBottom = 17f;
            sCell.MinimumHeight = 45f;
            sCell.HorizontalAlignment = Element.ALIGN_LEFT;
            sCell.VerticalAlignment = Element.ALIGN_BOTTOM;
            tableLogo.AddCell(sCell);

            var aCell = new PdfPCell();
            aCell.Border = 0;
            aCell.MinimumHeight = 45f;
            aCell.PaddingBottom = 17f;
            aCell.HorizontalAlignment = Element.ALIGN_LEFT;
            aCell.VerticalAlignment = Element.ALIGN_BOTTOM;
            var accFont = new Font(customfont, 18 * 0.667f, Font.NORMAL, new Color(170, 170, 170));
            var acc = new Paragraph("|  Accessories", accFont);
            aCell.AddElement(acc);
            tableLogo.AddCell(aCell);

            document.Add(tableLogo);
            #endregion

            document.Add(new Paragraph(""));

            #region 中间的表格
            PdfPTable table = new PdfPTable(list.Count + 1);//n列的表格
            table.DefaultCell.Border = 0;
            table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
            table.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;

            //根据图片数量确定列数及列宽
            if (pns.Count() == 1)
            {
                float[] widths = new float[] { 2f, 3f };
                table.SetWidths(widths);
            }
            else if (pns.Count() == 2)
            {
                float[] widths = new float[] { 2f, 3f, 3f };
                table.SetWidths(widths);
            }
            else if (pns.Count() == 3)
            {
                float[] widths = new float[] { 2f, 3f, 3f, 3f };
                table.SetWidths(widths);
            }
            else if (pns.Count() == 4)
            {
                float[] widths = new float[] { 2f, 3f, 3f, 3f, 3f };
                table.SetWidths(widths);
            }
            //左单元格
            var leftCell = new PdfPCell(new Paragraph("Images", leftFont));
            leftCell.MinimumHeight = 40f;
           leftCell.BackgroundColor = new Color(242, 242, 242);
            leftCell.HorizontalAlignment = Element.ALIGN_CENTER;
            leftCell.VerticalAlignment = Element.ALIGN_MIDDLE;
            table.AddCell(leftCell);

            //右单元格
            var rightCell = new PdfPCell();
            rightCell.HorizontalAlignment = Element.ALIGN_CENTER;
            rightCell.VerticalAlignment = Element.ALIGN_MIDDLE;
            rightCell.MinimumHeight = 40f;

            foreach (var item in list)
            {
                var imageCell = new PdfPCell();
                imageCell.Padding = 1f;
                //根据图片数量确定左边距,确保图片在中间显示。这个地方写的不好,暂时这样
                if (list.Count == 2)
                {
                    imageCell.PaddingLeft = 30f;
                }
                if (list.Count == 1)
                {
                    imageCell.PaddingLeft = 80f;
                }
                if (list.Count == 3)
                {
                    imageCell.PaddingLeft = 10f;
                }
                //确保网络图片存在
                if (!string.IsNullOrEmpty(item.Url) && Helper.IsExists(item.Url + "-218.png"))
                {
                    var image = iTextSharp.text.Image.GetInstance(item.Url + "-218.png");
                    if (list.Count == 4)
                    {
                        image.ScaleToFit(80f, 80f);
                    }
                    else
                    {
                        image.ScaleToFit(100f, 100f);
                    }
                    imageCell.AddElement(image);
                }
                table.AddCell(imageCell);
            }

            //Product Title
            leftCell.Phrase = new Paragraph("Product Title", leftFont);
            var titleFont = new Font(customfont, 14 * 0.667f, Font.NORMAL, new Color(255, 105, 0));
            table.AddCell(leftCell);
            foreach (var item in list)
            {
                rightCell.Phrase = new Paragraph(item.Title, titleFont);
                table.AddCell(rightCell);
            }

            //List Price
            leftCell.Phrase = new Paragraph("List Price", leftFont);
            table.AddCell(leftCell);
            foreach (var item in list)
            {
                rightCell.Phrase = new Paragraph(item.Currency + item.Price, baseFont);
                table.AddCell(rightCell);
            }

            //Part Number
            leftCell.Phrase = new Paragraph("Part Number", leftFont);
            table.AddCell(leftCell);
            foreach (var item in list)
            {
                rightCell.Phrase = new Paragraph(item.PN, baseFont);
                table.AddCell(rightCell);
            }

            //facet
            var first = list.FirstOrDefault();
            foreach (var item in first.Facets)
            {
                leftCell.Phrase = new Paragraph(item.Key, leftFont);
                table.AddCell(leftCell);
                rightCell.Phrase = new Paragraph(item.Value, baseFont);
                table.AddCell(rightCell);
                //其余的
                list.Remove(first);
                var other = list;
                foreach (var one in other)
                {
                    rightCell.Phrase = new Paragraph(one.Facets.FirstOrDefault(o => o.Key == item.Key).Value, baseFont);
                    table.AddCell(rightCell);
                }
            }
            document.Add(table);
            #endregion

            //页脚
            PDFFooter footer = new PDFFooter();
            footer.OnEndPage(pw, document);
            document.Close();
            var bytes = memoryStream.ToArray();
            result = Convert.ToBase64String(bytes);

            return result;
        }

/// <summary>
    /// 页脚类
    /// </summary>
    public class PDFFooter : PdfPageEventHelper
    {
        // write on top of document
        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            base.OnOpenDocument(writer, document);
            PdfPTable tabFot = new PdfPTable(new float[] { 1F });
            tabFot.SpacingAfter = 10F;
            PdfPCell cell;
            tabFot.TotalWidth = 300F;
            cell = new PdfPCell(new Phrase("Header"));
            tabFot.AddCell(cell);
            tabFot.WriteSelectedRows(0, -1, 150, document.Top, writer.DirectContent);
        }

        // write on start of each page
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            base.OnStartPage(writer, document);
        }

        // write on end of each page
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);
            PdfPTable tabFot = new PdfPTable(new float[] { 1F });
            tabFot.TotalWidth = 700f;
            tabFot.DefaultCell.Border = 0;
          //  var footFont = FontFactory.GetFont("Lato", 12 * 0.667f, new Color(60, 60, 60));
            string fontpath = HttpContext.Current.Server.MapPath("~/App_Data");
            BaseFont customfont = BaseFont.CreateFont(fontpath + "\\Lato-Regular.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
            var footFont = new Font(customfont, 12 * 0.667f, Font.NORMAL, new Color(170, 170, 170));
          
            PdfPCell cell;
            cell = new PdfPCell(new Phrase("@ 2016 . All Rights Reserved", footFont));
            cell.VerticalAlignment = Element.ALIGN_CENTER;
            cell.Border = 0;
            cell.PaddingLeft = 100f;
            tabFot.AddCell(cell);
            tabFot.WriteSelectedRows(0, -1, 150, document.Bottom, writer.DirectContent);
        }

        //write on close of document
        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);
        }
    } 

  

 /// <summary>
        /// 判断网络文件是否存在
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool IsExists(string url)
        {
            try
            {
                using (new WebClient().OpenRead(url)) { }
                return true;
            }
            catch (WebException)
            {
                return false;
            }
        }

  

iTextSharp生成pdf的一个简单例子

标签:min   nim   oid   表格   cli   writer   生成文件   ctc   cat   

原文地址:http://www.cnblogs.com/heifengwll/p/6235383.html

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