Download pdf programmatically - c#

How can I download a PDF and store to disk using vb.NET or C#?
The URL (of the PDF) has some rediection going on before the final PDF is reached.
I tried the below but the PDF seems corrupted when I attempt to open locally,
Dim PdfFile As FileStream = File.OpenWrite(saveTo)
Dim PdfStream As MemoryStream = GetFileStream(pdfURL)
PdfStream.WriteTo(PdfFile)
PdfStream.Flush()
PdfStream.Close()
PdfFile.Flush()
PdfFile.Close()

You can try to use the WebClient (System.Net namespace) class to do this which will avoid any stream work on your side.
The following C# code grabs an IRS form and saves it to C:\Temp.pdf.
using(WebClient client = new WebClient())
{
client.DownloadFile("http://www.irs.gov/pub/irs-pdf/fw4.pdf", #"C:\Temp.pdf");
}

You can also try the following code sample to download pdf files
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=Test_PDF.pdf");
Response.TransmitFile(Server.MapPath("~/Files/Test_PDF.pdf"));
Response.End();

How might you be able to use client.downloadfile when the URL is pointing a "showdocument.aspx" page.
Example:
https://gaming.nv.gov/modules/showdocument.aspx?documentid=246

Related

PDF won't display in browser window

I am using a handler to get and display a PDF in the browser window using the code below:
byte[] byt = RetrieveDocument(int.Parse(context.Request.Params["id"]), context.Request.Params["title"]);
string file = WriteDocumentFilePDF(byt);
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-length", byt.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=programdetails.pdf");
HttpContext.Current.Response.BinaryWrite(byt);
HttpContext.Current.Response.End();
The function WriteDocumentFilePDF successfully writes the PDF to the temp directory. I have the above code working correctly in a different application. Am I missing something?
When debugging issues like this, I find that Fiddler is an invaluable tool; many many times it has saved me from simple mistakes. Also, this site http://www.c-sharpcorner.com/uploadfile/prathore/what-is-an-ashx-file-handler-or-web-handler/ gives an example of doing the same thing but with a GIF image. The difference between your example and his seems to be the use of Response.WriteFile() rather than the direct write to the Response using BinaryWrite().
I would perform a Response.ClearHeaders() before I set the content-type and I would remove the call to Response.End().
Does it make a difference if you pass the byte[] to memorystream first? So something like
byte[] byt = RetrieveDocument(int.Parse(context.Request.Params["id"]), context.Request.Params["title"]);
string file = WriteDocumentFilePDF(byt);
MemoryStream ms = new MemoryStream(byt);
And then add your headers
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=programdetails.pdf");
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.End();

Is it possible to open a word document from a particular location in C#

