2013-07-05 134 views
2

我在輸出流上生成,保存和寫入PDF。關閉文檔時「文檔沒有頁面」錯誤

在輸出流上寫入時,出現The document has no page錯誤。

什麼問題?

string contents; 
string fileName = "aaa.pdf"; 
Response.ContentType = "application/pdf"; 
Response.AddHeader("content-disposition", "attachment; filename=" + fileName); 
Response.Cache.SetCacheability(HttpCacheability.NoCache); 
StringWriter sw = new StringWriter(); 
HtmlTextWriter hw = new HtmlTextWriter(sw); 
hw.AddStyleAttribute("font-size","11px"); 
abs.RenderControl(hw); 
string path = Server.MapPath("../Images/a.png"); 
contents = sw.ToString(); 
contents = contents.Replace("../Images/a.png", path); 
sw.Close(); 
hw.Close();  
StringReader sr = new StringReader(contents); 

System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/pdf/") + fileName, FileMode.Create); 
Document pdfDoc = new Document(PageSize.A4, 30,5,35,5); 
Document cpdfDoc = new Document(PageSize.A4, 30, 5, 35, 5); 

pdfDoc.PageCount = 2; 
cpdfDoc.PageCount = 2; 
HTMLWorker htmlparser = new HTMLWorker(pdfDoc); 
PdfWriter.GetInstance(pdfDoc,fs); 
pdfDoc.Open(); 
htmlparser.Parse(sr); 
pdfDoc.Close(); 
fs.Close(); 
HTMLWorker htmlparser2 = new HTMLWorker(cpdfDoc);    
PdfWriter.GetInstance(cpdfDoc, Response.OutputStream); 
cpdfDoc.Open(); 
htmlparser2.Parse(sr); 

cpdfDoc.Close();  

Response.Write(cpdfDoc); 
Response.Flush(); 
Response.End(); 

保存沒有問題。我在這條線上收到錯誤cpdfDoc.Close();

+0

你得到一個「文檔有沒有頁面」異常時沒有內容被添加到文檔實例。在你的HTML中可能沒有任何東西可以被解析。 –

+0

但存儲的pdf包含數據.. – balaji

+0

但內容流爲空。 –

回答

1

使用此代碼並設置您的pdf位置。和圖像路徑。 其工作。

string contents = "hi"; 
     string fileName = "aaa.pdf"; 
     Response.ContentType = "application/pdf"; 
     Response.AddHeader("content-disposition", "attachment; filename=" + fileName); 
     Response.Cache.SetCacheability(HttpCacheability.NoCache); 
     StringWriter sw = new StringWriter(); 
     HtmlTextWriter hw = new HtmlTextWriter(sw); 
     hw.AddStyleAttribute("font-size", "11px"); 

     string path = Server.MapPath("~/Images/a.png"); 

     contents = contents.Replace("~/Images/a.png", path); 
     sw.Close(); 
     hw.Close(); 
     StringReader sr = new StringReader(contents); 

     System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/") + DateTime.Now.Ticks, FileMode.Create); 
     Document pdfDoc = new Document(PageSize.A4, 30, 5, 35, 5); 
     Document cpdfDoc = new Document(PageSize.A4, 30, 5, 35, 5); 

     pdfDoc.PageCount = 2; 
     cpdfDoc.PageCount = 2; 
     HTMLWorker htmlparser = new HTMLWorker(pdfDoc); 
     PdfWriter.GetInstance(pdfDoc, fs); 
     pdfDoc.Open(); 
     htmlparser.Parse(sr); 
     pdfDoc.Close(); 
     fs.Close(); 
     HTMLWorker htmlparser2 = new HTMLWorker(cpdfDoc); 
     PdfWriter.GetInstance(cpdfDoc, Response.OutputStream); 
     cpdfDoc.Open(); 
     htmlparser2.Parse(sr); 

不使用此行

contents = sw.ToString(); 
+0

您已刪除HtmlTextWriter的目的。我從html控件獲取內容 – balaji

+0

'abs'是什麼?首先告訴我,而不是我給解決方案。 –

+0

'abs'是包含pdf數據的div的id。 – balaji