locked
itext export to pdf - Document has no page RRS feed

  • Question

  • User1487175000 posted

    Hi,

    I am using itext dll to export my gridview to PDF. But its gave me following error when its converting to PDF. 

    Error

    Server Error in '/Konferense Booking System' Application.
    
    The document has no pages.
    
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
    
    Exception Details: System.IO.IOException: The document has no pages.
    
    Source Error: 
    
    
    Line 85:         pdfDoc.Open();
    Line 86:         htmlparser.Parse(sr);
    Line 87:         pdfDoc.Close();
    Line 88:         Response.Write(pdfDoc);
    Line 89:         Response.End();  
    
    Source File: c:\Drive D\S&M IT Services\7A\Konferense Booking System\SearchBooking.aspx.cs    Line: 87 
    
    Stack Trace: 
    
    
    [IOException: The document has no pages.]
       iTextSharp.text.pdf.PdfPages.WritePageTree() +190
       iTextSharp.text.pdf.PdfWriter.Close() +549
       iTextSharp.text.pdf.PdfDocument.Close() +373
       iTextSharp.text.Document.Close() +165
       SearchBooking.btnDownloadPDF_Click(Object sender, EventArgs e) in c:\Drive D\S&M IT Services\7A\Konferense Booking System\SearchBooking.aspx.cs:87
       System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e) +115
       System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +120
       System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
       System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
       System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
    

    ASPX

     <table width="100%">
            <tr>
                <td colspan="2" width="100%">
                <center>
                    <h3 style="color: #993300;">Sök Bokning</h3>
                 
                </center>
                </td>
            </tr>
            <tr>
                <td colspan="2" width="100%">
                <center>
                    <asp:ImageButton ID="btnDownload" runat="server" ImageUrl="~/images/excel.png" 
                    onclick="btnDownload_Click" ToolTip="Export to excel"/>
                    <asp:ImageButton ID="btnDownloadPDF" runat="server" 
                    ToolTip="Export to PDF" ImageUrl="~/images/pdf.png" 
                        onclick="btnDownloadPDF_Click"/>
                </center>
                </td>
            </tr>
            <tr>
                <td colspan="2" width="100%">
                    <center>
                        <asp:GridView ID="gvSearchBooking" runat="server" CssClass="mGrid">
                        </asp:GridView>
                    </center>
                </td>
            </tr>
        </table>

    Code Behind

      public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }
     protected void btnDownloadPDF_Click(object sender, EventArgs e)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=SearchBooking.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            gvSearchBooking.AllowPaging = false;
            gvSearchBooking.DataBind();
            gvSearchBooking.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();  
        }



    Friday, April 26, 2013 5:41 PM

