Click here to Skip to main content
15,904,817 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to save a html as PDF. I am getting this error:Data at the root level is invalid. Line 1, position 1, html contains textboxes,lables,images
my code
C#
string confirmValue = Request.Form["confirm_value"];
           if (confirmValue == "Yes")
           {

               string sPathToWritePdfTo = @"C:\new_pdf_name.pdf";


               System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();
               sbHtml.Append("Contractor1.aspx");




               using (System.IO.Stream stream = new System.IO.FileStream(sPathToWritePdfTo, System.IO.FileMode.OpenOrCreate))
               {

                   Pdfizer.HtmlToPdfConverter htmlToPdf = new Pdfizer.HtmlToPdfConverter();

                   htmlToPdf.Open(stream);

                   htmlToPdf.Run(sbHtml.ToString());

                   htmlToPdf.AddChapter("Mobily");

                   htmlToPdf.Close();
               }


               HttpContext.Current.Response.Clear();

               HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "mobily.pdf"));

               HttpContext.Current.Response.ContentType = "application/pdf";



               HttpContext.Current.Response.WriteFile(sPathToWritePdfTo);

               HttpContext.Current.Response.End();

           }
Posted
Updated 25-Dec-14 3:11am
v6
Comments
KaushalJB 25-Dec-14 8:54am    
At which line does it throws error ? Debug with F11 and check..
Atif Ur Rahman 25-Dec-14 9:09am    
htmlToPdf.Run(sbHtml.ToString());

at this line error occurs

1 solution

I would suggest to use http://wkhtmltopdf.org/[^].

Refer - C# – Convert HTML to PDF using Pechkin (WkHtmlToPdf)[^], which uses the .NET Wrapper Class for wkhtmltopdf.
 
Share this answer
 
Comments
Atif Ur Rahman 25-Dec-14 9:23am    
can this code converts images,textboxes,lables also
Have you tried?
Atif Ur Rahman 26-Dec-14 5:21am    
getting a error

var pdf = pechkin.Convert(new ObjectConfig()
.SetLoadImages(true).SetZoomFactor(1.5)
.SetPrintBackground(true)
.SetScreenMediaType(true)
.SetCreateExternalLinks(true), html);//error


the Name html does not exist in the current context
html is the whole html string, you want to convert. So, declare a string variable "html" and put your html contents in that.
Atif Ur Rahman 26-Dec-14 6:55am    
can u please tell how to convert my html page to string

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