Displaying a PDF on a website - asp.net

I require some assistance, I have a pdf file that is located on a ftp location.
What i want to do, is on a button click i want to retrieve the pdf file and display it on a new tab.
Please assist on how to accomplish this task.
Thanks in advance.

One approach would be to make a web request to download the file and then pass the download stream along to the ASP.NET response stream. I haven't compiled or executed this code, but it might look something like this:
WebRequest request = HttpWebRequest.Create("ftp://ftp.yoursite.com/yourfile.pdf");
request.Credentials = new NetworkCredential("ftpuser","ftppassword");
// Get the response
WebResponse response = request.GetResponse();
StreamReader responseStream = new StreamReader(response.GetResponseStream());
// Send the response directly to output
Response.ContentEncoding = responseStream.CurrentEncoding;
Response.ContentType = "application/pdf";
Response.Write(responseStream.ReadToEnd());
Response.End();

Just use the HTML anchor tag ("a" tag). In the href attribute put the FTP address of the PDF file (eg. ftp://example.com/file.pdf). To open in a new window you should also specify a target attribute with the value "_blank".
Example:
<a href='ftp://example.com/file.pdf' target='_blank'>Click here to open the PDF file</a>

Related

ASP.NET how to return pdf file as response without changing response header

I want to return a pdf file as response to some button click.
I succeeded to send the pdf file, but when i try to save it via the browser, it won't let me save it as a .pdf file (but as .aspx file)
here's the code:
Dim myWebClient As WebClient = New WebClient()
Dim myDataBuffer As Byte() = myWebClient.DownloadData(LocalImageURL) ' LocalImageURL is some path to a pdf file
Response.ContentType = "application/pdf"
Response.BinaryWrite(myDataBuffer)
Response.Flush()
Response.End()
if I am adding also the following line before writing the byte array:
Response.AddHeader("content-disposition", "attachment;filename=report.pdf")
it does the trick, but the problem is that the page remains stuck (looks like it still waits for server response to come)
This has been asked and answered before. Details are at the link below:
asp.net VB.net file download handler not work properly

using web sites to transfer xml

How do I setup a scenario where one website hosted at X publishes a URL that when browsed to will return purely XML.
A web page elsewhere is going to hit this URL, load the XML into objects.
So I want a url like http://www.xml.com/document.aspx?id=1
Another site will use webresponse and webrequest objects to get the response from the above page, I want the response to be good XML so I can just use the XML to populate objects.
I did get something working but the response contained all the HTML required to render the page and I actually just want XML as the response.
Probably the best way to this is with a HttpHandler/ASHX file, but if you want to do it with a page it's perfectly possible. The two key points are:
Use an empty page. All you want in the markup for your ASPX is the
<% Page ... %> directive.
Set the ContentType of the Response stream
to XML - Response.ContentType = "text/xml"
How you generate the XML itself is up to you, but if the XML represents an object graph, you can use an XmlSerializer (from the System.Xml.Serialization namespace) to write the XML directly to the Response stream for you e.g.
using System.Xml.Serialization;
// New up a serialiser, passing in the System.Type we want to serialize
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
// Set the ContentType
Response.ContentType = "text/xml";
// Serialise the object to XML and pass it to the Response stream
// to be returned to the client
serialzer.Serialize(Response.Output, MyObject);
If you already have the XML, then once you've set the ContentType, you just need to write it to the Response stream and then end and flush the stream.
// Set the ContentType
Response.ContentType = "text/xml";
Response.Write(myXmlString);
Response.Flush();
Response.End();

PDF from content of asp.net page

I'm trying to create a pdf of the content on a page ("returnsPage.aspx?id="returnId) and allow the user to download this directly when clicking the button.
However in my onClick method I have the following code:
lnkLoadPDF.CommandArgument = "/returns/returnsPage.aspx?id="+returnId.ToString();
string virtualPath = lnkLoadPDF.CommandArgument;
string fileName = System.IO.Path.GetFileName(virtualPath);
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.WriteFile(virtualPath);
Response.ContentType = "";
Response.End();
Response.Redirect("/returns/returnsPage.aspx?id="+returnId);
which returns this error:
'/returns/returnsPage.aspx?id=23' is not a valid virtual path.
Can anyone please tell me what I'm doing wrong?
Thanks!
In order to turn a webpage into a pdf, you must convert it to pdf on the server. In order to do that, you must have a program on the server that can do that for you.
I've tried a variety of webpage-to-pdf converters and one of the better ones is a free, open source program called wkhtmltopdf.
After you create the pdf, you can either redirect the user to the newly created pdf (discouraged), or prompt them to download it with a savefile dialog.
If you get stuck, just search for wkhtmltopdf on stackoverflow or post another question.
You can't send a file to the client and redirect him to a new location during the same request. You also can't create a PDF from a webpage without some kind of component that converts the HTML into a PDF, it's (quite a bit) more tricky that what I think you're trying to attempt.
As for your exception, are you sure returnsPage.aspx exists? :)

