The document has no pages
I am using the below code to export gridview to PDF
form1.Controls.Clear();
form1.Controls.Add(GridView1);
StringWriter sw = new StringWr开发者_C百科iter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
string html = "<html><body>" + sw.ToString() + "</body></html>";
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
document.AddAuthor("Ram");
document.AddSubject("Export To pdf");
document.Open();
string tempFile = Path.GetTempFileName();
using (StreamWriter tempwriter = new StreamWriter(tempFile, false))
{
tempwriter.Write(html);
}
HtmlParser.Parse(document, tempFile);
document.Close();
writer.Close();
File.Delete(tempFile);
writer = null;
document = null;
Response.End();
I have checked that grridview has 10 rows by putting breakpoint. But I am getting error at
document.Close();
that
The document has no pages.
Any suggestion how to fix it?
1) Setting a breakpoint to see that your grid view has 10 rows helps, but only checks part of the problem. You also need to check the contents of tempFile
. That's what iText is actually working with. If it's empty, you'll sill get the "doc has no pages" exception.
2.1) HtmlParser no longer exists within iText. Having said that, I just dug up this code sample via google:
public static void main(String[] args) throws Exception {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("html1.pdf"));
HtmlParser.parse(document, "example.html");
}
No opens or closes, just a call to HtmlParser. It's quite possible that HtmlParser checks to see if the document is already open, and won't proceed if it is... that would explain the behavior you're seeing.
2.2) The "correct" way to convert HTML these days goes something like this:
String html = readHtml();
List<Element> objects = HTMLWorker.parseToList(new StringReader(html), null);
for (Element element : objects)
document.add(element);
I had same issue and the below suggestion help and my issue is solved
Document has no pages means your GridView data is lost when you export. Hence in the Export button event rebind the GridView with data from database
https://www.aspforums.net/Threads/264988/Export-GridView-to-PDF-Error-Document-has-no-pages/
精彩评论