Response image src in asp.net mvc - c#

I return HTML content and display in excel file in ASP.NET MVC.
My question is about img source.Img source does not work.
My Code:
public ActionResult ExportData()
{
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
var stringWrite = new StringWriter();
var htmlWrite = new HtmlTextWriter(stringWrite);
var headerTable = #"<Table><tr><td><img src=""‪C:\Users\xx\Desktop\Export\Export\Images\orderedList0.png"" \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(stringWrite.ToString());
Response.End();
return RedirectToAction("StudentDetails");
}
Above code exports excell file without problem. I only have problem about displaying image. Image can not appear exactly. There is a problem about img source.
What is the correct way for img src for my code?

Please keep in mind the path to the image you are embedding into Excel is an absolute path which MUST EXIST on the client's machine at that exact path.
I assume you get an image placeholder within the workbook? If so, it's a path problem. You will have to make sure the path points correctly to a file which exists at that exact path on that exact machine.
A much better idea would be to alter the src tag to be relative as Ash suggested and host the image from your webserver
var headerTable = #"<Table><tr><td><img src=""fullyqualifiedurltoimagefileonserver.png"" \></td></tr></Table>";
If you are 100% certain on the image path you may be facing an Excel security limitation.

Related

Render SSRS report in PDF format in ASP.NET

I have some deployed SSRS reports on the server. Now I am accessing those reports from my ASP.NET application. After some research I found that default print button of the ReportViewer will not be visible in Chrome or any web browser except Internet Explorer. So all I want to render the Reports in PDF format so user can take the print out of PDF format without saving the file. Here's the piece of code I am using:
IReportServerCredentials irsc = DBConnection.NetworkCredentials();
ReportViewer1.ServerReport.ReportServerCredentials = irsc;
List<ReportParameter> list = new List<ReportParameter>();
list.Add(new ReportParameter("ref_no", refNo));
ReportViewer1.ServerReport.SetParameters(list);
ReportViewer1.ServerReport.Render("PDF");
ReportViewer1.ServerReport.Refresh();
But its not working. The reports are getting rendered but not in PDF format. And if someone take the print out, alignment of all the fields like Tablix, TextBox are not properly aligned. Does any one know how can I do this?
Fortunately, after so many try, have found the solution. This is what I have done:
IReportServerCredentials irsc = DBConnection.NetworkCredentials();
ReportViewer1.ServerReport.ReportServerCredentials = irsc;
List<ReportParameter> list = new List<ReportParameter>();
list.Add(new ReportParameter("ref_no", refNo));
ReportViewer1.ServerReport.SetParameters(list);
byte[] data = ReportViewer1.ServerReport.Render("pdf");
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline;filename=Manifest_Print.pdf");
Response.BinaryWrite(data);
And it worked for me.

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();

ASP.NET Meta refresh Force Download

I am using a meta refresh tag to point to a file that i want to download from a server. How do i make it so that it downloads all files, rather than opens them in the browser. I am adding the meta tag in code behind like this:
String filename = filenode.Element("name").Value.ToString();
HtmlMeta redirectMetaTag = new HtmlMeta();
redirectMetaTag.HttpEquiv = "Refresh";
redirectMetaTag.Content = string.Format("2;url=http://example.example.net/example/" + filename);
this.Header.Controls.Add(redirectMetaTag);
At the moment, thie file eg a jpg is just being opened in the browser
If you want to force the browser to open a Save As dialog you must add a couple of custom headers for the page.
I sugggest you to use the TransmitFile function:
Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition","attachment; filename=[your-file-name]");
Response.TransmitFile( Server.MapPath("~/images/[your-file-name]") );
Response.End();
It will automatically write the file content to the OutputStream of the Response.

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;
}
}
}

Download pdf programmatically

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

Categories

Resources