private static PdfGrid createHeader(PagesHeaderBuilder header) { var table = new PdfGrid(numColumns: 1) { WidthPercentage = 100, RunDirection = PdfWriter.RUN_DIRECTION_RTL, SpacingAfter = 7 }; var basefont = BaseFont.CreateFont(TestUtils.GetTahomaFontPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var gillsans = new iTextSharp.text.Font(basefont, 30, iTextSharp.text.Font.BOLD, new BaseColor(ColorTranslator.FromHtml("#009cde").ToArgb())); FontSelector selector = new FontSelector(); selector.AddFont(gillsans); var title = selector.Process("PayPing"); var pdfCell = new PdfPCell(title) { RunDirection = PdfWriter.RUN_DIRECTION_RTL, BorderWidthLeft = 0, BorderWidthRight = 0, BorderWidthTop = 0, BorderWidthBottom = 1, PaddingBottom = 10, BorderColorBottom = new BaseColor(System.Drawing.Color.LightGray.ToArgb()), HorizontalAlignment = Element.ALIGN_CENTER }; table.AddCell(pdfCell); return(table); }
private Anchor getAnchor(FontSelector fontSelector, CellAttributes attributes) { var text = getText(attributes); var url = getUrl(attributes); var anchor = new Anchor(fontSelector.Process(text.ToSafeString())) { Reference = url }; return(anchor); }
// --------------------------------------------------------------------------- public void EndElement(string name) { if ("pace".Equals(name)) { PdfPCell cell = new PdfPCell(); cell.AddElement(fs.Process(buf.ToString())); cell.Padding = 3; cell.UseAscender = true; cell.UseDescender = true; if (rtl) { cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL; } table.AddCell(language); table.AddCell(cell); table.AddCell(countries); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document(PageSize.A4)) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 FontSelector selector = new FontSelector(); selector.AddFont(FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12)); selector.AddFont(FontFactory.GetFont( "MSung-Light", "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED )); Phrase ph = selector.Process(TEXT); document.Add(new Paragraph(ph)); } }
private void DrawPageNumber(Font font) { #if DEBUG //Console.WriteLine("pageNumberBox: " + pageNumberBox.X + ", " + pageNumberBox.Y); #endif PdfReader reader = new PdfReader(stream.ToArray()); MemoryStream _stream = new MemoryStream(); PdfStamper stamper = new PdfStamper(reader, _stream); int currentPage = 1; int totalPage = 0; int drawPage = 1; PDFDrawItextSharp.PDFDrawItextSharp pDraw = (PDFDrawItextSharp.PDFDrawItextSharp)PdfDrawer; FontSelector selector = pDraw.FontSelector(font); foreach (int eachCount in EachPageCount) { if (drawPage == 1) { currentPage = 1; totalPage = eachCount; } else { currentPage = 1; totalPage = eachCount - totalPage; } while (drawPage <= eachCount) { #if DEBUG //Console.WriteLine("PDFTemplateItextSharp.DrawPageNumber: " + currentPage + "/" + totalPage); #endif if (PageNumberBoxes.Count < currentPage) { break; } var pageNumberBox = PageNumberBoxes[currentPage - 1]; Hashtable data = new Hashtable { { "{__PAGE__}", currentPage }, { "{__TOTALPAGE__}", totalPage } }; PdfContentByte cb = stamper.GetOverContent(drawPage); //iTextSharp.text.Phrase phrase = new iTextSharp.text.Chunk(pageNumberBox.GetText(data), font); Phrase phrase = selector.Process(pageNumberBox.GetText(data)); //Console.WriteLine("chunk.Content: " + chunk.Content); //iTextSharp.text.pdf.ColumnText column = new iTextSharp.text.pdf.ColumnText(cb); int align = PDFDrawItextSharpHelper.Align( Helper.GetAttributeValue( "align", pageNumberBox.Attributes, "Left")); //20130610 :: mellorasinxelas :: change to static class //20130721 :: cmwong :: change to PDFDrawItextSharp.DrawString() pDraw.DrawString(cb, phrase, pageNumberBox.X, pageNumberBox.Y, pageNumberBox.Width, align, null); currentPage++; drawPage++; } } stamper.Close(); stream = _stream; }
/// <summary> /// 转换GridView为PDF文档 /// </summary> /// <param name="sdr_Context">SqlDataReader</param> /// <param name="title">标题名称</param> /// <param name="fontpath_Title">标题字体路径</param> /// <param name="fontsize_Title">标题字体大小</param> /// <param name="fontStyle_Title">标题样式</param> /// <param name="fontColor_Title">标题颜色</param> /// <param name="fontpath_Col">列头字体路径</param> /// <param name="fontsize_Col">列头字体大小</param> /// <param name="fontStyle_Col">列头字体样式</param> /// <param name="fontColor_Col">列头字体颜色</param> /// <param name="col_Width">表格总宽度</param> /// <param name="arr_Width">每列的宽度</param> /// <param name="pdf_Filename">在服务器端保存PDF时的文件名</param> /// <param name="FontPath">正文字体路径</param> /// <param name="FontSize">正文字体大小</param> /// <param name="fontStyle_Context">正文字体样式</param> /// <param name="fontColor_Context">正文字体颜色</param> /// <param name="para">Criteria rows / Report header, depending on the mode</param> /// <returns>返回调用是否成功</returns> public static void exp_Pdf(string[] ExtendedFields, Dictionary <string, string> content, List <string> subtotal, List <string> subavg, List <string> SubCount, List <string> Count, List <string> group, List <string> avg, List <string> sum, string companyname, string[] para, System.Data.DataTable sdr_Context, string title, string fontpath_Title, float fontsize_Title, int fontStyle_Title, BaseColor fontColor_Title, string fontpath_Col, float fontsize_Col, int fontStyle_Col, BaseColor fontColor_Col, string tempFolderPath, string pdf_Filename, string FontPath, float FontSize, int fontStyle_Context, BaseColor fontColor_Context, string[] reportFooter = null) { bool showChangeOnly = ExtendedFields[0] == "1"; // CUSTOMERP.Model.REPORT.EXTENDFIELDs.ChangeOnly bool hideCriteria = ExtendedFields[1] == "1"; //CUSTOMRP.Model.REPORT.EXTENDFIELDs.HideCriteria Single tableWidth = (sdr_Context.Columns.Count * 200 >= 800 ? 800 : sdr_Context.Columns.Count * 200); //在服务器端保存PDF时的文件名 string strFileName = pdf_Filename + ".pdf"; //初始化一个目标文档类 Document document = new Document(PageSize.A4.Rotate(), 0, 0, 10, 10); //调用PDF的写入方法流 //注意FileMode-Create表示如果目标文件不存在,则创建,如果已存在,则覆盖。 //PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(HttpContext.Current.Server.MapPath(strFileName), FileMode.Create)); using (FileStream fs = new FileStream(tempFolderPath + strFileName, FileMode.Create)) { PdfWriter writer = PdfWriter.GetInstance(document, fs); //try //{ //标题字体 BaseFont basefont_Title = BaseFont.CreateFont(fontpath_Title, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font font_Title = new Font(basefont_Title, fontsize_Title, fontStyle_Title, fontColor_Title); Font font_COMPANY = new Font(basefont_Title, fontsize_Title - 3, fontStyle_Title, fontColor_Title); Font font_CRITERIAL = new Font(basefont_Title, fontsize_Title - 4, fontStyle_Title, fontColor_Title); Font font_DATETIME = new Font(basefont_Title, fontsize_Title - 4, fontStyle_Title, fontColor_Title); //表格列字体 BaseFont basefont_Col = BaseFont.CreateFont(fontpath_Col, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font font_Col = new Font(basefont_Col, fontsize_Col, fontStyle_Col, fontColor_Col); //正文字体 BaseFont basefont_Context = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); FontSelector selector = new FontSelector(); //Cheong - 2015/02/10 - use selector when phrase can have mixed language (like English and Chinese) selector.AddFont(FontFactory.GetFont(FontFactory.COURIER, FontSize, fontStyle_Context, fontColor_Context)); selector.AddFont(new Font(basefont_Context, FontSize, fontStyle_Context, fontColor_Context)); // feeded is SimSun for CHS selector.AddFont(FontFactory.GetFont("MHei-Medium", "UniCNS-UCS2-H", FontSize, fontStyle_Context, fontColor_Context)); // add CHT font FontSelector boldselector = new FontSelector(); //Cheong - 2015/02/10 - use selector when phrase can have mixed language (like English and Chinese) boldselector.AddFont(FontFactory.GetFont(FontFactory.COURIER, FontSize, fontStyle_Context | iTextSharp.text.Font.BOLD, fontColor_Context)); boldselector.AddFont(new Font(basefont_Context, FontSize, fontStyle_Context | iTextSharp.text.Font.BOLD, fontColor_Context)); // feeded is SimSun for CHS boldselector.AddFont(FontFactory.GetFont("MHei-Medium", "UniCNS-UCS2-H", FontSize, fontStyle_Context | iTextSharp.text.Font.BOLD, fontColor_Context)); // add CHT font FontSelector greyselector = new FontSelector(); //Cheong - 2015/02/10 - use selector when phrase can have mixed language (like English and Chinese) greyselector.AddFont(FontFactory.GetFont(FontFactory.COURIER, FontSize, fontStyle_Context, BaseColor.LIGHT_GRAY)); greyselector.AddFont(new Font(basefont_Context, FontSize, fontStyle_Context, BaseColor.LIGHT_GRAY)); // feeded is SimSun for CHS greyselector.AddFont(FontFactory.GetFont("MHei-Medium", "UniCNS-UCS2-H", FontSize, fontStyle_Context, BaseColor.LIGHT_GRAY)); // add CHT font //打开目标文档对象 document.Open(); #region Company name Paragraph Company = new Paragraph(companyname, font_COMPANY); Company.IndentationLeft = 100; Company.Alignment = Element.ALIGN_LEFT; document.Add(Company); #endregion Company name #region Report title Paragraph p_Title = new Paragraph(title, font_Title); p_Title.Alignment = Element.ALIGN_LEFT; p_Title.IndentationLeft = 100; p_Title.SpacingAfter = 8; document.Add(p_Title); #endregion Report Title #region Criteria //v1.1.0 - Cheong - 2016/06/01 - Hide criteria text if (!hideCriteria) { for (int i = 0; i < para.Length; i++) { Paragraph P_pa = new Paragraph(para[i], font_CRITERIAL); P_pa.Alignment = Element.ALIGN_LEFT; P_pa.IndentationLeft = 100; document.Add(P_pa); } } #endregion #region Print on date Paragraph P_date = new Paragraph("Print on : " + DateTime.Now.ToString("yyyy-MM-dd"), font_DATETIME); P_date.Alignment = Element.ALIGN_LEFT; P_date.IndentationLeft = 100; document.Add(P_date); P_date.SpacingBefore = 32; #endregion //根据数据表内容创建一个PDF格式的表 PdfPTable table = new PdfPTable(sdr_Context.Columns.Count); table.SpacingBefore = 42; table.TotalWidth = tableWidth; //表格总宽度 table.LockedWidth = true; //锁定宽度 List <int> arr = new List <int>(); for (int jj = 0; jj < sdr_Context.Columns.Count; jj++) { arr.Add(100); } table.SetWidths(arr.ToArray());//设置每列宽度 //构建列头 //设置列头背景色 table.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY; //设置列头文字水平、垂直居中 table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; table.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; // 告诉程序这行是表头,这样页数大于1时程序会自动为你加上表头。 table.HeaderRows = 1; if (sdr_Context.Rows.Count > 0) { for (int i = 0; i < sdr_Context.Columns.Count; i++) { //v1.0.0 - Cheong - 2015/05/27 - Use Displayname instead //table.AddCell(new Phrase(sdr_Context.Columns[i].ColumnName, font_Col)); table.AddCell(new Phrase(content[sdr_Context.Columns[i].ColumnName], font_Col)); } // 添加数据 //设置标题靠左居中 table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT; // 设置表体背景色 table.DefaultCell.BackgroundColor = BaseColor.WHITE; table.DefaultCell.BorderColor = BaseColor.WHITE; //start set value to each cell. int[] Subsum_Index = Function.IncWeb.getColumnIndexByColumnName(subtotal.ToArray(), sdr_Context.Columns); int[] Subavg_Index = Function.IncWeb.getColumnIndexByColumnName(subavg.ToArray(), sdr_Context.Columns); int[] Subcount_Index = Function.IncWeb.getColumnIndexByColumnName(SubCount.ToArray(), sdr_Context.Columns); int[] sum_Index = Function.IncWeb.getColumnIndexByColumnName(sum.ToArray(), sdr_Context.Columns); int[] avg_Index = Function.IncWeb.getColumnIndexByColumnName(avg.ToArray(), sdr_Context.Columns); int[] count_Index = Function.IncWeb.getColumnIndexByColumnName(Count.ToArray(), sdr_Context.Columns); int[] groupIndex = Function.IncWeb.getColumnIndexByColumnName(group.ToArray(), sdr_Context.Columns); subTotal[] subTotalInfo = new subTotal[Subsum_Index.Length]; subAvg[] subAvginfo = new subAvg[Subavg_Index.Length]; subCount[] subcountinfo = new subCount[Subcount_Index.Length]; for (int x = 0; x < subTotalInfo.Length; x++) { subTotalInfo[x].ColumnIndex = Subsum_Index[x]; } for (int y = 0; y < subAvginfo.Length; y++) { subAvginfo[y].ColumnIndex = Subavg_Index[y]; } int tempRowsCount = 0; for (int i = 0; i < sdr_Context.Rows.Count; i++) { //if (showType == "0") //{ if (groupIndex.Length > 0) { //v1.0.0 - Cheong - 2016/03/18 - Insert new row before each group (except the first one) if (i != 0) { for (int j = 0; j < sdr_Context.Columns.Count; j++) { table.AddCell(selector.Process(" ")); } } #region group header bool GroupBegin = false; if (i == 0) { GroupBegin = true; } else { for (int g_i = 0; g_i < groupIndex.Length; g_i++) { if (sdr_Context.Rows[i][groupIndex[g_i]].ToString() != sdr_Context.Rows[i - 1][groupIndex[g_i]].ToString()) { GroupBegin = true; break; } } } if (GroupBegin) { tempRowsCount = 0; StringBuilder sb = new StringBuilder(); //v1.0.0 - Cheong - 2015/05/27 - Use DisplayName instead //sb.AppendFormat("{0} : {1}", group[0], sdr_Context.Rows[i][groupIndex[0]]); //sb.AppendFormat("{0} : {1}", content[group[0]], sdr_Context.Rows[i][groupIndex[0]]); if (!Convert.IsDBNull(sdr_Context.Rows[i][groupIndex[0]])) { if (sdr_Context.Columns[groupIndex[0]].DataType == typeof(DateTime)) { string l_strDateTime = ((DateTime)sdr_Context.Rows[i][groupIndex[0]]).ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture); l_strDateTime = l_strDateTime.Replace("1900-01-01", "").Trim(); l_strDateTime = l_strDateTime.Replace("00:00:00", "").Trim(); sb.AppendFormat("{0} : {1}", content[group[0]], l_strDateTime); //row.CreateCell(j).SetCellValue(((DateTime)dt.Rows[i][j]).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)); } else { sb.AppendFormat("{0} : {1}", content[group[0]], sdr_Context.Rows[i][groupIndex[0]]); } } else { sb.AppendFormat("{0} : {1}", content[group[0]], String.Empty); } for (int g_i = 1; g_i < groupIndex.Length; g_i++) { //v1.0.0 - Cheong - 2015/05/27 - Same as above comment //sb.AppendFormat(" {0} : {1}", group[g_i], sdr_Context.Rows[i][groupIndex[g_i]]); //sb.AppendFormat(" {0} : {1}", content[group[g_i]], sdr_Context.Rows[i][groupIndex[g_i]]); if (!Convert.IsDBNull(sdr_Context.Rows[i][groupIndex[g_i]])) { if (sdr_Context.Columns[groupIndex[g_i]].DataType == typeof(DateTime)) { string l_strDateTime = ((DateTime)sdr_Context.Rows[i][groupIndex[g_i]]).ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture); l_strDateTime = l_strDateTime.Replace("1900-01-01", "").Trim(); l_strDateTime = l_strDateTime.Replace("00:00:00", "").Trim(); sb.AppendFormat(" {0} : {1}", content[group[g_i]], l_strDateTime); } else { sb.AppendFormat(" {0} : {1}", content[group[g_i]], sdr_Context.Rows[i][groupIndex[g_i]]); } } else { sb.AppendFormat(" {0} : {1}", content[group[g_i]], String.Empty); } } if (sdr_Context.Columns.Count == 1) { table.AddCell(new PdfPCell(boldselector.Process(sb.ToString())) /*BorderWidthTop = table.DefaultCell.BorderWidthTop * 2*/ } {
private void ReportBody() { var fontStyleBold = FontFactory.GetFont("Tahoma", 9f, 1); _fontStyle = FontFactory.GetFont("Tahoma", 9f, 0); #region Detail Tab Header _pdfCell = new PdfPCell(new Phrase("Id", fontStyleBold)); _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.VerticalAlignment = Element.ALIGN_MIDDLE; _pdfCell.BackgroundColor = BaseColor.Gray; _pdfTable.AddCell(_pdfCell); _pdfCell = new PdfPCell(new Phrase("Name", fontStyleBold)); _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.VerticalAlignment = Element.ALIGN_MIDDLE; _pdfCell.BackgroundColor = BaseColor.Gray; _pdfTable.AddCell(_pdfCell); _pdfCell = new PdfPCell(new Phrase("Address", fontStyleBold)); _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.VerticalAlignment = Element.ALIGN_MIDDLE; _pdfCell.BackgroundColor = BaseColor.Gray; _pdfTable.AddCell(_pdfCell); #endregion #region Detail Table Body foreach (var student in _students) { _pdfCell = new PdfPCell(new Phrase(student.Id.ToString(), _fontStyle)); _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.VerticalAlignment = Element.ALIGN_MIDDLE; _pdfCell.BackgroundColor = BaseColor.White; _pdfTable.AddCell(_pdfCell); // Registering KHmer Font string path = _webHostEnviroment.WebRootPath + "/fonts"; string khmerFontPath = Path.Combine(path, "Khmer Sangam MN.ttf", BaseFont.IDENTITY_H); string englishFontPath = Path.Combine(path, "Tahoma.ttf", BaseFont.IDENTITY_H); FontFactory.Register(khmerFontPath); Font khmerFont = FontFactory.GetFont("Khmer Sangam MN", BaseFont.IDENTITY_H); FontFactory.Register(englishFontPath); Font englishFont = FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H); FontSelector fontSelector = new FontSelector(); fontSelector.AddFont(khmerFont); fontSelector.AddFont(englishFont); // var phrase = fontSelector.Process(student.Name); _pdfCell = new PdfPCell(new Phrase(fontSelector.Process(student.Name))); _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.VerticalAlignment = Element.ALIGN_MIDDLE; _pdfCell.BackgroundColor = BaseColor.White; _pdfTable.AddCell(_pdfCell); _pdfCell = new PdfPCell(new Phrase(student.Address, this.GetFont("Khmer Sangam MN.ttf", 28))); _pdfCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfCell.VerticalAlignment = Element.ALIGN_MIDDLE; _pdfCell.BackgroundColor = BaseColor.White; _pdfTable.AddCell(_pdfCell); _pdfTable.CompleteRow(); } #endregion }
/// <summary> /// 导出图片和表格数据到Pdf /// </summary> /// <param name="strhead">表头文字</param> /// <param name="strfoot">表</param> /// <param name="filepath">文件名</param> /// <param name="图片地址">imgurl</param> public static void ExportPicToPdf(string strhead, string strfoot, string filename, string imgurl) { //Document.compress = false; Document document = new Document(PageSize.A3, 20f, 20f, 20f, 20f); //string strFileName = "Export" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ".pdf"; //string path = HttpContext.Current.Server.MapPath(BasePage.AppUrl + "_Temp") + @"\" + strFileName; string path = filename; try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create)); // step 3: we open the document document.Open(); StyleSheet style = new StyleSheet(); style.LoadTagStyle("body", "face", "SIMHEI"); style.LoadTagStyle("body", "encoding", "Identity-H"); style.LoadTagStyle("body", "leading", "12,0"); FontFactory.RegisterDirectory("c:\\Windows\\Fonts"); FontSelector selector = new FontSelector(); selector.AddFont(FontFactory.GetFont("Gulim", BaseFont.IDENTITY_H, false, 10)); if (!string.IsNullOrEmpty(strhead)) { Paragraph para1 = new Paragraph(selector.Process("")); HTMLWorker worker = new HTMLWorker(document); StringReader stringReader = new StringReader(strhead); System.Collections.ArrayList p = HTMLWorker.ParseToList(stringReader, style); for (int k = 0; k < p.Count; k++) { para1.Add((IElement)p[k]); } document.Add(para1); } // step 4: we create a table and add it to the document string url = imgurl; iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(url); //图片自适应大小 经验证PDF宽度大致为800以上像素 小于此宽不论 大于则自动缩放图片到宽度800 if (img.PlainWidth > 800) { img.ScalePercent(100 * 800 / img.PlainWidth); } //img.ScalePercent(100); document.Add(img); if (!string.IsNullOrEmpty(strfoot)) { Paragraph para2 = new Paragraph(selector.Process("")); HTMLWorker worker = new HTMLWorker(document); StringReader stringReader = new StringReader(strfoot); System.Collections.ArrayList p = HTMLWorker.ParseToList(stringReader, style); for (int k = 0; k < p.Count; k++) { para2.Add((IElement)p[k]); } document.Add(para2); } //document.Add(AddTable(strfoot)); } catch (DocumentException de) { System.Web.HttpContext.Current.Response.Write(de.Message); } catch (IOException ioe) { System.Web.HttpContext.Current.Response.Write(ioe.Message); } // step 5: we close the document document.Close(); // DownloadFile(path); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(Path.GetFileName(path).Trim()) + "\""); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.WriteFile(path); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.Close(); if (File.Exists(path)) { File.Delete(path); } HttpContext.Current.Response.End(); }
/// <summary> /// HTML导出PDF /// </summary> /// <param name="myGridView">表格GridView的HTML</param> /// <param name="filepath">filename文件名</param> public static void ExportToPdf(string myGridViewHtml, string filename) { try { //System.Web.HttpContext.Current.Response.ContentType = "application/pdf"; //System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=ExportPdf.pdf"); //System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); Document document = new Document(PageSize.A3, 20f, 20f, 20f, 20f); StyleSheet style = new StyleSheet(); style.LoadTagStyle("body", "face", "SIMHEI"); style.LoadTagStyle("body", "encoding", "Identity-H"); style.LoadTagStyle("body", "leading", "12,0"); FontFactory.RegisterDirectory("c:\\Windows\\Fonts"); FontSelector selector = new FontSelector(); string zhch = filename.Substring(filename.Length - 21, 4); BaseFont baseFont = BaseFont.CreateFont( "C:\\WINDOWS\\FONTS\\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); if (filename.Substring(filename.Length - 21, 4) == "工况明细") { //selector.AddFont(FontFactory.GetFont("Gulim", BaseFont.IDENTITY_H, false, 1)); selector.AddFont(new Font(baseFont, 2)); } else if (filename.Substring(filename.Length - 21, 4) == "方量分析") { //selector.AddFont(FontFactory.GetFont("Gulim", BaseFont.IDENTITY_H, false, 5)); selector.AddFont(new Font(baseFont, 5)); } else { //selector.AddFont(FontFactory.GetFont("Gulim", BaseFont.IDENTITY_H, false, 5)); selector.AddFont(new Font(baseFont, 5)); } Paragraph para = new Paragraph(selector.Process("")); HTMLWorker worker = new HTMLWorker(document); StringReader stringReader = new StringReader(myGridViewHtml); HeaderFooter footer = new HeaderFooter(new Phrase("page "), true); footer.Alignment = Element.ALIGN_RIGHT; footer.Border = Rectangle.NO_BORDER; document.Footer = footer; PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create)); document.Open(); System.Collections.ArrayList p = HTMLWorker.ParseToList(stringReader, style); for (int k = 0; k < p.Count; k++) { para.Add((IElement)p[k]); } document.Add(para); document.Close(); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(Path.GetFileName(filename).Trim()) + "\""); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.WriteFile(filename); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.Close(); } catch (DocumentException de) { System.Web.HttpContext.Current.Response.Write(de.ToString()); } if (File.Exists(filename)) { File.Delete(filename); } HttpContext.Current.Response.End(); }