Click here to Skip to main content
15,916,846 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi

i have saved a web browser in pdf by using below code in a folder ...... pdf is saved in folder But pdf wil not open so please help me to solve

C#
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);

StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
this.Page.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
MemoryStream ms = new MemoryStream();
PdfWriter.GetInstance(pdfDoc, ms);
pdfDoc.Open();
htmlparser.Parse(sr);

FileStream file = new FileStream(Server.MapPath("~/Files/")+"Test.PDF", FileMode.Create, System.IO.FileAccess.Write);
byte[] bytes = new byte[ms.Length];
ms.Read(bytes, 0, (int)ms.Length);
file.Write(bytes, 0, bytes.Length);
file.Close();
pdfDoc.Close();
ms.Close(); 


Error is

could not open the TEST.PDF because it is either not a supported file type
Posted
Updated 20-Nov-14 8:10am
v2

1 solution

Try moving to the beginning of the MemoryStream before trying to read it:
C#
ms.Seek(0L, SeekOrigin.Begin);
ms.Read(bytes, 0, (int)ms.Length);
file.Write(bytes, 0, bytes.Length);

Alternatively, use the ToArray method:
C#
byte[] bytes = ms.ToArray();
file.Write(bytes, 0, bytes.Length);

Or use the CopyTo method:
C#
ms.CopyTo(file);
 
Share this answer
 
Comments
George Jonsson 20-Nov-14 14:12pm    
Or
ms.Position = 0;
vakativamsi 21-Nov-14 0:53am    
Thank you for your reply .....


But when i am using above code , i am getting same problem ...so please tell me one more option for that

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900