Лучший отвечающий
Expot GridVew to PDF с использованием iTextSharp русский шрифт

Вопрос
-
Уважаемые друзья помогите с решением данной задачи:
есть файл *.aspx на нем расположен GridVew вот его код
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="5" PageSize="4" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" Width="800px"> <Columns> <asp:TemplateField HeaderText="№"> <ItemTemplate> <asp:Label ID="lblN" runat="server" Text='<%# Container.DataItemIndex + 1 %>' Font-Bold="true" Font-Names="arial" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Реестр закупок"> <ItemTemplate> <b><i> Наименование закупки:</i></b> <br /> <asp:Label ID="lblnameOrder" runat="server" Text='<%# Eval("nameOrder") %>' Font-Bold="true" Font-Names="arial" /> <br /> Сумма: <asp:Label ID="lblsummaOrder" runat="server" Text='<%# Eval("summaOrderUp", "{0:# ### ##0.00 руб.}") %>' Font-Bold="true" Font-Names="arial" /> <br /> Дата закупки: <asp:Label ID="lblperiodOr" runat="server" Text='<%# Eval("periodOr","{0:#-й квартал}" ) %>' Font-Bold="true" Font-Names="arial" /> <asp:Label ID="Label3" runat="server" Text='<%# Eval("dateOrderOff", "{0:(dd MMMM yyyy г.)}") %>' Font-Italic="true" Font-Names="arial" /> <br /> <b><i>Наименование и местонахождение поставщика (подрядчика, исполнителя услуг):</i></b> <br /> ИНН: <asp:Label ID="lblinnPro" runat="server" Text='<%# Eval("innPro") %>' Font-Bold="true" Font-Names="arial" /> наименование: <asp:Label ID="lblnamePro" runat="server" Text='<%# Eval("namePro") %>' Font-Bold="true" Font-Names="arial" /> <br /> Адрес: <asp:Label ID="lbladressPro" runat="server" Text='<%# Eval("adressPro") %>' Font-Bold="true" Font-Names="arial" /> телефон: <asp:Label ID="lbltelPro" runat="server" Text='<%# Eval("telPro") %>' Font-Bold="true" Font-Names="arial" /> e-mail: <asp:Label ID="lblemailPro" runat="server" Text='<%# Eval("emailPro") %>' Font-Bold="true" Font-Names="arial" /> </ItemTemplate> <HeaderStyle HorizontalAlign="Center" /> </asp:TemplateField> </Columns> <PagerSettings Mode="NumericFirstLast" /> </asp:GridView>
готовое решение в инете вот - GridView To Pdf
есть код *.cs этого файла - вот
using System; using System.Collections; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Text; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using kodeDSTableAdapters; using iTextSharp.text; using iTextSharp.text.html; using iTextSharp.text.html.simpleparser; using iTextSharp.text.pdf; public partial class Cabinet_Reporting : System.Web.UI.Page { tbN2731TableAdapter nomTA = new tbN2731TableAdapter(); lblidOkdpTableAdapter nameOKDPTA = new lblidOkdpTableAdapter(); lblidOsTableAdapter osnovTA = new lblidOsTableAdapter(); lblidKBKTableAdapter nameKbkTA = new lblidKBKTableAdapter(); tbOrdersProtokolTableAdapter ordProTA = new tbOrdersProtokolTableAdapter(); tbReestrTableAdapter reestrTA = new tbReestrTableAdapter(); protected void Page_Load(object sender, EventArgs e) { Response.Cache.SetCacheability(HttpCacheability.NoCache); GridView1Bind(); GridView3Bind(); } private void GridView1Bind() { GridView1.DataSource = reestrTA.GetData(); GridView1.DataBind(); } private void GridView3Bind() { GridView3.DataSource = ordProTA.GetDataHeldOrder(); GridView3.DataBind(); } ///1 ТАВ Реестр закупок, осуществленных без заключения государственных или муниципальных контрактов #region protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; GridView1Bind(); } public override void VerifyRenderingInServerForm(Control control) { } protected void btnExportRtf_Click(object sender, EventArgs e) { Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.rtf"); Response.Charset = ""; Response.ContentType = "text/rtf"; //Response.ContentType = "application/vnd.ms-word "; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); GridView1.AllowPaging = false; GridView1.DataBind(); GridView1.RenderControl(hw); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); } protected void btnExportCalc_Click(object sender, EventArgs e) { Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls"); Response.Charset = ""; Response.ContentType = "application/vnd.ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); GridView1.AllowPaging = false; GridView1.DataBind(); for (int i = 0; i < GridView1.Rows.Count; i++) { GridViewRow row = GridView1.Rows[i]; //Apply text style to each Row row.Attributes.Add("class", "textmode"); } GridView1.RenderControl(hw); //style to format numbers to string string style = @"<style> .textmode { mso-number-format:\@; } </style>"; Response.Write(style); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); } protected void btnExport_Click(object sender, EventArgs e) { ExportPDF(); } private static string GetPath(string path) { return Path.GetFullPath(path).Replace("~/", ""); } private void ExportPDF() { try { iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(GridView1.Columns.Count); table.RunDirection = PdfWriter.RUN_DIRECTION_RTL; //BaseFont bf = BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\arial.ttf", System.Text.Encoding.GetEncoding("1251").BodyName, true); //Очень важно указывать шрифт вручную, иначе кирилица не будет отображатся в Pdf документе //BaseFont bf1 = BaseFont.CreateFont(GetPath(@"fonts/") + "arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //BaseFont font = BaseFont.CreateFont(@"C:\Windows\Fonts\arial.ttf", "Identity-H", false); //BaseFont bf = BaseFont.CreateFont(Server.MapPath("~/fonts/arial.ttf"), "Identity-H", false); //BaseFont bf = BaseFont.CreateFont(Server.MapPath("~/fonts/arial.ttf"), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // BaseFont bf = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); //BaseFont bf = BaseFont.CreateFont(Server.MapPath("~/fonts/arial.ttf"), "windows-1251", true); BaseFont bf = iTextSharp.text.pdf.BaseFont.CreateFont(Server.MapPath("~/fonts/arial.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var defaultFont = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK); var italicFont = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.ITALIC, iTextSharp.text.Color.BLACK); var titleFont = new iTextSharp.text.Font(bf, 15, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK); iTextSharp.text.Font f2 = new iTextSharp.text.Font(bf, 8); //Set the column widths int[] widths = new int[GridView1.Columns.Count]; for (int x = 0; x <= GridView1.Columns.Count - 1; x++) { widths[x] = Convert.ToInt32(GridView1.Columns[x].ItemStyle.Width.Value); string cellText = Page.Server.HtmlDecode(GridView1.HeaderRow.Cells[x].Text); iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(10, cellText, f2)); cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL; table.AddCell(cell); } //Transfer rows from GridView to table for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { if (GridView1.Rows[i].RowType == DataControlRowType.DataRow) { for (int j = 0; j <= GridView1.Columns.Count - 1; j++) { string cellText = Page.Server.HtmlDecode(GridView1.Rows[i].Cells[j].Text); iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(10, cellText, f2)); cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL; table.AddCell(cell); } } } //Create the PDF Document Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); PdfWriter.GetInstance(pdfDoc, Page.Response.OutputStream); pdfDoc.Open(); Chunk c = new Chunk("Реестр закупок \n", FontFactory.GetFont(bf.ToString(), 14)); Paragraph p = new Paragraph(); p.Alignment = Element.ALIGN_CENTER; p.Add(c); Chunk chunk1 = new Chunk("www@krakoss.ru \n\n", FontFactory.GetFont(bf.ToString(), 8)); Paragraph p1 = new Paragraph(); p1.Alignment = Element.ALIGN_RIGHT; p1.Add(chunk1); pdfDoc.Add(p); pdfDoc.Add(p1); pdfDoc.Add(table); pdfDoc.Close(); Page.Response.ContentType = "application/pdf"; Page.Response.AddHeader("content-disposition", "attachment;filename=Reestr.pdf"); Page.Response.Cache.SetCacheability(HttpCacheability.NoCache); Page.Response.Write(pdfDoc); Page.Response.End(); } catch (Exception ex) { Page.Response.Write(ex.Message); } } /// и еще раз в PDF /// /// protected void btnExportPdf_Click(object sender, EventArgs e) { ExportToPDF(GridView1, true); } protected void ExportToPDF(GridView gvReport, bool LandScape) { int noOfColumns = 0, noOfRows = 0; DataTable tbl = null; if (gvReport.AutoGenerateColumns) { tbl = gvReport.DataSource as DataTable; // Gets the DataSource of the GridView Control. noOfColumns = tbl.Columns.Count; noOfRows = tbl.Rows.Count; } else { noOfColumns = gvReport.Columns.Count; noOfRows = gvReport.Rows.Count; } float HeaderTextSize = 8; float ReportNameSize = 10; float ReportTextSize = 8; float ApplicationNameSize = 7; // Creates a PDF document Document document = null; if (LandScape == true) { // Sets the document to A4 size and rotates it so that the orientation of the page is Landscape. document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5); } else { document = new Document(PageSize.A4, 0, 0, 15, 5); } // Creates a PdfPTable with column count of the table equal to no of columns of the gridview or gridview datasource. iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns); // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages. mainTable.HeaderRows = 4; // Creates a PdfPTable with 2 columns to hold the header in the exported PDF. iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2); // Creates a phrase to hold the application name at the left hand side of the header. Phrase phApplicationName = new Phrase("Реестр закупок", FontFactory.GetFont("Times New Roman", ApplicationNameSize, iTextSharp.text.Font.NORMAL)); // Creates a PdfPCell which accepts a phrase as a parameter. PdfPCell clApplicationName = new PdfPCell(phApplicationName); // Sets the border of the cell to zero. clApplicationName.Border = PdfPCell.NO_BORDER; // Sets the Horizontal Alignment of the PdfPCell to left. clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT; // Creates a phrase to show the current date at the right hand side of the header. Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Times New Roman", ApplicationNameSize, iTextSharp.text.Font.NORMAL)); // Creates a PdfPCell which accepts the date phrase as a parameter. PdfPCell clDate = new PdfPCell(phDate); // Sets the Horizontal Alignment of the PdfPCell to right. clDate.HorizontalAlignment = Element.ALIGN_RIGHT; // Sets the border of the cell to zero. clDate.Border = PdfPCell.NO_BORDER; // Adds the cell which holds the application name to the headerTable. headerTable.AddCell(clApplicationName); // Adds the cell which holds the date to the headerTable. headerTable.AddCell(clDate); // Sets the border of the headerTable to zero. headerTable.DefaultCell.Border = PdfPCell.NO_BORDER; // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable. PdfPCell cellHeader = new PdfPCell(headerTable); cellHeader.Border = PdfPCell.NO_BORDER; // Sets the column span of the header cell to noOfColumns. cellHeader.Colspan = noOfColumns; // Adds the above header cell to the table. mainTable.AddCell(cellHeader); // Creates a phrase which holds the file name. Phrase phHeader = new Phrase("Реестр закупок", FontFactory.GetFont("Times New Roman", ReportNameSize, iTextSharp.text.Font.BOLD)); PdfPCell clHeader = new PdfPCell(phHeader); clHeader.Colspan = noOfColumns; clHeader.Border = PdfPCell.NO_BORDER; clHeader.HorizontalAlignment = Element.ALIGN_CENTER; mainTable.AddCell(clHeader); // Creates a phrase for a new line. Phrase phSpace = new Phrase("\n"); PdfPCell clSpace = new PdfPCell(phSpace); clSpace.Border = PdfPCell.NO_BORDER; clSpace.Colspan = noOfColumns; mainTable.AddCell(clSpace); // Sets the gridview column names as table headers. for (int i = 0; i < noOfColumns; i++) { Phrase ph = null; if (gvReport.AutoGenerateColumns) { ph = new Phrase(tbl.Columns[i].ColumnName, FontFactory.GetFont("Times New Roman", HeaderTextSize, iTextSharp.text.Font.BOLD)); } else { ph = new Phrase(gvReport.Columns[i].HeaderText, FontFactory.GetFont("Times New Roman", HeaderTextSize, iTextSharp.text.Font.BOLD)); } mainTable.AddCell(ph); } // Reads the gridview rows and adds them to the mainTable for (int rowNo = 0; rowNo < noOfRows; rowNo++) { for (int columnNo = 0; columnNo < noOfColumns; columnNo++) { if (gvReport.AutoGenerateColumns) { string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim(); Phrase ph = new Phrase(s, FontFactory.GetFont("Times New Roman", ReportTextSize, iTextSharp.text.Font.NORMAL)); mainTable.AddCell(ph); } else { if (gvReport.Columns[columnNo] is TemplateField) { DataBoundLiteralControl lc = gvReport.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl; if (lc != null) { string s = lc.Text.Trim(); Phrase ph = new Phrase(s, FontFactory.GetFont("Times New Roman", ReportTextSize, iTextSharp.text.Font.NORMAL)); mainTable.AddCell(ph); } } else { string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim(); Phrase ph = new Phrase(s, FontFactory.GetFont("Times New Roman", ReportTextSize, iTextSharp.text.Font.NORMAL)); mainTable.AddCell(ph); } } } // Tells the mainTable to complete the row even if any cell is left incomplete. mainTable.CompleteRow(); } // Gets the instance of the document created and writes it to the output stream of the Response object. PdfWriter.GetInstance(document, Response.OutputStream); // Creates a footer for the PDF document. HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true); pdfFooter.Alignment = Element.ALIGN_CENTER; pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER; // Sets the document footer to pdfFooter. document.Footer = pdfFooter; // Opens the document. document.Open(); // Adds the mainTable to the document. document.Add(mainTable); // Closes the document. document.Close(); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment; filename = Reestr.pdf"); Response.End(); } /// и еще раз в PDF /// это выводит все надписи только не понимает русский шрифт /// надо его как то подключить??? protected void btnGridToPdf_Click(object sender, EventArgs e) { GridToPDF(); } protected void GridToPDF() { Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); GridView1.AllowPaging = false; GridView1.DataBind(); GridView1.RenderControl(hw); StringReader sr = new StringReader(sw.ToString()); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); } /// /// <summary> /// еще раз пробуем вывести gridView в документ PDF с поддержкой русских шрифтов /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnGridViewToPdf_Click(object sender, EventArgs e) { GridViewToPdf(); } private void GridViewToPdf() { Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=4_Reestr.pdf"); Document document = new Document(PageSize.A4, 10f, 10f, 10f, 0f); String FONT_LOCATION = Server.MapPath("~/fonts/arial.ttf"); BaseFont baseFont = BaseFont.CreateFont(FONT_LOCATION, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL); PdfWriter.GetInstance(document, Response.OutputStream); //открыли документ document.Open(); //добавили Параграф document.Add(new Paragraph("Русский \n\n", font)); //Создадим таблицу PdfPTable table = new PdfPTable(GridView1.Columns.Count); //Создадим заголовок table.AddCell(new PdfPCell(new Paragraph("Реестр\n\n", font)) { Colspan = GridView1.Columns.Count }); //работа с ГридВью for (int i = 0; i < GridView1.Rows.Count; i++) { for (int j = 0; j < GridView1.Columns.Count; j++) { string value = GridView1.Rows[i].Cells[j].Text.ToString(); PdfPCell cell = new PdfPCell(new Paragraph(value.ToString(), font)); table.AddCell(cell); } } document.Add(table); document.Close(); } #endregion ///3 ТАВ Не состоявшиеся закупки #region protected void GridView3_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) e.Row.BackColor = System.Drawing.Color.AliceBlue; if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='#F0F8FF'"; e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='#FFFFFF'"; ////добавление строк между строками с Данными e.Row.BackColor = System.Drawing.Color.White; TableCell tableCell = new TableCell(); tableCell.Attributes["ColSpan"] = GridView3.Columns.Count.ToString(); tableCell.BackColor = System.Drawing.Color.SkyBlue; GridViewRow gridViewRow = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal); gridViewRow.Cells.Add(tableCell); System.Web.UI.WebControls.Table table = e.Row.Parent as System.Web.UI.WebControls.Table; table.Controls.AddAt(GridView3.Controls[0].Controls.Count, gridViewRow); ////все закончили данную работу Int64 _id_N = (Int64)(DataBinder.Eval(e.Row.DataItem, "idN")); int _id_N1 = Convert.ToInt32(_id_N); if (_id_N1 > 0) { string _nameN = Convert.ToString(nomTA.GetData(_id_N1)[0]["nameN"].ToString()); System.Web.UI.WebControls.Image _imgI = (System.Web.UI.WebControls.Image)e.Row.FindControl("imgI"); _imgI.ToolTip = _nameN; } String _code = (String)(DataBinder.Eval(e.Row.DataItem, "idOkdp")); if (_code.Length > 0) { string _name = Convert.ToString(nameOKDPTA.GetData(_code)[0]["name"].ToString()); System.Web.UI.WebControls.Image _imgOkdp = (System.Web.UI.WebControls.Image)e.Row.FindControl("imgOkdp"); _imgOkdp.ToolTip = _name; } Int64 _idOs = (Int64)(DataBinder.Eval(e.Row.DataItem, "idOs")); if (Convert.ToInt32(_idOs) > 0) { string _descripnonOS = Convert.ToString(osnovTA.GetData(Convert.ToInt32(_idOs))[0]["descripnonOS"].ToString()); Label _descripnonOS1 = (Label)e.Row.FindControl("descripnonOS"); _descripnonOS1.Text = _descripnonOS; string _summaOs = Convert.ToString(osnovTA.GetData(Convert.ToInt32(_idOs))[0]["summaOs"].ToString()); if (_summaOs.Length > 2) { System.Web.UI.WebControls.Image _imgsummaOs = (System.Web.UI.WebControls.Image)e.Row.FindControl("imgsummaOs"); _imgsummaOs.ToolTip = String.Format("{0:C}", Convert.ToDecimal(_summaOs)); } else { System.Web.UI.WebControls.Image _imgsummaOs = (System.Web.UI.WebControls.Image)e.Row.FindControl("imgsummaOs"); _imgsummaOs.Visible = false; } } Int64 _idKBK = (Int64)(DataBinder.Eval(e.Row.DataItem, "idKBK")); if (Convert.ToInt32(_idKBK) > 0) { string _codeKBK = Convert.ToString(nameKbkTA.GetData(Convert.ToInt32(_idKBK))[0]["codeKBK"].ToString()); Label _codeKBK1 = (Label)e.Row.FindControl("codeKBK"); _codeKBK1.Text = _codeKBK; string _nameKBK = Convert.ToString(nameKbkTA.GetData(Convert.ToInt32(_idKBK))[0]["nameKBK"].ToString()); System.Web.UI.WebControls.Image _ImageKBK = (System.Web.UI.WebControls.Image)e.Row.FindControl("ImageKBK"); _ImageKBK.ToolTip = _nameKBK; } } } protected void GridView3_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView3.PageIndex = e.NewPageIndex; GridView3Bind(); } #endregion }
в нем реализовано 4 способа вывода GridView To PDF - но не один из них не дает нужного результата
на тестовом проекте можно увидеть что получается
в созданном файле не отображаются данные русского шрифта
подскажите как решить данную задачу
С уважением Юрий
28 марта 2012 г. 8:18
Ответы
-
решение найдено
вот код
protected void btnGridViewToPdf_Click(object sender, EventArgs e) { GridViewToPdf(); } private void GridViewToPdf() { Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=Reestr.pdf"); //подключаем шрифт String FONT_LOCATION = Server.MapPath("~/fonts/arial.ttf"); BaseFont baseFont = BaseFont.CreateFont(FONT_LOCATION, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL); iTextSharp.text.Font italicFont = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.ITALIC); //подключили //создаем PDF документ Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); //Создадим таблицу PdfPTable table = new PdfPTable(2); //Создадим заголовок table.AddCell(new PdfPCell(new Paragraph("\nРеестр закупок\n\n", font)) { Colspan = 2, HorizontalAlignment=1 }); //столбцы шириной в пропорции - 1/15 и 14/15 float[] widths = new float[] { 1f, 14f }; table.SetWidths(widths); //оставлять зазор до и после таблицы table.SpacingBefore = 10f; table.SpacingAfter = 10f; PdfPCell cell = new PdfPCell(new Phrase()); cell.Padding = 5; cell.Colspan = 3; foreach (GridViewRow row in GridView1.Rows) { if (row.RowType == DataControlRowType.DataRow) { Label _lblN = row.FindControl("lblN") as Label; String lblN = _lblN.Text.ToString(); Label _lblnameOrder = row.FindControl("lblnameOrder") as Label; String lblnameOrder = _lblnameOrder.Text.ToString(); Label _lblsummaOrder = row.FindControl("lblsummaOrder") as Label; String lblsummaOrder = _lblsummaOrder.Text.ToString(); Label _lblperiodOr = row.FindControl("lblperiodOr") as Label; String lblperiodOr = _lblperiodOr.Text.ToString(); Label _lbldateOrderOff = row.FindControl("lbldateOrderOff") as Label; String lbldateOrderOff = _lbldateOrderOff.Text.ToString(); /// PdfPCell cell1 = new PdfPCell(new Phrase(lblN, font)) { HorizontalAlignment = 1, VerticalAlignment= 1 }; table.AddCell(cell1); /// table.AddCell(new PdfPCell(new Phrase("Наименование закупки: " + lblnameOrder + "\nСумма: " + lblsummaOrder + "\nДата закупки: " + lblperiodOr + " " + lbldateOrderOff, font))); } } pdfDoc.Add(table); pdfDoc.Close(); Response.End(); }
то есть читаем данные из GridView и вносим их на страницу PDF документа8 августа 2012 г. 7:00
Все ответы
-
Здравствуйте.
Так русский текс в названии таблицы же отображается нормально, скорей всего проблема в чем-то другом.
Попробуйте сначала просто в коде (не основываясь ни на чем) сформировать простеньку таблицу с какими то "забитыми" по умолчанию данными. Для начала чтобы были только латинские буквы. После попробовать поменять их на кириллицу. Так вы сможете локализовать проблему.
Для связи [mail]
29 марта 2012 г. 5:54Модератор -
Ваш вариант я еже пробовал - именно - проблема с кириллицей
вот код одного из вариантов работы - он полностью рабочий
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using iTextSharp.text; using iTextSharp.text.html; using iTextSharp.text.pdf; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DataTable tbl = new DataTable(); tbl.Columns.Add("First Name"); tbl.Columns.Add("Middle Name"); tbl.Columns.Add("Last Name"); tbl.Columns.Add("Age"); for (int i = 1; i <= 500; i++) { DataRow trow = tbl.NewRow(); trow[0] = "First Name" + " " + i.ToString(); trow[1] = "Middle Name" + " " + i.ToString(); trow[2] = "Last Name" + " " + i.ToString(); trow[3] = i.ToString(); tbl.Rows.Add(trow); } gvExport.DataSource = tbl; gvExport.DataBind(); } protected void btnExport_Click(object sender, EventArgs e) { ExportToPDF(gvExport, true); } protected void ExportToPDF(GridView gvReport, bool LandScape) { int noOfColumns = 0, noOfRows = 0; DataTable tbl = null; if (gvReport.AutoGenerateColumns) { tbl = gvReport.DataSource as DataTable; // Gets the DataSource of the GridView Control. noOfColumns = tbl.Columns.Count; noOfRows = tbl.Rows.Count; } else { noOfColumns = gvReport.Columns.Count; noOfRows = gvReport.Rows.Count; } float HeaderTextSize = 8; float ReportNameSize = 10; float ReportTextSize = 8; float ApplicationNameSize = 7; // Creates a PDF document Document document = null; if (LandScape == true) { // Sets the document to A4 size and rotates it so that the orientation of the page is Landscape. document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5); } else { document = new Document(PageSize.A4, 0, 0, 15, 5); } // Creates a PdfPTable with column count of the table equal to no of columns of the gridview or gridview datasource. iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns); // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages. mainTable.HeaderRows = 4; // Creates a PdfPTable with 2 columns to hold the header in the exported PDF. iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2); // Creates a phrase to hold the application name at the left hand side of the header. Phrase phApplicationName = new Phrase("Sample Application", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL)); // Creates a PdfPCell which accepts a phrase as a parameter. PdfPCell clApplicationName = new PdfPCell(phApplicationName); // Sets the border of the cell to zero. clApplicationName.Border = PdfPCell.NO_BORDER; // Sets the Horizontal Alignment of the PdfPCell to left. clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT; // Creates a phrase to show the current date at the right hand side of the header. Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL)); // Creates a PdfPCell which accepts the date phrase as a parameter. PdfPCell clDate = new PdfPCell(phDate); // Sets the Horizontal Alignment of the PdfPCell to right. clDate.HorizontalAlignment = Element.ALIGN_RIGHT; // Sets the border of the cell to zero. clDate.Border = PdfPCell.NO_BORDER; // Adds the cell which holds the application name to the headerTable. headerTable.AddCell(clApplicationName); // Adds the cell which holds the date to the headerTable. headerTable.AddCell(clDate); // Sets the border of the headerTable to zero. headerTable.DefaultCell.Border = PdfPCell.NO_BORDER; // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable. PdfPCell cellHeader = new PdfPCell(headerTable); cellHeader.Border = PdfPCell.NO_BORDER; // Sets the column span of the header cell to noOfColumns. cellHeader.Colspan = noOfColumns; // Adds the above header cell to the table. mainTable.AddCell(cellHeader); // Creates a phrase which holds the file name. Phrase phHeader = new Phrase("Sample Export", FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD)); PdfPCell clHeader = new PdfPCell(phHeader); clHeader.Colspan = noOfColumns; clHeader.Border = PdfPCell.NO_BORDER; clHeader.HorizontalAlignment = Element.ALIGN_CENTER; mainTable.AddCell(clHeader); // Creates a phrase for a new line. Phrase phSpace = new Phrase("\n"); PdfPCell clSpace = new PdfPCell(phSpace); clSpace.Border = PdfPCell.NO_BORDER; clSpace.Colspan = noOfColumns; mainTable.AddCell(clSpace); // Sets the gridview column names as table headers. for (int i = 0; i < noOfColumns; i++) { Phrase ph = null; if (gvReport.AutoGenerateColumns) { ph = new Phrase(tbl.Columns[i].ColumnName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD)); } else { ph = new Phrase(gvReport.Columns[i].HeaderText, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD)); } mainTable.AddCell(ph); } // Reads the gridview rows and adds them to the mainTable for (int rowNo = 0; rowNo < noOfRows; rowNo++) { for (int columnNo = 0; columnNo < noOfColumns; columnNo++) { if (gvReport.AutoGenerateColumns) { string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim(); Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL)); mainTable.AddCell(ph); } else { if (gvReport.Columns[columnNo] is TemplateField) { DataBoundLiteralControl lc = gvReport.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl; string s = lc.Text.Trim(); Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL)); mainTable.AddCell(ph); } else { string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim(); Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL)); mainTable.AddCell(ph); } } } // Tells the mainTable to complete the row even if any cell is left incomplete. mainTable.CompleteRow(); } // Gets the instance of the document created and writes it to the output stream of the Response object. PdfWriter.GetInstance(document, Response.OutputStream); // Creates a footer for the PDF document. HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true); pdfFooter.Alignment = Element.ALIGN_CENTER; pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER; // Sets the document footer to pdfFooter. document.Footer = pdfFooter; // Opens the document. document.Open(); // Adds the mainTable to the document. document.Add(mainTable); // Closes the document. document.Close(); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf"); Response.End(); } }
и сама страница
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Sample Export</title> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> <td> <center><b>Export GridView to PDF</b></center> </td> </tr> <tr> <td> <!-- Div tag to provide scrolling for the grid view --> <div style="height:400px; overflow:auto"> <asp:GridView ID="gvExport" runat="server" AutoGenerateColumns="true" PageSize="15"> </asp:GridView> </div> </td> </tr> <tr> <td> <asp:Button ID="btnExport" runat="server" Text="Export to PDF" OnClick="btnExport_Click" /> </td> </tr> </table> </div> </form> </body> </html>
обратился в службу поддержки
Thank you for your response to my letter to Garry I beg you to help with the solution of this problem http://social.msdn.microsoft.com/Forums/ru-RU/aspnetru/thread/6894f142-bf35-4046-a920-0f41c9cca85d After that I will be able to make a decision about purchasing your product С уважением Юрий Косенко www.krakoss.ru www@krakoss.ru
жду ответа еще и от самих производителей данной библиотеки
Если еще есть варианты - то предлагайте
30 марта 2012 г. 1:13 -
Здравствуйте.
Вам что-нибудь удалось выяснить у разработчиков библиотеки? Проблема все еще нужнается в решении?
Для связи [mail]
4 апреля 2012 г. 10:50Модератор -
разработчики библиотеки ответили что служба поддержки может помочь только после приобретения у них данного продукта
Проблема все еще нужнается в решении - да -
вот новый адрес страницы в инете - Тестовая версия
11 апреля 2012 г. 3:06 -
решение найдено
вот код
protected void btnGridViewToPdf_Click(object sender, EventArgs e) { GridViewToPdf(); } private void GridViewToPdf() { Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=Reestr.pdf"); //подключаем шрифт String FONT_LOCATION = Server.MapPath("~/fonts/arial.ttf"); BaseFont baseFont = BaseFont.CreateFont(FONT_LOCATION, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL); iTextSharp.text.Font italicFont = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.ITALIC); //подключили //создаем PDF документ Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); //Создадим таблицу PdfPTable table = new PdfPTable(2); //Создадим заголовок table.AddCell(new PdfPCell(new Paragraph("\nРеестр закупок\n\n", font)) { Colspan = 2, HorizontalAlignment=1 }); //столбцы шириной в пропорции - 1/15 и 14/15 float[] widths = new float[] { 1f, 14f }; table.SetWidths(widths); //оставлять зазор до и после таблицы table.SpacingBefore = 10f; table.SpacingAfter = 10f; PdfPCell cell = new PdfPCell(new Phrase()); cell.Padding = 5; cell.Colspan = 3; foreach (GridViewRow row in GridView1.Rows) { if (row.RowType == DataControlRowType.DataRow) { Label _lblN = row.FindControl("lblN") as Label; String lblN = _lblN.Text.ToString(); Label _lblnameOrder = row.FindControl("lblnameOrder") as Label; String lblnameOrder = _lblnameOrder.Text.ToString(); Label _lblsummaOrder = row.FindControl("lblsummaOrder") as Label; String lblsummaOrder = _lblsummaOrder.Text.ToString(); Label _lblperiodOr = row.FindControl("lblperiodOr") as Label; String lblperiodOr = _lblperiodOr.Text.ToString(); Label _lbldateOrderOff = row.FindControl("lbldateOrderOff") as Label; String lbldateOrderOff = _lbldateOrderOff.Text.ToString(); /// PdfPCell cell1 = new PdfPCell(new Phrase(lblN, font)) { HorizontalAlignment = 1, VerticalAlignment= 1 }; table.AddCell(cell1); /// table.AddCell(new PdfPCell(new Phrase("Наименование закупки: " + lblnameOrder + "\nСумма: " + lblsummaOrder + "\nДата закупки: " + lblperiodOr + " " + lbldateOrderOff, font))); } } pdfDoc.Add(table); pdfDoc.Close(); Response.End(); }
то есть читаем данные из GridView и вносим их на страницу PDF документа8 августа 2012 г. 7:00 -
Спасибо, что выложили решение.8 августа 2012 г. 11:54Модератор