how to save xml file from html page - c#

I have requirement to save an XML document which is displayed in a HTML page.
The scenario is like this: I am sending search request to the server and in return I am getting xml file but displayed in html page. What I want is to save client-side the xml file displayed inside the html form, using javascript, asp.net (C#).
Please see this link (server return file like this)
http://www.w3schools.com/dom/books.xml

You need to save the stream from your request into a xmldoc.
Should be really straight forward.
Have a look here:
http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.save(v=vs.100).aspx
Also, here there is a microsoft article about it:
http://support.microsoft.com/kb/307643

The sent file should have a HTTP header indicating it's meant to be saved, not shown.
Do it this way:
context.Response.ContentType = "application/force-download";

Assuming you are writing a client app to consume this file
using System.Net;
new WebClient().DownloadFile("http://www.w3schools.com/dom/books.xml", #"c:\books.xml");

As Rutesh said you can't go with javascript. Save it on the server with C#.NET and then access it from server. Secondly, the page you are talking about is not an html page its an xml file. I hope you know how to build an asp.net page, if yes then use this:
XmlDocument xdoc = new XmlDocument();
xdoc.Load("http://www.w3schools.com/dom/books.xml");
xdoc.Save("myfilename.xml");
Happy coding!

sourceResponse.ContentType = "application/octet-stream";
byte[] responseContent = "XML File content"
sourceResponse.AddHeader("content-disposition", String.Format("attachment; filename={0}.xml", "yourFileName"));
sourceResponse.BinaryWrite(responseContent);
sourceResponse.End();

Related

How to save string content to a local file

I am developing an application which is showing web pages through a web browser control.
When I click the save button, the web page with images should be stored in local storage. It should be save in .html format.
I have the following code:
WebRequest request = WebRequest.Create(txtURL.Text);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
Now string html contains the webpage content. I need to save this into D:\Cache\
How do i save the html contents to disk?
You can use this code to write your HTML string to a file:
var path= #"D:\Cache\myfile.html";
File.WriteAllText(path, html);
Further refinement: Extract the filename from your (textual) URL.
Update:
See Get file name from URI string in C# for details. The idea is:
var uri = new Uri(txtUrl.Text);
var filename = uri.IsFile
? System.IO.Path.GetFileName(uri.LocalPath)
: "unknown-file.html";
you have to write below code on save button
File.WriteAllText(path, browser.Document.Body.Parent.OuterHtml, Encoding.GetEncoding(browser.Document.Encoding));
Now the 'Body.parent' must save whole the page instead of just saving only part.
check it.
There is nothing built-in to the .NET Framework as far I know.
So my approach would be like below:
Use System.NET.HttpWebRequest to get the main HTML document as a
string or stream (easy). (Which you have done already)
Load this into a HTMLAgilityPack document where you can now easily
query the document to get lists of all image elements, stylesheet
links, etc.
Then make a separate web request for each of these files and save
them to a subdirectory.
Finally update all relevent links in the main page to point to the
items in the subdirectory.

Creating a hyperlink to a physical path on the local PC, to files not part of the web site

I have some files in a folder on the harddrive, like C:\ExtraContent\ that has some PDF files. This folder is not part of the website. I was able to successfully upload a PDF to this folder using the default ASP.NET FileUploader, no problem.
What I would like to do is, create a hyperlink that links to a PDF in that folder C:\ExtraContent\somePDF.pdf
I am able to get close using a Button with the following code:
protected void Button1_Click(object sender, EventArgs e)
{
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData("C:\ExtraContent\somePDF.pdf");
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
The above works in terms of opening the file. But I can't get this to work with an ASP.NET HyperLink.
The reason I want to use a HyperLink is so that the user can choose to right-click and Save As, to download a copy. If HyperLink controls can only link to relative paths, what can I do to get my desired result?
Note: making the files I'm trying to access part of the site is not practical for us.
Basically allowing access to the folder the way you describe is a real security risk (because it requires hacking at the permissions), isn't trivial and in general should be avoided. The way that you achieve your desired behaviour is something along these lines.
Firstly create a blank aspx or ashx page.
Secondly, either in the Page_Load or ProcessRequest you want to use code along the following lines
string filePath = "c:\\Documents\\Stuff\\";
string fileName = "myPath.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(filePath + fileName);
context.Response.Clear();
context.Response.ContentType = "application/pdf";
context.Response.Cache.SetCacheability(HttpCacheability.Private);
context.Response.Expires = -1;
context.Response.Buffer = true;
context.Response.AddHeader("Content-Disposition", string.Format("{0};FileName=\"{1}\"", "attachment", fileName));
context.Response.BinaryWrite(bytes);
context.Response.End();
I haven't tested this and taken it from my head so it might need some tweeks but the above code should get you on the right track to cause the persons browser to begin downloading the file you provide.
EDIT: I just realized (after rereading your question) your problem was slightly different to what I thought, to get your issue resolved simply make the hyperlink button you are using link to a page that can process the request as described above. IE: An ashx or aspx page
You need to create a hyperlink to a page that acts as a 'proxy' so that the page will return a response that contains the file stream.
You cannot create a link to a file that is not prt of your site.

ASP.NET web page to PDF

I looking for the easiest way to export the currently viewed asp.net web page to a PDF document using iTextSharp - it can be either a screenshot of it or passing in the url to generate the document. Sample code would be greatly appreciated. Many thanks in advance!
On a past project, we used Supergoo ABCPDF
to do something like you need to and it worked quite well. You basicly feed it an url and it process the HTML page into a PDF.
On the downside, it's a licensed software with costs associated to it and we had some performance issues when exporting a lot of large PDF at the same time.
Hope this helps !
Adding to what Darin said in his comment.
You can try using wkhtmltopdf to generate PDF files. It takes URL as input. This is what I have used for my SO application so2pdf.
It is not that easy (or i think so), i had same problem and i had to write code to generate exact page in pdf. It depends of page and used styles etc. So i create drawing of each element.
For some project i used Winnovative HTML to PDF converter but it is not free.
Give a try with PDFSharp (to generate PDF files at runtime), and it's Open Source library :
http://pdfsharp.com/PDFsharp/index.php?option=com_content&task=view&id=27&Itemid=1
Alternative solution : http://www.bratched.com/en/component/content/article/76-how-to-convert-xhtml-to-pdf-in-c.html
There is an example Convert the Current HTML Page to PDF on WInnovative website which does exactly this. The relevant C# code to convert the currently viewed asp.net web page to a PDF document is:
// Controls if the current HTML page will be rendered to PDF or as a normal page
bool convertToPdf = false;
protected void convertToPdfButton_Click(object sender, EventArgs e)
{
// The current ASP.NET page will be rendered to PDF when its Render method will be called by framework
convertToPdf = true;
}
protected override void Render(HtmlTextWriter writer)
{
if (convertToPdf)
{
// Get the current page HTML string by rendering into a TextWriter object
TextWriter outTextWriter = new StringWriter();
HtmlTextWriter outHtmlTextWriter = new HtmlTextWriter(outTextWriter);
base.Render(outHtmlTextWriter);
// Obtain the current page HTML string
string currentPageHtmlString = outTextWriter.ToString();
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set license key received after purchase to use the converter in licensed mode
// Leave it not set to use the converter in demo mode
htmlToPdfConverter.LicenseKey = "fvDh8eDx4fHg4P/h8eLg/+Dj/+jo6Og=";
// Use the current page URL as base URL
string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri;
// Convert the current page HTML string a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(currentPageHtmlString, baseUrl);
// Send the PDF as response to browser
// Set response content type
Response.AddHeader("Content-Type", "application/pdf");
// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Convert_Current_Page.pdf; size={0}", outPdfBuffer.Length.ToString()));
// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);
// End the HTTP response and stop the current page processing
Response.End();
}
else
{
base.Render(writer);
}
}

C# WebClient only downloads partial html

I am working on some scraping app, i wanted to try to get it to work but ran into a problem. I have replaced the original scraping destination in the below code with googles webpage, just for testing. It seems that my download doesnt get everything, i note that the body and the html tags are missing their close tags. How do i get it to download everything? Whats wrong with my sample code:
string filename = "test.html";
WebClient client = new WebClient();
string searchTerm = HttpUtility.UrlEncode(textBox2.Text);
client.QueryString.Add("q", searchTerm);
client.QueryString.Add("hl", "en");
string data = client.DownloadString("http://www.google.com/search");
StreamWriter writer = new StreamWriter(filename, false, Encoding.Unicode);
writer.Write(data);
writer.Flush();
writer.Close();
Google's web pages are now in HTML 5, meaning the BODY and HTML tags can be self-closed - which is why Google omits them (believe it or not, it saves them bandwidth.)
See this article.
You can write HTML5 in either "HTML/SGML" mode (which allows the omitting of closing tags like HTML did prior to XHTML) or in "XHTML" which follows the rules of XML, requiring all tags to be closed.
Which the browser chooses to parse the page depends on whether you send a Content-type header of text/html for HTML/SGML syntax or application/xhtml+xml for XHTML syntax. (Source: HTML5 syntax - HTML vs XHTML)
...Google's page doesn't have the closing tags for <body> and <html>. Talk about crazy optimization...
http://www.google.com/search doesn't have closing tags.

Generate PDF from ASP.NET from raw HTML/CSS content?

I'm sending emails that have invoices attached as PDFs. I'm already - elsewhere in the application - creating the invoices in an .aspx page. I'd like to use Server.Execute to return the output HTML and generate a PDF from that. Otherwise, I'd have to use a reporting tool to "draw" the invoice on a PDF. That blows for lots of reasons, not the least of which is that I'd have to update both the .aspx page and the report for every minor change. What to do...
There is no way to generate a PDF from an HTML string directly within .NET, but there are number of third party controls that work well.
I've had success with this one: http://www.html-to-pdf.net
and this: http://www.htmltopdfasp.net
The important questions to ask are:
Does it render correctly as compared to the 3 major browsers: IE, FF and Safari/Chrome?
Does it handle CSS fine?
Does the control have it's own rendering engine? If so, bounce it. You don't want to trust a home grown rendering engine - the browsers have a hard enough problem getting everything pixel perfect.
What dependencies does the third party control require? The fewer, the better.
There are a few others but they deal with ActiveX displays and such.
We use a product called ABCPDF for this and it works fantastic.
http://www.websupergoo.com/abcpdf-1.htm
This sounds like a job for Prince. It can take HTML and CSS and generate a PDF, which you can then present to your users. It supports CSS3 better than most web browsers (staff include HÃ¥kon Wium Lie, the inventor of CSS).
See the samples, especially the ones for Wikipedia pages, for the beautiful output it can generate. There's also an interesting Google Tech Talk with the authors.
Edit: There is a .NET wrapper available.
wkhtmltopdf is a free and cool exe to generate pdf from html. Its written in c++. But nReco htmltopdf is a wrapper dotnet library for this awesome tool. I implemented using this dotnet library and it was just so good it does everything by its own you just need to give html as a data source.
/// <summary>
/// Converts html into PDF using nReco dll and wkhtmltopdf.exe.
/// </summary>
private byte[] ConvertHtmlToPDF()
{
HtmlToPdfConverter nRecohtmltoPdfObj = new HtmlToPdfConverter();
nRecohtmltoPdfObj.Orientation = PageOrientation.Portrait;
nRecohtmltoPdfObj.PageFooterHtml = CreatePDFFooter();
nRecohtmltoPdfObj.CustomWkHtmlArgs = "--margin-top 35 --header-spacing 0 --margin-left 0 --margin-right 0";
return nRecohtmltoPdfObj.GeneratePdf(CreatePDFScript() + ShowHtml() + "</body></html>");
}
The above function is an excerpt from the below link post which explains it in detail.
HTML to PDF in ASP.Net
The initial question is about converting another aspx page containing an invoice to a PDF document. The invoice is probably using some session data and the user suggests to use Server.Execute() to obtain the invoice page HTML code and then to convert that code to PDF. Converting the invoice page URL directly is not possible because a new session would be created during conversion and the session data would be lost.
This is actually a good technique to preserve session data during conversion which is applied in Convert a HTML Page to PDF in Same Session ASP.NET Demo of the EvoPdf library. The complete C# code to get the HTML string rendered by the invoice page and to convert that string to PDF is:
// Execute the invoice page and get the HTML string rendered by this page
TextWriter outTextWriter = new StringWriter();
Server.Execute("Invoice.aspx", outTextWriter);
string htmlStringToConvert = outTextWriter.ToString();
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Use the current page URL as base URL
string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri;
// Convert the page HTML string to a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlStringToConvert, baseUrl);
// Send the PDF as response to browser
// Set response content type
Response.AddHeader("Content-Type", "application/pdf");
// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Convert_Page_in_Same_Session.pdf; size={0}", outPdfBuffer.Length.ToString()));
// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);
// End the HTTP response and stop the current page processing
Response.End();
As long as you can make sure to use proper XHTML, you could also use a product like Alt-Soft's Xml2PDF to convert XML (XHTML) into PDF by means of XSLT/XSL-FO.
It takes a bit of a learning curve to master, but it works very well once you've "got" it!
Marc
Since you are producing the answer, you can use a tool like Report.NET:
http://sourceforge.net/projects/report/
I disagree with the answers that say you cannot convert directly from output to PDF, however, as you can "re-call" the page and get the HTML as a stream and convert it. I am not sure what tool you would want to use to do this, however. In other words, it is possible, but I am not sure it is worth it. The PDF creation libs, like Report.NET, even though they force reusing some logic and no automagic converrsion, it is easier.
I have not tried this component, but I have heard good things about it from those who have. The model is more like HTML, but I am not sure you can simply send a rendered ASPX to it to create PDF:
http://www.websupergoo.com/abcpdf-8.htm
If you try to find some html to pdf software via GOOGLE you'll get a pile of this stuff.
There are about 10 leaders but most of them use IE dlls in background mode.
Just couple of them use their own parsing engine.
Please try PDF Duo .NET component in your ASP.NET project if you wish to create a PDF programaticaly.
It is light component for a cool generating of PDF invoces, reports e.g.
I'd go a different route. Assuming you are using SQL Server, use SSRS and generate the PDF that way.
A possible minimal solution to use Server.Execute() to obtain the HTML of the invoice page and convert that code to a PDF using winnovative html to pdf api for .net is:
TextWriter outTextWriter = new StringWriter();
Server.Execute("Invoice.aspx", outTextWriter);
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
byte[] pdfBytes = htmlToPdfConverter.ConvertHtml(outTextWriter.ToString(),
httpContext.Current.Request.Url.AbsoluteUri);
You can use PDFSharp or iTextSharp to convert html to pdf. PDFSharp is not free.

Categories