GWT Progress Bar while buffering PDF content before displaying on browser - gwt

In my GWT app I have written a servlet to download/stream a PDF file.
Following is the code.
protected void updateResponse(HttpServletResponse response, InputStream dataStream, long contentLength, KnownContentTypes contentType, String filename, int cacheSeconds) {
response.setHeader("Content-Type", contentType.getTypeString());
response.setHeader("Content-Length", String.valueOf(contentLength));
response.setHeader("Content-disposition", "inline;filename=" + filename);
response.setHeader("Cache-Control", "max-age=" + cacheSeconds);
byte[] buffer = new byte[BUFFER_SIZE];
try {
ServletOutputStream out = response.getOutputStream();
while ((dataStream.read(buffer)) != -1) {
out.write(buffer);
}
} catch (IOException e) {
sendError(response);
}
}
The pdf is successfully rendered on the browser.
The problem is some pdf's are really large in size and since this is called on window.open all I see is a blank browser.
I want to display a dynamic message like '1MB of 5MB downloaded' and display/render the entire PDF file once all bytes are streamed.
Please let me know how to do this.
I am new to GWT and any help will be appreciated.
Thanks.

This can not be done with synch request which we usually make by calling servlet with Window.open You have to make ajax request to calculate progress and display the response.
Take a look to this library: http://code.google.com/p/gwtupload/. It is really easy to to use and works fine in most of the browsers. It uses ajax requests to calculate progress.

Related

Flying Saucer: itext html to pdf conversion taking long time offline

I used Flying Saucer library to convert html to pdf. It used to work fine if the system is connected to internet. But if system is not connected to internet then it is taking around 5 minutes. Is there any parameter through which i can stop itextrenderer to look for images online.
Below is the method i used to convert HTML to PDF :
LOGGER.info("Converting HTML To PDF.");
OutputStream os = null;
try {
os = new FileOutputStream(finalOutputFilePath);
final Document cleanedDocument = HtmlUtil.cleanHTML(finalInputFilePath);
final ITextRenderer renderer = new ITextRenderer();
final String url = new File(finalInputFilePath).toURI().toURL().toString();
renderer.setDocument(cleanedDocument, url);
renderer.layout();
renderer.createPDF(os);
LOGGER.info("HTML is converted To PDF.");
} finally {
if (null != os) {
os.flush();
os.close();
}
}

Change page numbers in EvoPDF

Within a pdf it is possible to change page numbering, so the first page would be page 5, etc.
(This has nothing to do with headers and footers, i'm speaking strictly about the page numbers as they appear in the pdf toolbar)
Is it possible to control those numbers with EvoPDF?
Yes, apparently with EVOPDF v5 you can set the number to be displayed on the page using the PageNumberingStartIndex property of the PdfHeaderOptions object (same for Footers). I don't know of any examples using this.
It is not possible to change the page numbering displayed by Adobe Reader using an option in the generated PDF document. What you can do is to make the PDF viewer go to a certain page in PDF document when the document is opened. You can check the Go To a Location in a PDF Page When the Document is Opened Demo . The C# code to implement this feature is:
protected void convertToPdfButton_Click(object sender, EventArgs e)
{
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set license key received after purchase to use the converter in licensed mode
// Leave it not set to use the converter in demo mode
htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";
Document pdfDocument = null;
try
{
// Convert a HTML page to a PDF document object
pdfDocument = htmlToPdfConverter.ConvertUrlToPdfDocumentObject(urlTextBox.Text);
int goToPageNumber = int.Parse(pageNumberTextBox.Text);
if (goToPageNumber > pdfDocument.Pages.Count)
{
return;
}
// Get destination PDF page
PdfPage goToPage = pdfDocument.Pages[goToPageNumber - 1];
// Get the destination point in PDF page
float goToX = float.Parse(xLocationTextBox.Text);
float goToY = float.Parse(yLocationTextBox.Text);
PointF goToLocation = new PointF(goToX, goToY);
// Get the destination view mode
DestinationViewMode viewMode = SelectedViewMode();
// Create the destination in PDF document
ExplicitDestination goToDestination = new ExplicitDestination(goToPage, goToLocation, viewMode);
// Set the zoom level when the destination is displayed
if (viewMode == DestinationViewMode.XYZ)
goToDestination.ZoomPercentage = int.Parse(zoomLevelTextBox.Text);
// Set the document Go To open action
pdfDocument.OpenAction.Action = new PdfActionGoTo(goToDestination);
// Save the PDF document in a memory buffer
byte[] outPdfBuffer = pdfDocument.Save();
// Send the PDF as response to browser
// Set response content type
Response.AddHeader("Content-Type", "application/pdf");
// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Go_To_Page_Open_Action.pdf; size={0}", outPdfBuffer.Length.ToString()));
// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);
// End the HTTP response and stop the current page processing
Response.End();
}
finally
{
// Close the PDF document
if (pdfDocument != null)
pdfDocument.Close();
}
}

GWT RequestBuilder: How to handle pdf?

I am sending request on server, and server returns StreamingOutput (wriring bytes of pdf file)
In onResponseRecieved i need to handle this file and start download. How to start to download this file?
I supose you dont need to process that data in javascript, do you?
If you just want to download the file or display it in the browser, create a button in your page so as when the user clicks it will show in a new window or the user will asked to save the file:
final String url = "http://gwtquery.googlecode.com/git/README.txt";
String name = "README.txt";
Anchor link1 = new Anchor(name);
RootPanel.get().add(link1);
link1.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
Window.open(url, "_blank", "");
}
});

