I'm using Server.Transfer and in the 2nd place I have a number of labels that are updated with a Request.Form["textbox_text"];
This all works really well, but the problem is I also want to write the content in that textbox to file
like a word document using this method
Response.Clear();
Response.AddHeader("Content-disposition", "attachment; filename=Word.doc");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application / vnd.ms -word";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
htw.Write("<table><h2><b>[ Text ]</b></h2><br>" + TextBox_name.Text + "</table>");
Response.Write(sw.ToString());
Response.End();
But whenever I check the file it will not have anything written on it. I've even tried to save the value of a Request.Form to a static variable and then write that variable but without any success.
How are you using Server.Transfer()? Post that code, make sure you are using the overload that preserves the form values:
Server.Transfer("page.aspx", true);
I have tried a code to open a pdf file in a web browser. It give to allows me to open the file through pdf reader no in the browser. Almost all the codes i found over the internet are also same as this code. But this code doesn't work as i expected.
Help me to figure out the problem in here. I'm using a link button in the aspx.
Here is my code
aspx code
<asp:LinkButton ID="pdfViewLOP" runat="server" Style="margin-left: 10px" OnClick="pdfViewLOP_Click" >View PDF</asp:LinkButton>
aspx.cs
Response.Write(string.Format("<script>window.open('{0}','_blank');</script>", "viewPDF.aspx"));
Code of the new page which pdf should be displayed
string name=Session["name"].ToString();
int refNo = Convert.ToInt32(name);
string FilePath = Server.MapPath("~/filesPDF/" + refNo + ".pdf");
WebClient User = new WebClient();
Byte[] buffer = User.DownloadData(FilePath);
if (buffer != null)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
How if you directly create a hyperlink with target _blank and path of file as a href of hyperlink.
So the result hyperlink generated inside the html page is
View PDF
I have a working Excel Report code. Still, when I click the button the file goes directly to my download folder, without giving me the option to change its name or selecting where I want to save it.
Code is the following:
public void GetExcel()
{
var list = (IList<LeaseViewModel>)Session["currentList"];
var grd = new GridView { DataSource = list, AutoGenerateColumns = true };
grd.DataBind();
Response.ClearContent();
Response.AddHeader("Content-type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
Response.AddHeader("content-disposition", "attachment;filename=Leases.xls");
Response.ContentType = "application/excel";
var swr = new StringWriter();
var tw = new HtmlTextWriter(swr);
grd.RenderControl(tw);
Response.Write(swr.ToString());
Response.Flush();
Response.End();
tw.Close();
swr.Close();
}
Can somebody please indicate what should I change in order to have the window popping?
Thanks a lot.
Thanks for everybody highlighting this is a browser-configuration issue.
I thought that once I have the definition of the default name in the code I could also define it to always ask what is the name I want. I tested in different browsers though, and fact is you were right, thanks for identifying it and noticing me.
Regarding the default name issue, here is how I solve it:
Before:
Response.AddHeader("content-disposition", "attachment;filename=Leases.xls");
After:
Response.AddHeader("content-disposition", "attachment;filename=" + Session["listName"] + "_Report.xls");
Now regardless the report I export, the name is always customized.
Hope it helps other newbies like me (:
This is the code for downloading the file.
System.IO.FileStream fs = new System.IO.FileStream(Path+"\\"+fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] ar = new byte[(int)fs.Length];
fs.Read(ar, 0, (int)fs.Length);
fs.Close();
Response.AddHeader("content-disposition", "attachment;filename=" + AccNo+".pdf");
Response.ContentType = "application/octectstream";
Response.BinaryWrite(ar);
Response.End();
When this code is executed, it will ask user to open or save the file. Instead of this I need to open a new tab or window and display the file. How can I achieve this?
NOTE:
File won't necessary be located in the website folder. It might be located in an other folder.
Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
Response.BinaryWrite(fileContent);
And
<asp:LinkButton OnClientClick="openInNewTab();" OnClick="CodeBehindMethod".../>
In javaScript:
<script type="text/javascript">
function openInNewTab() {
window.document.forms[0].target = '_blank';
setTimeout(function () { window.document.forms[0].target = ''; }, 0);
}
</script>
Take care to reset target, otherwise all other calls like Response.Redirect will open in a new tab, which might be not what you want.
Instead of loading a stream into a byte array and writing it to the response stream, you should have a look at HttpResponse.TransmitFile
Response.ContentType = "Application/pdf";
Response.TransmitFile(pathtofile);
If you want the PDF to open in a new window you would have to open the downloading page in a new window, for example like this:
View PDF
this may help
Response.Write("<script>");
Response.Write("window.open('../Inventory/pages/printableads.pdf', '_newtab');");
Response.Write("</script>");
You have to create either another page or generic handler with the code to generate your pdf. Then that event gets triggered and the person is redirected to that page.
Here I am using iTextSharp dll for generating PDF file.
I want to open PDF file instead of downloading it.
So I am using below code which is working fine for me.
Now pdf file is opening in browser ,now dowloading
Document pdfDoc = new Document(PageSize.A4, 25, 10, 25, 10);
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
Paragraph Text = new Paragraph("Hi , This is Test Content");
pdfDoc.Add(Text);
pdfWriter.CloseStream = false;
pdfDoc.Close();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.End();
If you want to download file,
add below line, after this Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Example.pdf");
you can return a FileResult from your MVC action.
*********************MVC action************
public FileResult OpenPDF(parameters)
{
//code to fetch your pdf byte array
return File(pdfBytes, "application/pdf");
}
**************js**************
Use formpost to post your data to action
var inputTag = '<input name="paramName" type="text" value="' + payloadString + '">';
var form = document.createElement("form");
jQuery(form).attr("id", "pdf-form").attr("name", "pdf-form").attr("class", "pdf-form").attr("target", "_blank");
jQuery(form).attr("action", "/Controller/OpenPDF").attr("method", "post").attr("enctype", "multipart/form-data");
jQuery(form).append(inputTag);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
return false;
You need to create a form to post your data, append it your dom, post your data and remove the form your document body.
However, form post wouldn't post data to new tab only on EDGE browser. But a get request works as it's just opening new tab with a url containing query string for your action parameters.
Use this code. This works like a champ.
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = outputPdfFile;
process.Start();
In ASP.NET 4.0 webforms, I'm trying to export a paged ListView control to an Excel file by un-paging the ListView's (trucks) datasource:
dsTrucks.EnablePaging = false;
For a non-paged ListView control, I can get it to work.
Here's the attempt to "un-page" and then export the ListView control:
// Nuke the current page.
Response.Clear();
// Setup the response header.
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Trucks.xls");
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
// Turn off view state.
this.EnableViewState = false;
// Create a string writer.
var stringWriter = new StringWriter();
// Create an HTML text writer and give it a string writer to use.
var htmlTextWriter = new HtmlTextWriter(stringWriter);
// Disable paging so we get all rows.
dsTrucks.EnablePaging = false;
// Render the list view control into the HTML text writer.
listViewTrucks.DataBind();
listViewTrucks.RenderControl(htmlTextWriter);
// Grab the final HTML out of the string writer.
string output = stringWriter.ToString();
// Write the HTML output to the response, which in this case, is an Excel file.
Response.Write(output);
Response.End();
There's no error but the output in the Excel file is still just one page of the ListView control instead of all rows.
Any ideas on where to start to get this to work?
Thanks,
Adam
Just a guess, but it might be that EnablePaging works only on the control's OnInit() and it is too late by the time you call it from your code.
Perhaps you could you set the PageSize some MAXINT value and force all results into one single page?