GWT:How to generate pdf save/open window? - gwt

I am using GWT2.4 version in my application.In this I application I have created Form using GWT control (like textbox,textaera).
I have also created preview of form.In that preview I have button of pdf generation.
Now I want to create behavior to deal with pdf link same as browsers(Mozilla/chrome).
For example in Mozilla on click of pdf link it asks for either save or open in a pop up window.
While debugging I found a jar name iText which can be used to create pdf, I want to implement browsers behavior in this also.
Please help me out.
Thanks in advance.

Read file contents into byte array.
Then do request for servlet or service, for eg. this way:
Window.Location.replace("rest/downloadPdf");
That Service should return Response with the right content type:
#Path("downloadPdf")
#GET
#Produces({"application/pdf"})
#Consumes(MediaType.TEXT_PLAIN)
public Response downloadPdf() throws Exception {
byte[] bytes = getYourPDFContents();
return Response
.ok(bytes, MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", "attachment; filename=\"yourFile.pdf\"")
.build();
}
Browser will then show save as dialog.
That's example of Service, you must include Jersey library into your project to be able to use method like I've wrote above .

Related

How to give a url to the page?

I am trying to open a new window with the below code. It opens a new window but it has the url as "about:blank". How to change the this url and give a custom url.
private native void openPrintWindow(String contents) /*-{
var printWindow = window.open("", "PrintWin", false);
printWindow.document.open("text/html","replace");
if (printWindow && printWindow.top) {
printWindow.document.write(contents);
} else {
alert("The print feature works by opening a popup window, but our popup window was blocked by your browser. If you can disable the blocker temporarily, you'll be able to print here. Sorry!");
}
}-*/;
It is empty, because first parameter of window.open method is an empty string. Check some examples here. So it should be something like this:
window.open("https://stackoverflow.com", "PrintWin", false);
From Your code I see You want to open a new window by custom URL with some HTML content inside. You cannot do it this way. If You put some URL, the browser will try to open this URL by making a GET request.
Solution to what You want to achieve is to do it more-or-less the MVC way (please note it is NOT a fully correct MVC solution, just a guidance):
Before You open the window, You need to store a content somewhere (best option is on a server side, but there is also a way to store it on a client side)
Create a new page, accessible via Your custom URL (either a simple HTML or a service, up to Your needs).
You need to write some code in this new page which will retrieve Your content (stored previously somewhere) and present it in this newly opened window.

How to clear the file data from a multipart jsp

I have a JSP form with form property (In order to submit multiple files) as
enctype = "multipart/form-data";
encoding = "multipart/form-data";
When the form get submitted I'm reading the form data as
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FileItem> fileItemList = fileUpload.parseRequest(request);
Now the issue I'm facing is that after the servlet process the request I'm coming back to the same page, after which if the user refreshes the page than based on the previous action performed the form is getting submitted again to the same servlet and I'm again getting the file which has been previously browsed and it's saving again.
Is there is any way we can clear the file information which has been browsed ?
Thanks
Your HTML code would have helped here. However, here is a solution that I think could help you resolve the issue.
You can reset the files associated with the file upload control by using
document.getElementById('yourFileInputControlId').files = '';
This should be done in java script immediately after your file upload request has been handled.(I am considering you are uploading your file using ajax)
If you are actually submitting the entire form rather than using Ajax, I do not see a reason why the file control would not reset. Please provide more details by editing the question if you still face the issue

File download in REST uing jersey and RESTclient in firefox not showing download pop up

I'm writing a code to download files using ReST API. my code is working fine and I am getting a response back.
But i am getting the file content as response body in browser rather than asking for a file download
below is the sample code I am using.. please help me to figure out what i am doing wrong.
I tried all the codes posted in SO that matched with my requirement but still i could not get the pop up .
#Path("/downloadfiles")
public class DownloadFiles {
#GET
#Produces("text/plain")
public Response getFiles( ) {
File file = new File("/opt/test/sample.csv");
ResponseBuilder response = Response.ok((Object) file).header("Content-Disposition",
"attachment; filename=sample.csv");
return response.build();
}
}
Thanks.
Hello try to make it produce "application/octet-stream" instead of text/plain
The kind of content you specify is the reason you only see text
hope it helps
Try #Produces("test/csv") and if that alone doesn't work try also setting the entity on the ResponseBuilder to the String contents of your file. That works for me, anyway.
BTW, in my browser I don't get a popup, it just starts downloading the CSV file immediately.

