Generating pdf before leaving a page in Asp.net - asp.net

After submitting a form and before Redirecting a page need to generate a pdf, ask the user to save the file, then redirect the page .
Below is my code
DataSet objData = objInsert.Execute();
DocLib dl = new DocLib();
System.IO.MemoryStream ms = dl.GenerateForm(objData.Tables[0].Rows[0]);
Response.AddHeader("content-disposition", "attachment;filename=" +OrderNo + ".pdf");
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
Response.Redirect("OrderList.aspx");
But currently once the save dialog box appears the page stops navigation and remains in the same page. How to redirect to another page.

I can't see a reason to effect Redirect's work. As another solution, you can try this.
Page.ClientScript.RegisterStartupScript(typeof(Page),"navigation",
"<script>window.location.href='OrderList.aspx'</script>")

Related

ASP.NET "application/pdf": code runs only once

I'm working on a SharePoint 2013 site and I've added the ability to save pages in PDF. The PDF conversion is handled by the third party library SelectPdf.
I managed to get everything to work (rendering and file download), except that the "PDF Download" button that I have on my page works only 1 time. Meaning, the click event on the code behind is fired only once, no matter how many times I click the button (notice that I click it with intervals of 10+ seconds). If I want to download the PDF file again, I have to refresh the page.
I put together a "hello world" example (see below) in order to pinpoint the problem:
protected void lnkPdfDownload_Click(object sender, EventArgs e)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=test.pdf");
/************************************ Create PDF File ************************************/
string html = #"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"">
<html dir=""ltr"" lang=""en-US"">
<body><h1>Hello World</h1></body>
</html>";
HtmlToPdf converter = new HtmlToPdf();
PdfDocument doc = converter.ConvertHtmlString(html);
byte[] bytes = doc.Save();
Response.OutputStream.Write(bytes, 0, bytes.Length); // ALTERNATIVE: doc.Save(Response.OutputStream);
/************************************ Create PDF File ************************************/
//Response.End(); // This throw a ThreadAbortException, therefore I'm using the alternative code below
Response.Flush();
Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
At the beginning I thought it was Response.End() that caused the issue (by throwing the ThreadAbortException), but I replaced it with other code and I still have the same problem (no exceptions are thrown now).
I don't think the problem is in the SelectPdf library: I can comment out the entire block (between the "Create PDF File" comments), and I still get the same thing (obviously no PDF is generated).
I noticed that, at most, I can successfully click the "download" button up to 2 times (it's rare, and not consistent): the third time nothing happens.
While this isn't a huge deal, I think there is something wrong going on that I'm not seeing. Here is why: after I click the "download" button (and get my PDF file), I am not able to go on edit mode in my SharePoint page. The "loading" message keeps spinning but nothing happens (again, unless I refresh the page).
Has anyone had this problem? I looked online but I couldn't find anything about it.
I'm using Internet Explorer 11 and Chrome 51. Please let me know if you need more information. Thank you.
Are you sure there are not javascript/jquery errors happening when the download button is clicked that prevent the re-clicking of the PDF button and also going into edit mode?
Especially since refreshing the page makes everything work again.

Open PDF new browser tab ASP.net 2.0

I am trying to open a PDF in a new tab in the browser. So far I have been able to get the PDF in the browser within the "same" page. However I would now like it to open it in a new tab. However I am stuck on how to achieve this?
Response.Clear()
Response.ClearContent()
Response.ClearHeaders()
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Disposition", "inline;filename=" + strFileId & fileExtension)
Response.AddHeader("Content-Length", bytesReturned.Length.ToString())
Response.OutputStream.Write(bytesReturned, 0, bytesReturned.Length)
Response.Flush()
Response.End()
Result:
The result is displayed in a gridview, I would like to link each "view" button to a target"_blank" attribute. The "ID" corresponds to the file name.
From my research, I can see you can add a button in the aspx page and give it target "_blank" attribute but I am not sure how to link it to my displayPDF() method?
If the question is unclear, please let me know.
One way is to make view button an anchor and set its attribute to _blank and second is to open file by using code behind.
Call this code on button click
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "a", "window.open('"+strFileId & fileExtension+"','_blank');", true);

Setting ContentType = "image/tiff" and sending an image is not working in IE