Is it possible to open a word document from a particular location in C# using:
string str2 = "Docname.doc"
Response.AppendHeader("Content-Type", "application/msword");
Response.AppendHeader("Content-disposition", "attachment; filename=" + str2);
My problem is that above code create and open a word doc but i want to open any existing doc file at any particular location.
An HTTP response can't contain a reference to a file path on the client computer, if that's what you're after then the answer is no.
If the file is on the server and you want it to open on the client, then you need to read the entire contents of the file and write those contents to the response.
You have to read the document and write it to response as a MemoryStream. I think this should work:
var fileStream = System.IO.File.ReadAllBytes(#"path/to/document.doc");
var stream = new MemoryStream(fileStream);
stream.WriteTo(Response.OutputStream);
Response.AddHeader("Content-Disposition","Attachment;filename=documentName.doc");
Response.ContentType = "application/msword";

Can I download an Excel file made from a memory stream off an ASP.NET page?

I have an ASP.NET page where a user provides an ID, and then we pull some data from the DB and put it into an Excel spreadsheet. I would like to create the Excel file in memory and then allow the user to download the file. I could create a file on the server, and then delete it afterwards, but it seems unnecessary. Depending on error handling I could potentially orphan a file with that approach, etc.
Is something like this possible? Or do I need to use a file stream?
On a side note, I'm using EPPlus as an API (quick plug for it).
You want to specify the content-type and content-dispisition headers like so - Response.ContentType = "application/vnd.ms-excel" works in IE and firefox but not in Safari, then stream your file. Once complete, call Response.End() to stop the application execution
Code Sample:
void StreamExcelFile(byte[] bytes)
{
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=name_you_file.xls");
Response.BinaryWrite(bytes);
Response.End();
}
ExcelPackage pck = new ExcelPackage();
.....
.....
.....
byte[] bfr = pck.GetAsByteArray();
Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("content-disposition", "attachment; filename=ExcelFileName.xlsx");
Response.OutputStream.Write(bfr, 0, bfr.Length);
Response.Flush();
Response.Close();
Yes, look into using an HTTP Handler to stream the file to the browser from memory.
http://msdn.microsoft.com/en-us/library/ms972953.aspx
What you're looking for is called a generic handler:
http://www.dotnetperls.com/ashx
In a nutshell, what you need to do is define the context type. Which in your case will be a xls or xlsx. Set the response, and direct the user to the handler.
They will be prompted to download the file.

itextsharp open pdf with another browser windows

basically below is the code for me to read pdf file, the output for this code below is ask client to download the pdf file and open it from client side, this is not what i want,what i want it open the pdf at another browswer windows or open in inside tag under same browser windows, but how can i make it?
var fi = new FileInfo(Server.MapPath(#"~/AIA2.pdf"));
Response.Clear();
Response.AddHeader("Content-Disposition",
String.Format("attachment; filename=\"{0}\"",
"AIA2.pdf"));
Response.AddHeader("Content-Length", fi.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(fi.FullName);
Response.End();
This is not upto the server to decide how content is handled - content disposition could be set to attachment or inline but its to the handling application to process these and i do not think any browser does that.
I can suggest a two step solution for this:
Use inline; instead of attachment
On the client side (if you have control on that ofcourse), use something like
That should do the trick!

How To: Dynamically Creating the XML file content and sending as a text file in asp.net c#

hi there i am working on an asp.net web page that first lets users to enter required values to indicated textfields and then generate a new text file according to the data given by the user.
I want to let users receive a "Result.xml" file when they click on "get file" button.
i've searched for that info, i know it must have an easy solution but by now i am out of luck (i must be tired). i tried the following code but it didnt worked:
DataSet ds = new DataSet();
ds.Tables.Add("TEST");
ds.writexml("test.xml");
Response.TransmitFile("test.xml");
but the program says it couldnt find any file. also i dont want to "write" a physical file to the server, i just want to send the contents of the dataset as "test.xml"
Please help,
Thanks for spending your time.
Well assuming you are able to populate your DataSet properly, you should be able to use DataSet.WriteXML as in your example to write to a MemoryStream, then dump the file to the HTTP response without ever hitting your server's disk.
I'm a little rusty with C#, this example is from VB, so please take syntax with a grain of salt:
System.IO.MemoryStream objStream = new System.IO.MemoryStream();
System.Data.DataSet ds = new System.Data.DataSet();
ds.Tables.Add("TEST");
ds.WriteXml(objStream);
Response.Clear();
Response.Buffer = true;
Response.ContentType = "text/xml";
Response.AddHeader("Content-Disposition", "attachment; filename=File.xml");
Response.BinaryWrite(objStream.ToArray());
Response.End();
You can use the below code to write a XML file to the Client machine. Here we
write the contents directly into the Response.OutputStream using the XmlTextWriter:
try
{
Response.Clear();
Response.ContentType = "text/xml";
Response.AppendHeader("Content-Disposition","attachment;filename=FileName.xml");
XmlTextWriter xWriter = new XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8);
xWriter.Formatting = Formatting.Indented;
xWriter.WriteStartDocument();
//Create Parent element
xWriter.WriteStartElement("Parent");
//Create Child elements
xWriter.WriteStartElement("Element");
xWriter.WriteElementString("ID", "1001");
xWriter.WriteElementString("Name", "John");
xWriter.WriteElementString("Age", "22");
xWriter.WriteEndElement();
//End writing top element and XML document
xWriter.WriteEndElement();
xWriter.WriteEndDocument();
xWriter.Close();
Response.End();
}
Whenever you work with files in Asp.Net you should use Server.MapPath. If you use relative paths your code will probably try to write to the IIS folder and might (hopefully) not be allowed to do so. So instead of using "test.xml" you should use
Server.MapPath("~/text.xml")
The tilde expands to your web application folder. That said it's a bad idea to store the file to disc. The Response object has an OutputStream which can be used to send data to the browser. You should write your data set directly into that stream. So no file has to be written to disc, you don't have to care about paths and your code will also work with multiple concurrent requests.
You can have the link link to an IHTTPHandler with the folowing code:
public class YourHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Response.Clear();
Response.ContentType = "text/xml";
Response.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", XML_FileName));
Response.TransmitFile(Server.MapPath("MyFile.xml"));
Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}

Categories

Resources