效果圖:
參考:http://www.cnblogs.com/CareySon/archive/2011/11/09/2243496.html
http://www.cnblogs.com/julyluo/p/3839788.html
itextsharp版本:4.1.6.0
代碼:
/// <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; } }
其他注意點:
1、當字體不支持中文、日文、繁體中文
public string[] ChineseFont = new string[] { "Traditional Chinese [zh-tw]", "Japanese [ja]" }; BaseFont customfont = BaseFont.CreateFont(fontpath + "\\Lato-Regular.ttf", BaseFont.CP1252, BaseFont.EMBEDDED); if (ChineseFont.Contains(data.Language)) { customfont = BaseFont.CreateFont(fontpath + "\\msyh.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); }
要寫BaseFont.IDENTITY_H
2、表格的邊框
設置 table.DefaultCell.Border = 0;是不能約束單元格的邊框的,必須每個單元格單獨設置邊框pnCell.Border=0或設置其他寬度及四面是否顯示。
3、表格位置
一個表格默認是在頁面中居中對齊,要設置 左對齊: pnTable.HorizontalAlignment = Element.ALIGN_LEFT;
4、表格中嵌套表格
嵌套的表格不會占滿此行,設置了此表格左對齊,右邊留白很多。要完全設置表格的寬度,並且鎖定才行。
pnTable.TotalWidth = 404 * 0.667f;
pnTable.LockedWidth = true;
5、鏈接。
鏈接要用塊來實現。
var linkCell = new PdfPCell(); linkCell.BorderWidthTop = 0; linkCell.Padding = 5f; linkCell.PaddingLeft = 10f; linkCell.PaddingBottom = 20f; var chunk = new Chunk("More Information", link14); chunk.SetAnchor("http://accsmartfind.lenovo.com/products/" + model.PN); linkCell.AddElement(chunk); table.AddCell(linkCell);
6、樣式。
樣式不行表格來湊,如果樣式還不出來,再加一個表格。
代碼:https://pan.baidu.com/s/1bwjMZcfCwndFeSfmG9zd6w ,里面的對象數據要自己添加些調試。vs2013.