How to display a PDF stream in a browser using javascript - javascript

I am accessing an existing WCF web service (which returns a PDF as a byte stream) using jquery's ajax methods.
When the call to the service completes, I end up with a javascript variable containing a PDF (the variable has the binary data in, starting "%PDF-1.4...").
I'd like to display this PDF in a new browser window, but I'm having difficulty achieving this.
My research so far shows that I might be able to achieve what I want using a data: uri, so my code that's called when the ajax call completes is as follows:
function GotPDF(data)
{
// Here, data contains "%PDF-1.4 ..." etc.
var datauri = 'data:application/pdf;base64,' + Base64.encode(data);
var win = window.open("", "Your PDF", "width=1024,height=768,resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no");
win.document.location.href = datauri;
}
This causes a new browser window to open, but the contents are blank.
Interestingly, if I point my browser (IE9) at an existing file on my local disk by using a file: uri, such as file://c:/tmp/example.pdf, then I get the same result, i.e. a blank window.
Is there any way I can display this PDF data?

Code you wrote does not display anything, simply open a blank window (location.href is an hash for browsing history, not the content of the page).
To display a PDF you have, at least, following options:
× Embed the PDF viewer inside an object tag. It may not be as straightforward as you may imagine, take a look to this post for sample code. In short it should be something like this:
<object data="your_url_to_pdf" type="application/pdf">
<div>No PDF viewer available</div>
</object>
That's basic code but I suggest to follow what I say in the linked post if you need higher cross-browser compatibility (it also contains a few examples about how you might try to detect support for a PDF viewer).
× Download the file to local computer (simply add the full URL of your web service method that produces the file, do not forget to add the proper Content-Disposition in the header).
× Open the file into a new browser window. Create a normal a tag as you point to a PDF file on-line that you want to display in a new window. Change the href to javascript:functionName and in that function produce the URI you'll use to call the web service method.
Whatever you'll do, do not forget to set the proper MIME type in your response moreover you method shouldn't return a byte stream (even if encoded) but a valid response for your web browser.

If you are using <embed> or <object> tag to display a streamed PDF file (or other file types) from a server as in:
<object data="SomeServlet?do=get_doc&id=6" type="application/pdf" width="800" height="400">
make sure the server sends the proper http content-disposition value, which in this case would be inline.

Related

Is It Possibly to Access Firefox Save As Command Using JS?

I'm trying to figure out how to call the File Save As Command in Firefox
(the one you get when you right click an image and save it) to save an image using JS (or if there is something else I can use, I would be grateful if you pointed me in that direction). I am looking for an example of how to open the Save As menu and pre-fill the file name field ... I've been searching furiously and have come up with zip. In my search I saw that you cannot directly save a file to disk, but is it impossible to call the save as function? Any suggestions would be greatly appreciated!
Edit:
I'm not looking to make this code available to everyone, and the java script is client side, I'm just writing a small script to make saving photos a little easier in terms of naming them.
-Will
No you can't do this, and really you are trying to find a solution in a way that does not embrace the internet and the way people interact with content. What you are trying to do is call on Operating System operation from Javascript. If there were anyway this would be possible, I don't think it is at all, it would be a very poor solution. Think about all the different Operating Systems Firefox is being used on. If you found a solution for Windows 7, what about an Apple Mac running Firefox?
What you should consider is that a User decides whether to Save something to their computer, not the programmer of the application. Provide a link to the file, most users know how to right click a link and select Save As. Add help tip explaining what to do as well.
To give a File a specific name or even start an automatic download when a User clicks or takes some kind of action, you can create a response from your server that is a PDF,Excel,Jpeg,Doc,Docx or many other files types. The server can load the file in memory and sent it as a response with the proper header information in the response.
For example to set a specific name for the file when the user downloads you can set your Response header with something like:
header('Content-Disposition: attachment; filename="downloaded.pdf"');
You can use the anchor element's download attribute to specify that a link is to be downloaded. Note that this is not implemented in all browsers, Chrome, Firefox, and Opera currently support it
https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
HTMLAnchorElement.download
Is a DOMString indicating that the linked
resource is intended to be downloaded rather than displayed in the
browser. The value represent the proposed name of the file. If the
name is not a valid filename of the underlying OS, browser will adapt
it. The value is a URL with a scheme like http:, file:, data: or even
blob: (created with URL.createObjectURL).
Demo
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillRect(25,25,100,100);
ctx.clearRect(45,45,60,60);
ctx.strokeRect(50,50,50,50);
var link = document.getElementById("link");
//Set href to the data url that you want downloaded
link.href = "http://placehold.it/350x350";
//set download to the default filename you want to use
link.download = "image.png";
<canvas id="canvas" width="150" height="150"></canvas>
Click to download
You can also specify a regular url to a file, but note that if the server sends a filename header: Content-Disposition ... filename... that it will overwrite whatever you have in the download attribute.

