Close pop up window after binary file is sent to browser - asp.net

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.

Related

Print Friendly Page

So I would like to be able to have a print button for entries in our database so users can print an entry via a print friendly "form".
My thought was to create a separate page, add labels and have those labels pull the relevant information.
I know I can add the open widget information via this code:
app.datasources.ModelName.selectKey(widget.datasource.item._key);
app.showPage(app.pages.TestPrint);
But I'm running into a few problems:
I can't get the page to open in a new window. Is this possible?
window.open(app.pages.TestPrint);
Just gives me a blank page. Does the browser lose the widget source once the new window opens?
I can't get the print option (either onClick or onDataLoad) to print JUST the image (or widget). I run
window.print();
And it includes headers + scroll bars. Do I need to be running a client side script instead?
Any help would be appreciated. Thank you!
To get exactly what you'd want you'd have to do a lot of work.
Here is my suggested, simpler answer:
Don't open up a new tab. If you use showPage like you mention, and provide a "back" button on the page to go back to where you were, you'll get pretty much everything you need. If you don't want the back to show up when you print, then you can setVisibility(false) on the button before you print, then print, then setVisibility(true).
I'll give a quick summary of how you could do this with a new tab, but it's pretty involved so I can't go into details without trying it myself. The basic idea, is you want to open the page with a full URL, just like a user was navigating to it.
You can use #TestPrint to indicate which page you want to load. You also need the URL of your application, which as far as I can remember is only available in a server-side script using the Apps Script method: ScriptApp.getService().getUrl(). On top of this, you'll probably need to pass in the key so that your page knows what data to load.
So given this, you need to assemble a url by calling a server script, then appending the key property to it. In the end you want a url something like:
https://www.script.google.com/yourappaddress#TestPage?key=keyOfYourModel.
Then on TestPage you need to read the key, and load data for that key. (You can read the key using google.script.url).
Alternatively, I think there are some tricks you can play by opening a blank window and then writing directly to its DOM, but I've never tried that, and since Apps Script runs inside an iframe I'm not sure if it's possible. If I get a chance I'll play with it and update this answer, but for your own reference you could look here: create html page and print to new tab in javascript
I'm imagining something like that, except that your page an write it's html content. Something like:
var winPrint = window.open('', '_blank', 'left=0,top=0,width=800,height=600,toolbar=0,scrollbars=0,status=0');
winPrint.document.write(app.pages.TestPage.getElement().innerHTML);
winPrint.document.close();
winPrint.focus();
winPrint.print();
winPrint.close();
Hope one of those three options helps :)
So here is what I ended up doing. It isn't elegant, but it works.
I added a Print Button to a Page Fragment that pops up when a user edits a database entry.
Database Edit Button code:
app.datasources.ModelName.selectKey(widget.datasource.item._key);
app.showDialog(app.pageFragments.FragmentName);
That Print Button goes to a different (full) Page and closes the Fragment.
Print Button Code:
app.datasources.ModelName.selectKey(widget.datasource.item._key);
app.showPage(app.pages.ModelName_Print);
app.closeDialog();
I made sure to make the new Print Page was small enough so that Chrome fits it properly into a 8.5 x 11" page (728x975).
I then created a Panel that fills the page and populated the page with Labels
#datasource.item.FieldName
I then put the following into the onDataLoad for the Panel
window.print();
So now when the user presses the Print Button in the Fragment they are taken to this new page and after the data loads they automatically get a print dialog.
The only downside is that after printing the user has to use a back button I added to return to the database page.
1.
As far as I know, you cannot combine window.open with app.pages.*, because
window.open would require url parameter at least, while app.pages.* is essentially an internal routing mechanism provided by App Maker, and it returns page object back, suitable for for switching between pages, or opening dialogs.
2.
You would probably need to style your page first, so like it includes things you would like to have printed out. To do so please use #media print
ex: We have a button on the page and would like to hide it from print page
#media print {
.app-NewPage-Button1 {
display : none;
}
}
Hope it helps.
1. Here is how it is done, in a pop up window, without messing up the current page (client script):
function print(widget, title){
var content=widget.getElement().innerHTML;
var win = window.open('', 'printWindow', 'height=600,width=800');
win.document.write('<head><title>'+title+'/title></head>');
win.document.write('<body>'+content+'</body>');
win.document.close();
win.focus();
win.print();
win.close();
}
and the onclick handler for the button is:
print(widget.root.descendants.PageFragment1, 'test');
In this example, PageFragment1 is a page fragment on the current page, hidden by adding a style with namehidden with definition .hidden{display:none;} (this is different than visible which in App Maker seems to remove the item from the DOM). Works perfectly...
2. You cannot open pages from the app in another tab. In principle something like this would do it:
var w=window.parent.parent;
w.open(w.location.protocol+'//'+w.location.host+w.location.pathname+'#PrintPage', '_blank');
But since the app is running in frame nested two deep from the launching page, and with a different origin, you will not be able to access the url that you need (the above code results in a cross origin frame access error). So you would have to hard code the URL, which changes at deployment, so it gets ugly very fast. Not that you want to anyway, the load time of an app should discourage you from wanting to do that anyway.