All replies

  • User1508394307 posted

    Things to check

    1) there can be a problem to generate pdf from a gridview. Make sure that some simple html is working, e.g.

    //htmlparser.Parse(sr);
    htmlparser.Parse(new StringReader("hello world"));

    2) if it does work, try to save pdf file on the server and not directly send it with Response.Write(pdfDoc); See if it saved and can't be opened from server.

    Friday, April 26, 2013 6:37 PM
  • User-1137493631 posted
    Document document = new Document();
    document.Open();
    document.NewPage();
    AddParagraph(item, document);
    document.Close();

    Friday, April 26, 2013 8:19 PM
  • User1487175000 posted

    after update my code still getting The document has no page.

    Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=SearchBooking.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
    
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
    
            gvSearchBooking.AllowPaging = false;
            gvSearchBooking.DataBind();
            gvSearchBooking.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();
            pdfDoc.NewPage();
            htmlparser.Parse(sr);
            pdfDoc.Close();
    
            Response.Write(pdfDoc);
            Response.End();



    Saturday, April 27, 2013 6:07 AM
  • User1508394307 posted

    What did you update? Added pdfDoc.NewPage();? It's required only if you need a page break and will not help to solve your issue. Please see my previous post above.

    Saturday, April 27, 2013 6:19 AM
  • User1487175000 posted

    When do the following code its gave me this error the "AddParagraph" does not exist in this context.

    pdfDoc.Open();
    pdfDoc.NewPage();

    AddParagraph(htmlparser.Parse(sr), pdfDoc);
    pdfDoc.Close();

    Saturday, April 27, 2013 6:23 AM
  • User1487175000 posted

    I am following this tutorial to export my gridview to PDF.

    http://www.aspdotnet-suresh.com/2011/04/how-to-export-gridview-data-to-pdf.html

    I just want to create a pdf file of my gridview data. 

    Saturday, April 27, 2013 6:26 AM
  • User1508394307 posted

    Again, I asked you regarding following

    1) there can be a problem to generate pdf from a gridview. Make sure that some simple html is working, e.g.

    //htmlparser.Parse(sr);
    htmlparser
    .Parse(new StringReader("hello world"));

    2) if it does work, try to save pdf file on the server and not directly send it with Response.Write(pdfDoc); See if it saved and can't be opened from server.

    Saturday, April 27, 2013 6:36 AM
  • User1487175000 posted

    Yes with simple HTML its working. Its generate PDF file with Hello World

    Saturday, April 27, 2013 6:40 AM
  • User1487175000 posted

    2) if it does work, try to save pdf file on the server and not directly send it with Response.Write(pdfDoc); See if it saved and can't be opened from server.

    How i can save pdf file on the server.

    Saturday, April 27, 2013 6:44 AM
  • User1508394307 posted

    So, the problem is 

    - not in missing pdfDoc.NewPage();
    - not in missing AddParagraph(...);

    but in the content of your gridview.

    Even it does work in some tutorials, it might not work in many cases because GridView may include many html/javascript code that will not be understood by itextsharp.  

    Either try to simplify your gridview (e.g. format it exactly as per your tutorial) and see if it helps, or create a new method that will create a pure table from scratch by using itextsharp objects PdfPTable and PdfPCell as explained at http://www.mikesdotnetting.com/Article/86/iTextSharp-Introducing-Tables

    Hope this helps.

    Saturday, April 27, 2013 6:47 AM
  • User1487175000 posted

    I have download a example of PDF created from this link http://www.aspsnippets.com/Articles/Export-GridView-To-WordExcelPDFCSV-in-ASP.Net.aspx

    and its working perfect just loose the gridview formating. But atleast creating the PDF file and also its not master pages example, Same code in my origional page. 

    Here is ASPX

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CSharp.aspx.cs"   Inherits="CSharp" %>
    
    <!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>GridView Export</title>
        <link href="Style/Gridview.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
    <asp:GridView ID="GridView1" runat="server" 
            AutoGenerateColumns = "true" CssClass="mGrid"
            >
        </asp:GridView>
        </div>
            <br />
            <asp:Button ID="btnExportWord" runat="server" Text="ExportToWord" OnClick="btnExportWord_Click" />
            &nbsp;
            <asp:Button ID="btnExportExcel" runat="server" Text="ExportToExcel" OnClick="btnExportExcel_Click" />
            &nbsp;
            <asp:Button ID="btnExportPDF" runat="server" Text="ExportToPDF" OnClick="btnExportPDF_Click" />
             &nbsp;
            <asp:Button ID="Button1" runat="server" Text="ExportToCSV" OnClick="btnExportCSV_Click" />
        </form>
    </body>
    </html>
    

    Code behind

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    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 System.Data.SqlClient;
    using System.IO;
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using iTextSharp.text.html;
    using iTextSharp.text.html.simpleparser;
    using System.Text;
    
    public partial class CSharp : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string strQuery = "SP_SearchBookingByDates '2013-04-01','2013-04-30'";
            SqlCommand cmd = new SqlCommand(strQuery);
            DataTable dt = GetData(cmd);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        private DataTable GetData(SqlCommand cmd)
        {
            DataTable dt = new DataTable();
            String strConnString = "Data Source=EV2C41381794C3;User ID=sa;Password = Shahid786;Initial Catalog=7A";
            SqlConnection con = new SqlConnection(strConnString);
            SqlDataAdapter sda = new SqlDataAdapter();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            try
            {
                con.Open();
                sda.SelectCommand = cmd;
                sda.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
                sda.Dispose();
                con.Dispose();
            }
        }
       
    
        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }
        protected void OnPaging(object sender, GridViewPageEventArgs  e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            GridView1.DataBind();  
        }
    
        protected void btnExportWord_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.doc");
            Response.Charset = "";
            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 btnExportExcel_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(); 
    
            //Change the Header Row back to white color
            GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
    
            //Apply style to Individual Cells
            GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
            GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
            GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
            GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");   
    
            for (int i = 0; i < GridView1.Rows.Count;i++ )
            {
                GridViewRow row = GridView1.Rows[i];
    
                //Change Color back to white
                row.BackColor = System.Drawing.Color.White;
    
                //Apply text style to each Row
                row.Attributes.Add("class", "textmode");
    
                //Apply style to Individual Cells of Alternating Row
                if (i % 2 != 0)
                {
                    row.Cells[0].Style.Add("background-color", "#C2D69B");
                    row.Cells[1].Style.Add("background-color", "#C2D69B");
                    row.Cells[2].Style.Add("background-color", "#C2D69B");
                    row.Cells[3].Style.Add("background-color", "#C2D69B");   
                }
            }
            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 btnExportPDF_Click(object sender, EventArgs e)
        {
            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();  
        }
        protected void btnExportCSV_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv");
            Response.Charset = "";
            Response.ContentType = "application/text";
    
            GridView1.AllowPaging = false;
            GridView1.DataBind(); 
    
            StringBuilder sb = new StringBuilder();
            for (int k = 0; k < GridView1.Columns.Count; k++)
            {
                //add separator
                sb.Append(GridView1.Columns[k].HeaderText + ',');
            }
            //append new line
            sb.Append("\r\n");
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                for (int k = 0; k < GridView1.Columns.Count; k++)
                {
                    //add separator
                    sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
                }
                //append new line
                sb.Append("\r\n");
            }
            Response.Output.Write(sb.ToString());
            Response.Flush();
            Response.End();
        }
    }
    




    Saturday, April 27, 2013 9:07 AM
  • User-80018064 posted

    Hi,

    Your advice was helpful for me simple table easily convert in PDF format, but if i am using image in my webpage than i am getting error,than what will be the solution.

    Thanks in advance

    Tuesday, September 19, 2017 7:28 AM