How do I take a converted file (pdf to html), and open it locally in a new tab in google chrome?

Basically I have a django app that communicates with a chrome extension. I have a bunch of functionality that interfaces with normal HTML pages that's all done by the extension. I want to allow users to have the same functionalities for PDF files. I have a python script which translates the pdf file into an html page.
The problem I run into is when the pdfs are open locally within chrome.
Like the following file:///home/wcr5048/Downloads/sample_pdf.pdf
This is my current solution, it basically gets the html and replaces all the current html, which is just an embedded pdf, and replaces it with the converted pdf(html). But I run into an issue because the "url" isn't really a url, and therefore I can't append html to something that doesn't exist.
function convert_to_html(request) {
console.log('converting to html...');
document.getElementsByTagName('html')[0].innerHTML = request.data;
chrome.runtime.sendMessage({
detail: 'refresh'
});
}
What I don't want to happen is to download a file just like the pdf but one that's been converted into html. I would rather have everything happen automatically.
I only see two possible options:
I create a unique link for the converted pdf file for every user, and then send the raw html string to populate the corresponding view.
I somehow tell the extension to use a popup to cover the entire width of the screen, and then populate it with the data.
Are there any suggested solutions that would be a better fit, and if not, which would be a better solution.
Thanks for viewing

Chrome extension: How to show custom UI for a PDF file?

