I have one URL which will ask Open/Save PDF when we browse it. I need to convert this pdf to Convert.ToBase64String in Javascript. I have one simple URL which have the PDF.
The URL is like
This
Let me know if you need anything else.
Define div to create the link inside it
<div id="getpdf">
<i>Generating PDF file, please wait..</i>
</div>
Then convert your PDF file containted in PDFAsString variable and create the inline datauri link like this to show this PDF inline:
// create base 64 encoded string
var PDFContentBase64 = btoa(unescape(encodeURIComponent(PDFAsString))));
var pdfdiv = document.getElementById("getpdf");`
pdfdiv.innerHTML = "<h3><a title=\"View PDF file\" href=\"data:application/pdf;base64,' + PDFContentBase64 + '\">Click here to VIEW PDF<\/a></h3>";`
UPDATE: (thanks to #roland) If you need to support IE8 and older browsers then consider N. Zackas's implementation of base64 encoding.
Related
I have a base64 pdf that I get from external system.
I want to be able to download this pdf in IE9 with JavaScript and this is a problem since IE9 doesn't support DATA URI for pdf.
Please help me.
Thanks!
You should use Adobe Flash based plugin Downloadify (see the demo) to allow users download file in IE9.
You may check if the current browser supports dataURI or not using the following js function:
function CheckDataURISupport(){
var result = true;
var checkDataURISupportImage = new Image();
checkDataURISupportImage.onload = checkDataURISupportImage.onerror = function(){
if(this.width != 1 || this.height != 1){
result = false;
}
}
checkDataURISupportImage.src = "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=";
// check if we have datauri support in current browser - end
return result;
}
Downloadify.js is a great solution for your case. Just be careful with options. There should be
'dataType': 'base64'
'data:' string representation of pdf in base64 format
Also be sure that your link/button has inserted 'flash code' by downloadify plugin (check source code after downloadify.create() initialization). Also you can check if your base64 has data:application/pdf;base64, type at the beginning.
I have some text data (say var a = 'Hello World From Javascript';)in javascript variable in current window. I want to do the following
through javascript-
1. open a new window and write the text data to the window.
2. set the content type to text/plain.
3. set the content-disposition to attachment, so that download prompt comes.
4. user downloads the text data as a text file and saves it to his local disk.
is this all possible through javascript?
I know we can make ajax calls to server or redirect but in this case instead of following above steps. But in this case, these workarounds are not adaptable.
you can do that using JS & HTML5 features. Please find below a sample code.
var fileParts = ['Hello World From Javascript'];
// Create a blob object.
var bb = new Blob(fileParts,{type : 'text/plain'});
// Create a blob url for this.
var dnlnk = window.URL.createObjectURL(bb);
var currentLnk = $('#blobFl').attr('href');
// blobFl is the id of the anchor tag through which the download will be triggered.
$('#blobFl').attr('href',dnlnk);
$('#blobFl').attr('download','helloworld.txt');
// For some reason trigger from jquery dint work for me.
document.getElementById('blobFl').click();
Triggering a file download without any server request
Unfortunately this is not something you can do with normal browser capabilities. Something like flash or a browser-specific plugin will get you what you need, but security limitations within javascript will not let you download arbitrary data created within the browser.
Also the 'data' url is not supported across all browser/version combinations. I am not sure if your users are constrained on what browser they are using or not but that may limit what you can do with that solution.
Source: Triggering a file download without any server request
If you already have the file on the server (I make an ajax call to generate and save a PDF on the server) - you can do this
window.location.replace(fileUrl);
No, Content-Disposition is a response header, it has to come from the server. I think you could do it with Flash but I wouldn't recommend it.
Here's a clean, pure js version of #Rajagopalan Srinivasan's answer:
var fileParts = ["Hello World From Javascript"];
// The anchor tag to use.
const blobLink = document.getElementById("blobLink");
// Create a blob object.
var blob = new Blob(fileParts, { type: "text/plain" });
// Create a blob url for this.
var blobUrl = window.URL.createObjectURL(blob);
blobLink.setAttribute("href", blobUrl);
blobLink.setAttribute("download", "helloworld.txt");
blobLink.click();
<a id="blobLink">Download</a>
This question already has answers here:
How to create a file in memory for user to download, but not through server?
(22 answers)
Closed 6 years ago.
Typically, HTML pages can have link to documents (PDF, etc...) which can be downloaded from the server.
Assuming a Javascript enabled webpage, is it possible to dynamically create a text document (for example) from within the user browser and add a link to download this document without a round trip to the server (or a minimal one)?
In other word, the user would click on a button, the javascript would generate randoms numbers (for example), and put them in a structure. Then, the javascript (JQuery for example) would add a link to the page to download the result as a text file from the structure.
This objective is to keep all (or at least most) of the workload on the user side.
Is this feasible, if yes how?
Here's a solution I've created, that allows you to create and download a file in a single click:
<html>
<body>
<button onclick='download_file("my_file.txt", dynamic_text())'>Download</button>
<script>
function dynamic_text() {
return "create your dynamic text here";
}
function download_file(name, contents, mime_type) {
mime_type = mime_type || "text/plain";
var blob = new Blob([contents], {type: mime_type});
var dlink = document.createElement('a');
dlink.download = name;
dlink.href = window.URL.createObjectURL(blob);
dlink.onclick = function(e) {
// revokeObjectURL needs a delay to work properly
var that = this;
setTimeout(function() {
window.URL.revokeObjectURL(that.href);
}, 1500);
};
dlink.click();
dlink.remove();
}
</script>
</body>
</html>
I created this by adapting the code from this HTML5 demo and messing around with things until it worked, so I'm sure there are problems with it (please comment or edit if you have improvements!) but it's a working, single-click solution.
(at least, it works for me on the latest version of Chrome in Windows 7)
By appending a data URI to the page, you can embed a document within the page that can be downloaded. The data portion of the string can be dynamically concatenated using Javascript. You can choose to format it as a URL encoded string or as base64 encoded. When it is base64 encoded, the browser will download the contents as a file. You will have to add a script or jQuery plugin to do the encoding. Here is an example with static data:
jQuery('body').prepend(jQuery('<a/>').attr('href','data:text/octet-stream;base64,SGVsbG8gV29ybGQh').text('Click to download'))
A PDF file? No. A txt file. Yes. With the recent HTML5 blob URIs. A very basic form of your code would look something like this:
window.URL = window.webkitURL || window.URL;
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
var file = new window.BlobBuilder(),
number = Math.random().toString(); //In the append method next, it has to be a string
file.append(number); //Your random number is put in the file
var a = document.createElement('a');
a.href = window.URL.createObjectURL(file.getBlob('text/plain'));
a.download = 'filename.txt';
a.textContent = 'Download file!';
document.body.appendChild(a);
You can use the other methods mentioned in the other answers as a fallback, perhaps, since BlobBuilder probably isn't supported very well.
Demo
Note: BlobBuilder seems to be deprecated. Refer to this answer to see how to use Blob instead of BlobBuilder. Thanks to #limonte for the heads up.
I want to modify through the dom various element properties and then save that page as an html file. View source doesn't always reflect dom adjustments. Is there a way to write the whole page to a file or otherwise get the updated source page into a file?
I'm thinking this should do the trick for ya.
$('html').html();
JavaScript can't write files when being ran from a browser (security). But you can send this to a PHP script and write it to a file from there. For example:
$.post('write.php', { dom : $('html').html() });
write.php
file_put_contents('new.html', urldecode($_POST['dom']));
In newish browsers (IE 10, FF 20, Chrome 26, Safari 6, Opera 15), you can create a Blob and save it into a file using window.URL.createObjectURL.
Demo, Reference:
objectURL = window.URL.createObjectURL(blob);
Where blob is a File object or a Blob object to create a URL object for.
objectURL is the generated object URL. The entire contents of the specified file are represented by the text of the URL. It can then be used in window.open.
Example of a Blob:
var parts = ["<p class=\"paragraph\"><a id=\"link\">hey!<\/a><\/p>"];
new Blob(parts, { "type" : "text\/html" });
To list current Blobs in Chrome execute the following in your address bar:
chrome://blob-internals
I am writing an Adobe Air app in HTML/JavaScript and I am trying to base64 encode an image so I can add it to and XML RPC request. I have tried many methods and nothing seems to work.
I see that actionscript has a Base64Encoder class that look like it would work, is there any way to utilize this in JavaScript?
Thanks #some for the link.
I used the btoa() function to base64 encode image data like this:
var loader = new air.URLLoader();
loader.dataFormat = air.URLLoaderDataFormat.BINARY;
loader.addEventListener(air.Event.COMPLETE,function(e){
var base64image = btoa(loader.data);
});
var req = new air.URLRequest('file://your_path_here');
loader.load(req);
I was trying to upload an image using metaWeblog.newMediaObject, but it turns out that the data doesn't need to be base64 encoded, so the binary value was all that was needed.