How to designate the name of a file that a user downloads via an ASHX downloader?

This is my first time writing code that allows a user to download a file uploaded by another user.
I've written an ASHX file, download.ashx, with code that looks like this:
s = context.Request.QueryString.ToString();
byte[] buffer = new ReplacementTicketFileIO().GetSpecifiedFile(s);
context.Response.BinaryWrite(buffer);
context.Response.Flush();
context.Response.End();
When a user clicks on a link to download.ashx with the appropriate querystring, the file is downloaded, but the browser wants to display the content in the browser window. If the user right-clicks on the link, he can download the file, but the name of the file defaults to download.ashx.
I would like to accomplish two things:
1) I would like to be able to specify the default name of the file downloaded on the user's device based on the querystring.
For instance, if the user clicks on download.ashx?linkedfile=car.pdf, I would like for the browser to default to car.pdf for the name of this file.
2) I would like for the browser to default to saving the link, as opposed to opening the link in the browser window.
Is it reasonable for me to want to do this, or is there a better way to download files? Please let me know.
Set the Content-Disposition HTTP header. E.g.
Content-Disposition: attachment; filename=hello.jpg
You can do that in C# using:
Response.AddHeader("Content-Disposition", "attachment; filename=hello.jpg");
Here is something I have for excel files and I believe it forces a download rather than a new window. There is a page property for QueryString. You would just need to capture the QueryString and use it in this code as well as determining the content type. The String.Format will give you clean code.
private string _ExcelFilename
{
get
{
return (Request.QueryString["xls"] != null) ? Request.QueryString"xls"] : "bis";
}
}
Page.Response.Clear();
Page.EnableViewState = false;
Page.Response.Clear();
Page.Response.ContentType = "application/vnd.ms-excel";
Page.Response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}_{1}.xls", _ExcelFilename, DateTime.Now.ToString("yyyyMMdd")));
Page.Response.Write(excel);
Page.Response.Flush();
Page.Response.End();

Response.WriteFile

There is one URL with specific syntax to download a file.
http://www.hddownloader.com/?url=http://www.youtube.com/watch?v=N-HbxNtY1g8&feature=featured&dldtype=128
The user enters the file name in the textbox and presses the download button.In the click event the Response.WriteFile is called which sends the file to the client.
Now I want to create another website with a page, in which the user enters the filename and presses the download button to download that file.
Now I want to utilise the first URL for that. I dont want to use Response.Redirect, because by that way, the user will come to know that I am using mydownload.com.
How can I acheieve that.
One way is : When we download something from microsoft's website, a small popup window(with no close, maximise and minimise button) and then the save dialog box appears.
How to achieve this or another to achieve the same ?
You could first download the file from the remote location on your server using WebClient.DownloadFile:
using (var client = new WebClient())
{
client.DownloadFile("http://remotedomain.com/somefile.pdf", "somefile.pdf");
Response.WriteFile("somefile.pdf");
}
or if you don't want to save the file temporary to the disk you could use the DownloadData method and then stream the buffer into the response.
UPDATE:
Example with the second method:
using (var client = new WebClient())
{
var buffer = client.DownloadData("http://remotedomain.com/somefile.pdf");
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment;filename=somefile.pdf");
Response.Clear();
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.Flush();
}

Resources