2011-03-14 71 views
0

我使用下面的代碼的GridView導出爲PDF的文檔沒有頁

form1.Controls.Clear(); 
form1.Controls.Add(GridView1); 
StringWriter sw = new StringWriter(); 
HtmlTextWriter htw = new HtmlTextWriter(sw); 
GridView1.RenderControl(htw); 
string html = "&lt;html><body>" + sw.ToString() + "&lt;/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(); 

我已經檢查了grridview有10行通過把斷點。但我在

document.Close(); 

該文件有沒有網頁出現錯誤。

任何建議如何解決它?

+0

請幫助我 – Chris 2011-03-14 11:51:39

+1

那麼究竟是什麼問題呢? – 2011-03-22 15:41:40

回答

0

1)設置斷點來查看網格視圖有10行有幫助,但只檢查部分問題。您還需要檢查tempFile的內容。這就是iText實際正在處理的內容。如果它是空的,你會得到「文檔沒有頁面」的例外。

2.1)HtmlParser不再存在於iText中。說了這麼多,我只是通過谷歌挖了此代碼示例:

public static void main(String[] args) throws Exception { 
    Document document = new Document(); 
    PdfWriter.getInstance(document, new FileOutputStream("html1.pdf")); 
    HtmlParser.parse(document, "example.html"); 
} 

沒有打開或關閉,只是爲了HTMLParser的一個電話。 HtmlParser很可能會檢查文檔是否已經打開,如果它是......這將解釋您所看到的行爲,則不會繼續。

2.2)的「正確」的方式轉換成HTML,這些天是這樣的:

String html = readHtml(); 
List<Element> objects = HTMLWorker.parseToList(new StringReader(html), null); 

for (Element element : objects) 
    document.add(element);