I need to send an image (as a downloadable file) from an ASP web page. It is working correctly in every browser except for IE (all versions).
Here is the server side code:
bool export = Request.QueryString["Export"] != null;
if (export)
{
byte[] allBytes = File.ReadAllBytes(#"C:\MyImage.tif");
Response.ContentType = "image/tiff";
Response.AddHeader("content-disposition", "attachment; filename=\"MyImage.tif\"");
Response.OutputStream.Write(allBytes, 0, allBytes.Length);
Response.OutputStream.Flush();
Response.End();
return;
}
And here is the JavaScript:
$('#ExportFrame').attr('src', 'Default.aspx?Export=true'); // ExportFrame is an iframe
In IE, I keep getting an error saying "Internet Explorer cannot download Default.aspx from localhost". I thought it might be an issue with loading it in an iframe element, but redirecting to the URL is not working either. The really odd thing is that going to the URL (/Default.aspx?Export=true) does not work the first time, but works every time after that. Again, this works in every browser I've tried except IE.
Any ideas?
Update:
The aspx page has the following code to keep the page from getting cached:
// Never cache this page
Response.CacheControl = "no-cache";
Response.AddHeader("Pragma", "no-cache");
Response.Expires = -1;
Removing the first 2 lines and leaving only Response.Expires = -1 resolved the issue.
AFAIK, you have to fix the file type association on the client for this to work. Known issue - Windows Updates often breaks this association resulting in this type of error message.
http://www.eggheadcafe.com/software/aspnet/36147698/office-updates-break-tiff-file-associations.aspx
UPDATE
1.) Create a blank text document on your desktop. (File.txt)
2.) Change the file extension from .txt to .tiff.
3.) Right click on the .tiff file and select open. On the next box choose “select program from a list of installed programs.
4.) Click on the browse button and browse to “C:\Program Files\Common Files\Microsoft Shared\MODI\12.0”.
5.) Select “MSPVIEW.EXE” and click “Open”.
6.) Select “Microsoft Office Document Imaging” and click OK.
7.) You will get a message saying it is unable to open the document. That is because it is not an actual graphic image. We are just setting the file association at this point.
8.) Repeat steps 1 – 7 and use .tif as apposed to .tiff because there are two different file extensions for this type of document.
The aspx page had the following code to keep the page from getting cached:
// Never cache this page
Response.CacheControl = "no-cache";
Response.AddHeader("Pragma", "no-cache");
Response.Expires = -1;
Removing the first 2 lines and leaving only Response.Expires = -1 resolved the issue. For some reason this was preventing the image from working properly in IE.

ASP.NET 4: HttpResponse open in NEW Browser?

I am using a PDF generater that utlizes HttpResponse. Is there a way (perhaps passing a header tag) to open the PDF in a NEW windows instead of the same one? I don't want the user to be directed away from the website...
Here's the code I'm using:
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear();
response.AddHeader("Content-Type", "application/pdf");
response.AddHeader("Content-Disposition",
"inline; filename=" + downloadName + "; size=" + downloadBytes.Length.ToString());
response.Flush();
response.BinaryWrite(downloadBytes);
response.Flush();
response.End();
You cannot do that on server side if you have not generated the link yourself. But if you have, then as Robert said, provide a target with the <a> link.
There is a server-side alternative and that is to set the content type to application/octect-stream so that the file is download and user will be able to open it with the application of choice outside browser. See here for more.
You also need to use content disposition header to provide the file name so that client can know what file type is it after it has been downloaded as binary.
Content-Disposition: attachment; filename=my.pdf;
You presumably have a link on your site that directs the user to the URL where this PDF generation is done. In that link, add target="_blank" to the <a> tag.
If what you're really asking is how to make the save dialog to show instead of having the PDF loaded into your browser, then you need to modify your header.
You are setting Content-Disposition to 'inline', change that to 'attachment'
http://support.microsoft.com/kb/260519

Close pop up window after binary file is sent to browser

Is there a way to close a pop up window after the page writes binary data (PDF) to the browswer?
Here are the details:
Whenever my web appilcation needs to print, it will pass some parameters over to a pop up window, which will display the print options. When the user clicks on the Print button, it will set the src of a iframe that will call the page that does the printing.
I have PDFConverter to convert URL / HTML to a pdf file. At the end of the converting, it will write the binary to the browser. Here are some code:
response.AddHeader("Content-Type", "binary/octet-stream");
response.AddHeader("Content-Disposition",
"inline; filename=" + fileName + ".pdf; size=" + pdfBytes.Length.ToString());
response.Flush();
response.BinaryWrite(pdfBytes);
response.Flush();
After this is done, i will need to close the pop up window. However it seems like you can't do anything after the response is flushed. Any ideas?
Thanks in advance!
Angela
Instead of creating the iframe in the popup window, you could create it in the parent window. This way once the user clicks the print button, you could safely close the popup without interupting the printing process. But instead of going through all the pain of creating new popups windows which might be blocked by some browsers, I would simply create some placeholder in the main page so that the user could choose printing options and then print the document.
Just in case anyone else is having the same problem. This is the solution that seems to work for me.
I use the jQuery Simple Modal to show my option list page. On this page, I have a window timer running every 1 second to check against the server if the print job is done. I use ajax for that. Once the job is done, I update the session variable, and the ajax call to the server will pick up the session value and close the pop up window.

Resources