how to load a svg in gwt widget from an url

I have a servlet that delivers png and svg images. With png i have no problem:
Image image = new Image(GWT.getHostPageBaseURL() + token);
But how to get svg to work? I already added "lib-gwt-svg" to my dependencies. There is a SVGImage class:
SVGImage svg = new SVGImage(OMSVGParser.parse(???));
The parse takes a string. Is there a way to load a raw String from an URL?
Or how to get it to work (with or without "lib-gwt-svg")?
Update:
thx to Andrei Volgin: he pointed out that it should work with "Image" and it does (i just had to correct the mime type to "image/svg+xml"). But the scripts within svg-image don't work this way (it looks like the images is rendered as a normal bitmap image).
I need the image rendered as svg (with scripts).
If you use a URL to load an image, you don't need any libraries at all. And you don't need a servlet to deliver them. Just add images to your /war/images folder. Then, in your GWT code:
Image image = new Image();
image.setUrl("images/myImage.svg");
myPanel.add(image);
You may want to add some logic for browsers that do not support svg files.
I found a solution that works without any external library (like Andrei's Solution) but keeps also the embedded scripts working. I used the info from here - i used a HTMLPanel and loaded the image via "RequestBuilder":
String url = GWT.getHostPageBaseURL() + link.getToken();
RequestBuilder rB = new RequestBuilder(RequestBuilder.GET, url);
rB.setCallback(new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
//create Widget
chartImage = new HTMLPanel(response.getText());
//add to layout
layout.add(chartImage);
}
#Override
public void onError(Request request, Throwable exception) {
// TODO Auto-generated method stub
}
});

open mp3 or apk file from webview

I would like to know how I can open a Mp3 file from within a webview, basically a link that points to an MP3 file which would then open up the standard media player. Is this possible? I know it is because it works on the default webbrowser so I was wondering why I can't get it to work on a standard webview. Any help would be much appreciated.
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".mp3")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "audio/*");
view.getContext().startActivity(intent);
return true;
} else if (url.endsWith(".mp4") || url.endsWith(".3gp")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "video/*");
view.getContext().startActivity(intent);
return true;
} else {
return super.shouldOverrideUrlLoading(view, url);
}
}
Robbe's answer is correct, however I ran into some headaches implementing this functionality, so you should note that you must be passing a DIRECT LINK to an mp3, it can't be a magical URL that ends up at an mp3 after several redirects, the loading wheel will spin and you will be prompted with a "Can not play the requested stream" message.