Web form non-responsive after download

I'm working in ASP.NET (2.0) and we have a page where a user is able to select and download a series of files as a zip. I got this to work without undo difficulty by using the DotNetZip library (which is probably not relevant to the problem, but included for completeness.)
After the user checks which files they want to download, the page does a postback, and in the button click event handler, I use the following code:
Response.Clear();
Response.BufferOutput = false; // false = stream immediately
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=FileRequest.zip");
using (ZipFile zip = new ZipFile())
{
zip.AddFile(MapPath("/datafiles/fileToZip.pdf"), "");
zip.Save(Response.OutputStream);
}
Response.Close();
And this all seems to work great. The user clicks the button, a download window pops up, the user downloads the zip. All is good...
...until they decide they want to do something else on the page. The buttons in the form are no longer responsive. For instance, if I click the download button again, it does nothing. If I reload the page, I can repeat this behavior...it works once, then does nothing.
I'm not understanding why the browser doesn't send the new request. It's not "spinning" or otherwise acting busy. I thought that this might be a browser issue, but I've repeated it in both IE and Firefox, so it seems likely that it's something I'm not understanding. Strangely, it's only form submission elements that seem to be non-responsive. Javascript still works, and so do regular links.
So why is this happening, and how do I get around it?
The problem is likely down to you returning;
Response.ContentType = "application/zip";
Once this has been sent (along with the actual content), the browser would assume it has nothing left to do (I believe).
You probably should create a new window specifically for downloading the files by saving the file selection in a session parameter (or equivalent) and opening a popup window that has your download code in.
This will leave the parent page in a suitable state.
Content-disposition header seems to be a discouraged solution. But the same effect of ASP.NET forms not being responsive occurs if you use standard Redirect to a zip file.
I solved very similar problem (returning *.csv files by the server for download) using Tančev Saša's code in "Response.Redirect to new window" Q&A and it works great. Perhaps it might produce some popup warnings in some browsers, but I think this is how it's often done in download sites.

Pop up to save image in asp.net

I am using asp.net 3.5 and C#.
I have a image which I want user can download.
Like, there would be a download button or link. When user click on this link he will be prompted with a pop up to save that image to his desktop.
I have tried with
<a href ="path" > </a>
but it is opening the image in other page, I want user to be prompted to either save or view the image,
please help
Thanks in advance
You need to write an IHttpHandler that serves the image along with a Content-Disposition header.
For example:
Response.AppendHeader("Content-Disposition", "attachment; filename=\"MyImage.png\"");
Response.TransmitFile(path);
You would probably pass the image name on the query-string.
If so, make sure it doesn't contain / or \, or attackers will be able to read arbitrary files.
You need to have another page or, better yet, an HttpHandler, that takes the image path as part of the query string or as a post parameter that will send the response with Content-Disposition set to attachment. Setting the content disposition this way will cause the browser to display the file download dialog. A slightly easier way, though it depends on the user doing something extra is simply to have the link open the image in a new page and let the user right-click on it and do a "Save As".
Download
or
<a href="/path/to/image" target="_blank">
Load Image in New Window then Use Save As</a>