I'm trying to write a Google Chrome extension for showing PDF files. As soon as I detect that browser is redirecting to a URL pointing to a PDF file, I want it to stop loading the default PDF viewer, but start showing my UI instead. The UI will use PDF.JS to render the PDF and jQuery-ui to show some other stuff.
Question: how do I make this? It's very important to block the original PDF viewer, because I don't want to double memory consumption by showing two instance of the document. Therefore, I should somehow navigate the tab to my own view.
As the main author of the PDF.js Chrome extension, I can share some insights about the logic behind building a PDF Viewer extension for Chrome.
How to detect a PDF file?
In a perfect world, every website would serve PDF files with the standard application/pdf MIME-type. Unfortunately, the real world is not perfect, and in practice there are many websites which use an incorrect MIME-type. You will catch the majority of the cases by selecting requests that satisfy any of the following conditions:
The resource is served with the Content-Type: application/pdf response header.
The resource is served with the Content-Type: application/octet-stream response header, and its URL contains ".pdf" (case-insensitive).
Besides that, you also have to detect whether the user wants to view the PDF file or download the PDF file. If you don't care about the distinction, it's easy: Just intercept the request if it matches any of the previous conditions.
Otherwise (and this is the approach I've taken), you need to check whether the Content-Disposition response header exists and its value starts with "attachment".
If you want to support PDF downloads (e.g. via your UI), then you need to add the Content-Disposition: attachment response header. If the header already exists, then you have to replace the existing disposition type (e.g. inline) with "attachment". Don't bother with trying to parse the full header value, just strip the first part up to the first semicolon, then put "attachment" in front of it. (If you really want to parse the header, read RFC 2616 (section 19.5.1) and RFC 6266).
Which Chrome (extension) APIs should I use to intercept PDF files?
The chrome.webRequest API can be used to intercept and redirect requests. With the following logic, you can intercept and redirect PDFs to your custom viewer that requests the PDF file from the given URL.
chrome.webRequest.onHeadersReceived.addListener(function(details) {
if (/* TODO: Detect if it is not a PDF file*/)
return; // Nope, not a PDF file. Ignore this request.
var viewerUrl = chrome.extension.getURL('viewer.html') +
'?file=' + encodeURIComponent(details.url);
return { redirectUrl: viewerUrl };
}, {
urls: ["<all_urls>"],
types: ["main_frame", "sub_frame"]
}, ["responseHeaders", "blocking"]);
(see https://github.com/mozilla/pdf.js/blob/master/extensions/chromium/pdfHandler.js for the actual implementation of the PDF detection using the logic described at the top of this answer)
With the above code, you can intercept any PDF file on http and https URLs.
If you want to view PDF files from the local filesystem and/or ftp, then you need to use the chrome.webRequest.onBeforeRequest event instead of onHeadersReceived. Fortunately, you can assume that if the file ends with ".pdf", then the resource is most likely a PDF file. Users who want to use the extension to view a local PDF file have to explicitly allow this at the extension settings page though.
On Chrome OS, use the chrome.fileBrowserHandler API to register your extension as a PDF Viewer (https://github.com/mozilla/pdf.js/blob/master/extensions/chromium/pdfHandler-vcros.js).
The methods based on the webRequest API only work for PDFs in top-level documents and frames, not for PDFs embedded via <object> and <embed>. Although they are rare, I still wanted to support them, so I came up with an unconventional method to detect and load the PDF viewer in these contexts. The implementation can be viewed at https://github.com/mozilla/pdf.js/pull/4549/files. This method relies on the fact that when an element is put in the document, it eventually have to be rendered. When it is rendered, CSS styles get applied. When I declare an animation for the embed/object elements in the CSS, animation events will be triggered. These events bubble up in the document. I can then add a listener for this event, and replace the content of the object/embed element with an iframe that loads my PDF Viewer.
There are several ways to replace an element or content, but I've used Shadow DOM to change the displayed content without affecting the DOM in the page.
Limitations and notes
The method described here has a few limitations:
The PDF file is requested at least two times from the server: First a usual request to get the headers, which gets aborted when the extension redirects to the PDF Viewer. Then another request to request the actual data.
Consequently, if a file is valid only once, then the PDF cannot be displayed (the first request invalidates the URL and the second request fails).
This method only works for GET requests. There is no public API to directly get response bodies from a request in a Chrome extension (crbug.com/104058).
The method to get PDFs to work for <object> and <embed> elements requires a script to run on every page. I've profiled the code and found that the impact on performance is negligible, but you still need to be careful if you want to change the logic.
(I first tried to use Mutation Observers for detection, which slowed down the page load by 3-20% on huge documents, and caused an additional 1.5 GB peak in memory usage in a complex DOM benchmark).
The method to detect <object> / <embed> tags might still cause any NPAPI/PPAPI-based PDF plugins to load, because it only replaced the <embed>/<object> tag's content when it has already been inserted and rendered. When a tab is inactive, animations are not scheduled, and hence the dispatch of the animation event will significantly be delayed.
Afterword
PDF.js is open-source, you can view the code for the Chrome extension at https://github.com/mozilla/pdf.js/tree/master/extensions/chromium. If you browse the source, you'll notice that the code is a bit more complex than I explained here. That's because extensions cannot redirect requests at the onHeadersReceived event until I implemented it a few months ago (crbug.com/280464, Chrome 35).
And there is also some logic to make the URL in the omnibox look a bit better.
The PDF.js extension continues to evolve, so unless you want to significantly change the UI of the PDF Viewer, I suggest to ask users to install the PDF.js's official PDF Viewer in the Chrome Web Store, and/or open issues on PDF.js's issue tracker for reasonable feature requests.
Custom PDF Viewer
Basically, to accomplish what you want to do you'll need to:
Interject the PDF's URL when it's loaded;
Stop the PDF from loading;
Start your own PDF viewer and load the PDF inside it.
How to
Using the chrome.webRequest API you can easily listen to the web requests made by Chrome, and, more specifically, the ones that are going to load .pdf files. Using the chrome.webRequest.onBeforeRequest event you can listen to all the requests that end with ".pdf" and get the URL of the requested resource.
Create a page, for example display_pdf.html where you will show the PDFs and do whatever you want with them.
In the chrome.webRequest.onBeforeRequest listener, prevent the resource from being loaded returning {redirectUrl: ...} to redirect to your display_pdf.html page.
Pass the PDF's URL to your page. This can be done in several ways, but, for me, the simplest one is to add the encoded PDF URL at the end of your page's url, like an encoded query string, something like display_pdf.html?url=http%3A%2F%2Fwww.example.com%2Fexample.pdf.
Inside the page, get the URL with JavaScript and process and render the PDF with any library you want, like PDF.js.
The code
Following the above steps, your extension will look like this:
<root>/
/background.js
/display_pdf.html
/display_pdf.js
/manifest.json
So, first of all, let's look at the manifest.json file: you will need to declare the permissions for webRequest and webRequestBlocking, so it should look like this:
{
"manifest_version": 2,
"name": "PDF Test",
"version": "0.0.1",
"background": {
"scripts": ["/background.js"]
},
"permissions": ["webRequest", "webRequestBlocking", "<all_urls>"],
}
Then, in your background.js you will listen to the chrome.webRequest.onBeforeRequest event and update the tab which is loading the PDF with the URL of your custom display_pdv.html page, like this:
chrome.webRequest.onBeforeRequest.addListener(function(details) {
var displayURL;
if (/\.pdf$/i.test(details.url)) { // if the resource is a PDF file ends with ".pdf"
displayURL = chrome.runtime.getURL('/display_pdf.html') + '?url=' + encodeURIComponent(details.url);
return {redirectUrl: displayURL};
// stop the request and proceed to your custom display page
}
}, {urls: ['*://*/*.pdf']}, ['blocking']);
And finally, in your display_pdf.js file you will extract the PDF's url from the query string and use it to do whatever you want:
var PDF_URL = decodeURIComponent(location.href.split('?url=')[1]);
// this will be something like http://www.somesite.com/path/to/example.pdf
alert('The PDF url is: ' + PDF_URL);
// do something with the pdf... like processing it with PDF.js
Working Example
A working example of what I said above can be found HERE.
Documentation links
I recommend you to take a look at the official documentation of the above specified APIs, that you can find following these links:
chrome.webRequest API
chrome.webRequest.onBeforeRequest event
chrome.runtime API
chrome.runtime.getURL method

Writing string content as PDF

I have already build functionality to generate pdf file for reports that user view.
So what it currently does is when user clicks to the print pdf button it
Get the html content of the div that needs to be printed
Send this content to the controller's method using jquery ajax method with POST
In the controller it wraps the content with html document strings like <html>, <body> etc. plus I add some styles there.
Then this html string is passed to one of the tools I am using that returns me pdf bytes for this string
Then its saves those bytes as pdf file in a folder and returns the path of this file.
Jquery then on success method opens up the window for this file's path.
This all is working fine.
The problem is
It does not immediately opens up the window as it does all the processing and then on success it opens the window
Plus I am wondering if I am doing this all correctly or doing some extra unnecessary steps, from this I mean is there any better way or short way to do this.
Something like after getting content of div make some changes to the string to directly show it in the new window as pdf content etc. to avoid server processing, is that possible?
Till now I have tried to show the content directly with data:application/pdf but that didn't work.
If that is not possible, I am thinking to avoid saving of pdf file but just show the view that will open up as pdf, may be by setting its content-type, is that possible?
What you did is the best approach. (All) browsers don't have the capability to convert html to pdf so you can't just order them to open a page as pdf. You must serve the pdf file from the server. For more control you can serve the file from a script at a specified url and add appropriate headers:
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="the.pdf"'); // second parameter is the name of the file
Content type means browser will try to open it with a program appropriate for this MIME type.
Content Disposition inline means that browser will try to open it in the browser.
As server is working just display "loading" image to the user. That way the user will know that something is happening and that he needs to wait.

Saving file from JavaScript string without hitting server

If I have an in-memory string in JavaScript that is let's say Excel or PDF format, and I want to pop open a save dialog so the user can save those bytes to a file, how would I go about doing this? I am trying to avoid going back to the server. If I was going back to the server I could send the correct HTTP headers in the response to tell the browser that I'm sending a file. But I want to do this from JavaScript instead because I already have the bytes I need on the client.
Is this possible?
Edit:
I should clarify what I'm actually looking for here. I am working with a Silverlight app. From Silverlight, I can pop up a save dialog and save the bytes (in this case, let's say they are Excel bytes). This seems to be what people are suggesting below when they suggest using Flash. Silverlight gives the same functionality.
But, I would prefer the the Excel file just opens in a new browser window. I could do that pretty easily if I was generating the file on the server, because I could just send the correct headers. But I already have the bytes in Silverlight on the client. Any way to open that doc in a new browser window so the user can just hit an Open button without having to pick a save location and navigate to the file?
And I can't use the out-of-browser application option. I know it would be possible using that by talking with Excel through COM-interop. But that's a no go in this case.
But I can interop with JavaScript from Silverlight. So I was hoping I could use JavaScript in some way to open a browser window and stream the Excel bytes to it.
You can use data URIs to embed the file in the HTML document; e.g., http://jsfiddle.net/dqWae/ creates a link that initiates a download of the Wikipedia title image. (The MIME type is hard coded as application/octet-stream but you can of course specify it as PDF or XLS).
You will need to encode the bytes of the file as base 64 and create a data URI for the resource. Then, create a new anchor element whose href attribute is the data URI. If you want to automatically initiate the download, programmatically issue a click event to the anchor element.
In JavaScript? I hope not, think of all the millions of security implications that would cause..
In pure javascript this will be possible only with html5 but not for now.
but you can do some javascript/flash 10 bridge, you pass the bytes to Flash who open the "save as" dialog and then you can save 100% client side.
The flash can be loaded dynamically.
see some code here : http://sujitreddyg.wordpress.com/2008/11/04/filereference-in-flash-player-10/
There are one non cross-browser solution (works only in Firefox, and only when user grant permissions).
// ask for security grants
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var pngBinary = 'some string';
var aFile = Components.classes["#mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
aFile.initWithPath( "/tmp/somefile.png" );
aFile.createUnique( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 600);
var stream = Components.classes["#mozilla.org/network/safe-file-output-stream;1"].
createInstance(Components.interfaces.nsIFileOutputStream);
stream.init(aFile, 0x04 | 0x08 | 0x20, 0600, 0);
stream.write(pngBinary, pngBinary.length);
if (stream instanceof Components.interfaces.nsISafeOutputStream) {
stream.finish();
} else {
stream.close();
}
But I recommend you to make cross-browser applications and choose Flash solution.

Categories

Resources