iTextSharp產生pdf的一個簡單例子

來源:互聯網
上載者:User

標籤: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的一個簡單例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.