openning files in another browser page/tab

i have an action that return a file content. i added:
Response.AddHeader("Content-Disposition", "attactment; filename:\"" + survey.File + "\"");
so that the image would be opened in another tab/page, gets opened in the current tab/page.
whats wrong with the header?
The content-disposition header instructs the user agent how it should present the data, and it is usually used when serving up binary data (as opposed to plain text). When set to "attachment", the display of the content is contingent upon further action of the user. In other words, the user should receive a prompt and must decide what to do with the content (usually given an "Open" or "Save" option).
You can not programmatically force a hyperlink to open up in a new tab. Even if you could, you should not. This behavior should be controlled by the user agent. As a user, when I want to open something in a new tab, I use the mouse-wheel-click because that is how my browser is configured.
You cannot control browser's tab behaviour by using HTTP headers - there is nothing in your code that affects this.
What might help you is changing HTML code that points to your download - if you are using tag you can set its target attribute to _tab or _blank and it will work in many browsers.

does showModalDialog interfere with ClientScript.RegisterStartupScript?

I'm showing a modal dialog via "window.showModalDialog(..." which happens in a vbscript function (the page shown is aspx). I'd like to do some resizing of the window based on the number of rows in a datatable that's coming back. So naturally I go to register a startup script that resizes the window based on the number of rows. Well, that didn't work, so I tried to register a script that just showed a msgbox.
The code looks like (in the OnLoad event handler):
if (!this.ClientScript.IsStartupScriptRegistered(typeof(MyPageClassName), "hello"))
{
this.ClientScript.RegisterStartupScript(typeof(MyPageClassName), "hello",
#"<script language=vbscript>
sub fnWindowOnLoad()
MsgBox ""hello""
end sub
<script>", false);
}
if (!this.ClientScript.IsStartupScriptRegistered(typeof(MyPageClassName), "hello"))
{
throw new Exception("Failed to load script");
}
To me it looks like this should work and show a message box that says "hello" when the page loads (I've got the window's onload event set to fnWindowOnLoad). But what happens is nothing, no exception, no alert. I've tried every Type I could think of in the typeof call. Nothing seems to work. The only thing I can think of is that since the dialog is a modal ClientScript.RegisterStartupScript won't run properly. But that doesn't make any sense to me.
I put the MsgBox "hello" call into my script block directly and the alert showed, so it's possible. But I need to modify some arguments in the code behind so I have to use RegisterStartupScript as far as I can tell.
Have you tried opening your window via window.open() rather than window.showModalDialog()? I've seen some postings on the web about incompatibilities between showModalDialog() and RegisterStartupScript.
showModalDialog() is an IE only method, so it's not recommended anyway. I know it's convenient because it returns a value, but there are various ways to simulate this functionality.
Edit: The other problem with showModalDialog() is that IE often caches the results. This means that if one time you calling the dialog, you do not resize it, then another time you do, then 2nd time might get your the first cached dialog. A way to get around this is to add a unique querystring at the end. Like MyDialog.aspx?q=320934 (randomly generated or generated based on server tics).
The solution for this was to have a script that read a value out of a hidden field and then resized the dialog. The value was set on the Page_Load. Using RegisterStartupScript never seemed to work, neither did RegisterClientScript, so I'm pretty sure modal dialog and RegisterXxx don't get along. Need to use window.dialogHeight & window.dialogWidth in the vbscript.

Resources