Downloading a PDF from an HTTP POST call

Here is what I'm trying to accomplish (IE 9+, Chrome, FF, Safari) without the use of JQuery:
Make an http POST call to my API endpoint with some data
Server dynamically generates a PDF and returns the PDF as a binary attachment
Browser does default download behavior and downloads the PDF without refreshing the page
Basically I want to get the behavior similar to <a href="test.pdf"> but for a dynamically generated PDF after making a POST call instead of a GET call.
I've tried lots of different things, but they either didn't work cross browser (such as using $window.open() with a blob URL), were blocked by popup blockers (any $window call outside of the click scope), or didn't cause the PDF to be automatically downloaded (any $http POST solution).
I finally found one solution that seems to work which creates a form using javascript and submits it.
var form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('action', myurl);
var params = {foo: 'bar'};
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement('input');
hiddenField.setAttribute('type', 'hidden');
hiddenField.setAttribute('name', key);
hiddenField.setAttribute('value', params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
This successfully accomplishes the 3 steps above, but now I've run into a new problem. There is no way to determine when the PDF file has been successfully downloaded. This is preventing me from removing the form and from displaying a friendly 'Please wait...' message to the user. There is also the additional problem that submitting the form cancels any outstanding ajax requests as well which isn't optimal.
I have full control over both the server and the client, so what's the best way to fix this? I don't want to have to save the PDF on the server so passing back a url and doing a second GET request from the client won't work in this case. Thanks!
You can make an server response behave as a download by applying some HTTP headers:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="SOME_NAME.pdf"
Content-Transfer-Encoding: binary
If you're initiating the download through JS only (instead of having the user click a download link), then check out this question for some caveats.
Update: Syntax for POST
Better Update: Form solution with iframe target
You can detect that your server-side script has finished (and subsequently, that the download is ready to begin) by having the form target an iframe. I believe this should also fix the issue of cancelling outstanding Ajax calls, but I'm not certain. Here is the code to do it (just stick this into your code example after the for loop and before document.body.appendChild(form);):
var frame = document.createElement('iframe');
frame.setAttribute('id', 'pdfFrame');
frame.onload = function(){
document.body.removeChild(form);
document.body.removeChild(frame);
alert('Download ready!');
}
document.body.appendChild(frame);
form.setAttribute('target', 'pdfFrame');
You can replace my alert with your code to remove the 'Please wait...'.

GWT dynamic data in new browser window at client side

I've got GWT module where I do some stuff and I have search results - doesn't matter in which form. Now after searching, and clicking on for example "Export to HTML" button,I would like to create new html page (for example from client side code by creating simple string which contains only listed results of searching list of results ) and open it in new browser window. I know that there is Window.open(...) method, but there I must specify url which i don't have. I want to create this new html page by client side - without server inference (I don't want to create some resource on server side and then paste url to this resource to client side). Is there any possibility to achieve this? If there is no option, other method which would satisfy me, is to open standard dialog box for saving, which will allow to save results in a html file.
Thanks for helps.
Kind regards.
Here's the code I use to print:
native void openPrintWindow(String contents) /*-{
var printWindow = window.open("", "PrintWin");
if (printWindow && printWindow.top) {
printWindow.document.write(contents);
printWindow.print();
printWindow.close();
} else {
alert("The print feature works by opening a popup window, but our popup window was blocked by your browser. If you can disable the blocker temporarily, you'll be able to print here. Sorry!");
}
}-*/;
Seems like you could adapt it for your purposes with some simple rewording and by removing the call to print()! The contents variable just holds flat HTML. There are no trips to the server.
openPrintWindow("<h1>Search Results</h1><ol><li>etc...");
The method of opening new window from client js which allows user to save that generated content from browser's save as menu is data:url scheme, content written to opened page via println usualy not saved. But data:url works only in morden browsers. And the content written should be quite small to fit browser's url length resteiction.
See example from this article http://en.wikipedia.org/wiki/Data_URI_scheme#JavaScript