I have this QR code generator that I pieced together from tutorials across the web. You can see it here. It replaces an image src in a div with the QR code generated from Google API based on input from the user, so doing doesn't work, as the link is dynamic. Is there a way to download the image from a button?
I didn't know what part of the code to attach to make it clear, so if you want to see the entire code, visit the GitHub repository: https://github.com/troop129/tarbiya/blob/main/index.html
Thanks for your help!
Not only it is possible to 'download the image from a button', but you can also download the image immediately after the API responds and then display it from a local URL.
const url = 'https://picsum.photos/200/300';
const target = document.getElementById('target');
const link = document.getElementById('download');
const xhr = new XMLHttpRequest();
xhr.addEventListener('loadend', (e) => {
const blobUrl = URL.createObjectURL(e.target.response);
target.src = blobUrl;
link.href = blobUrl;
link.download = 'image.jpg';
});
xhr.responseType = 'blob';
xhr.open('GET', url);
xhr.send();
<img id='target'></img>
<a id='download'>Download</a>
Related
I have looked at a few posts on here about pdfkit and embedding fonts but most seem to use the node version or ruby / something that looks vastly different than what I am doing.
I have everything but the fonts working as expected. However when I enable a custom font no text appears. I see placeholders and bullet points for lists but other than that, nothing.
<html>
<head>
<script src="https://github.com/foliojs/pdfkit/releases/download/v0.11.0/pdfkit.standalone.js"></script>
<script src="https://github.com/devongovett/blob-stream/releases/download/v0.1.3/blob-stream.js"></script>
<script type="text/javascript">
//getting the arraybuffer of the font I need
var xhr = new XMLHttpRequest;
xhr.onload = function() {
console.log("Font IS 1",xhr.response)
};
xhr.responseType = 'arraybuffer';
xhr.open('GET', 'https://fonts.gstatic.com/s/cormorantgaramond/v9/co3bmX5slCNuHLi8bLeY9MK7whWMhyjYqXtK.woff2', true);
xhr.send();
//wix method that starts when a UI element is called. In this case a "download" button
window.onmessage = (event) => {
if (event.data) {
// create a document and pipe to a blob
var doc = new PDFDocument();
var stream = doc.pipe(blobStream());
doc.font(xhr.response)
//The standard way of setting a font for embedded
//doc.font('Helvetica')
doc.fontSize(20)
doc.text('Стартовая Страница',200,120)
doc.text('Test',200,220)
doc.list(['Стартовая Страница'],50,50)
doc.list(['TestList'],50,400)
// end and display the document in the iframe to the right
doc.end();
stream.on('finish', function() {
const blob = stream.toBlob('application/pdf')
const a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = "ShoppingList";
a.style.position = 'fixed';
a.target = '_blank';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
});
};
</script>
</head>
<body>
</body>
</html>
I have tried several different methods but most help seems to be suggesting CSS which I don't see how I can use here. Unfortunately I am unable to upload a font to my own filesystem to use as the site where I am building it blocks upload of fonts for some reason. This is why I went with the google fonts as I didn't run into CORS issues.
I directly linked to the woff2 file as getting an arraybuffer using any of the other methods google recommends doesn't seem to work. As a note I will be using both Latin and Cyrillic characters so this might be an issue since they are separate character sets it appears
Here is where I was getting the links from
https://fonts.googleapis.com/css2?family=Cormorant+Garamond&display=swap
Also when I try opening the pdf I get this error
Cannot extract the embedded font 'BZZZZZ+CormorantGaramond-Regular'. Some characters may not display or print correctly
When I look at the registered fonts in the pdf it appears to show how it shows for other fonts
Is there some other way I should be trying to register this font to the document?
It seems that you can't directly embed any of the "woff2" files served by google fonts. You have to find the otf or ttf files that are available in the github repo.
You can find the files you need here: https://github.com/CatharsisFonts/Cormorant/tree/master/1.%20TrueType%20Font%20Files
Just download a file and then copy and paste the download link. So:
xhr.open('GET', 'https://fonts.gstatic.com/s/cormorantgaramond/v9/co3bmX5slCNuHLi8bLeY9MK7whWMhyjYqXtK.woff2', true);
should be:
xhr.open('GET', 'https://raw.githubusercontent.com/CatharsisFonts/Cormorant/master/1.%20TrueType%20Font%20Files/Cormorant-Regular.ttf', true);
User click on the button on the webpage to download the file, i want to track the file is being downloaded to the user machine or not using client side code like javascript/JQuery.
On button click, ASP.NET .ASHX Web handler code is called which return the file to be downloaded.
Also can we check using javascript/JQuery whether the user is having issue (security, firewall etc.) in downloading the file, when user click on the download button on the webpage.
This can be done via the "progress" event that is attached to an AJAX request.
let xhr = new XMLHttpRequest();
xhr.addEventListener("progress",event=>{
console.log(`${event.loaded} out of ${event.total}`);
});
The download can then be handled via AJAX by creating a false link that links to the file data which will be saved in memory:
xhr.onreadystatechange(function(){
if(this.readyState==4 && this.status==200){
//Download content via imaginary link with data saved in memory
var a = document.createElement('a');
var url = window.URL.createObjectURL(this.response);
a.href = url;
a.download = 'myfile.pdf';
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
}else if(this.status==404){
console.error("page not found");
}
});
xhr.open("GET","myfile.pdf",true);
xhr.responseType = "blob";
xhr.send();
I am trying to download a file with JavaScript and not let it open in a new tab or window.
What I have so far is this:
var link = document.createElement("a");
link.download = filename;
link.href = fileurl;
link.click();
I've been doing a fair bit of research about this but cannot find anything that works because the file is coming from a Google Signed URL which I have no control over and cannot modify headers for.
This has to happen in client side JavaScript/jQuery.
Edit
It is actually dynamic so there can be X number of files, if I could get them all to download as a zip that would be even better.
for(var i=0; i<filenames.length; i++){
var formData = new FormData();
formData.append('filename', filenames[i]);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
fileurl = this.responseText;
var link = document.createElement("a");
link.download = filenames[i];
link.href = fileurl;
link.click();
}
}
xmlhttp.open("POST", "url_to_get_download_urls");
xmlhttp.send(formData);
}
Have you tried doing the download action in different browsers? In the latest versions of Chrome, you cannot download cross-origin files (they have to be hosted on the same domain).
As well if the file doesn't change, have you tried hosting the file yourself and initiating the download?
edit: If you're trying to bundle the items into a zip for download, that would necessitate doing the initial download on your own server and zipping there.
I'm trying to create a web application for videos, I decided to start by configuring the videos, in case of problem, creating blob url for videos.
It turns out that I'm not sure what terms to use to search in google and the ones I used do not find anything very simple or straightforward.
I would like to know how I can create a blob url for videos and what would be the best way, since I have already seen topics using FileReader and MediaSource and some others, so I would like to know the simplest way to do this.
I'm testing on a direct html, without external libraries or external files.
var URL = this.window.URL || this.window.webkitURL;
var file = new Blob(["http://localhost/assets/mp4/video.mp4"],{"type" : "video\/mp4"});
var value = URL.createObjectURL(file);
$(document).ready(function(){
$('#MyVideo').attr('src',value);
});
Generates a blob link but does not load the video
Edit:
For further questions from beginners like me, I got the expected result with the script below:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/assets/mp4/video.mp4');
xhr.responseType = 'arraybuffer';
xhr.onload = function(e){
var blob = new Blob(([xhr.response]));
var url = URL.createObjectURL(blob);
document.getElementById('_video').src = url;
};
I'm trying to create a download link in an angular app that makes data in a model downloadable as a CSV file. I have it all working except for the actual download link. Using filesaver.js is blowing up unit tests in Karma so I'm exploring just doing it manually.
Below is what I have. In the controller:
var blob = new Blob([data.join('\n')], {type: 'text/csv;charset=utf-8'});
$scope.downloadUrl = URL.createObjectURL(blob);
In the view, I have:
<a ng-href="{{downloadUrl}}" download="ttester.csv" id="download">Download</a>
The issue is this opens a new page in Firefox 20 with the URL "unsafe:blob:af775c64-dcb1-864a-8eaa-adebe7f101a7", notice the "unsafe:" prefix. Removing that prefix downloads the data correctly, but without the filename I want.
What am I missing in my hyperlink to make it work? I expect it to open a download dialog with the filename tester.csv for the file.
Really appreciate any help
You could use the following code that will create the blob, a fake link and will dispatch a click event on this fake link. Note that no new page should be opened but you will be directly prompted with the save dialog box.
var blob = new Blob([data.join('\n')], {type: 'text/csv;charset=utf-8'});
var url = window.URL || window.webkitURL;
var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
link.href = url.createObjectURL(blob);
link.download = 'teams.csv'; // whatever file name you want :)
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, false);
link.dispatchEvent(event);
You can see a working Fiddle here