I have the following code:
let self = this;
this.chunks = [];
const canvas2 = document.getElementById("self-canvas");
let recordStream = canvas2.captureStream(1);
var options;
options = {mimeType: 'video/webm; codecs=vp9'};
this.recorder = new MediaRecorder(recordStream, options);
this.recorder.ondataavailable = function(evt) {
self.chunks.push(evt.data);
};
this.recorder.onstop = function(evt) {
console.log("recorder stopping");
const link = document.createElement('a');
const videoBlob = new Blob(self.chunks, { type: "video/webm" });
console.log("file size: " + videoBlob.size);
const url = URL.createObjectURL(videoBlob);
link.href = url;
link.download = "sample.webm";
document.body.append(link);
link.click(); //if I comment out here I can see the video
};
console.log("finished setting controller")
console.log("recorder starting");
this.recorder.start(10000);
// the recorder.stop is called somewhere else
What it is supposed to do is pretty simple:
I have the element with id "self-canvas" that is showing my camera.
Now I am trying to record the camera and download the video from the browser using MediaRecorder, but for some reason I am unable to download the file.
I am sure that the file is being recorded, and console.log("file size: " + videoBlob.size); does not return empty.
But when I let the code run, instead of downloading the file, it tries to open it on the same window, and I cannot even see the video because the previous window disappears with the data of the recording.
However if I comment out the link.click(); I am able to see the video by opening the link on a new page (without closing the previous one). But it still doesn't download...
I used this as example, what am I doing wrong?
For heaven's sake...
I just added target blank and it worked.
link.href = url;
link.download = "sample.webm";
link.target = '_blank';
Probably because the resources are lost if it tries to open on the same page, and because it doesn't actually download the file if it is not a link "click".
Still, I never saw anyone having to add target blank in their examples like this one.
So I wonder why this is the case only for me...
I have the following Angular code to download a PDF document. It works fine in other browsers but in Firefox when browser settings are set to "Open in Firefox" for PDF download then it doesn't open a new tab.
const blob = new Blob([data], { type: docType });
const blobDoc = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = blobDoc;
link.download = 'Filename.pdf';
link.click();
What I want is that in case of Firefox the link must always be open in a new tab. Even if when I set the target attribute, it doesn't open the new tab.
link.target = '_blank'
I tried the following and it works but then I do not get the file name.
const agent = window.navigator.userAgent.toLowerCase();
if (agent.indexOf('firefox') > -1) {
window.open(blobDoc, '_target');
} else {
// Normal download
}
I want to use mp3 playing in my mobile web app, so I wrote a test app, I used this solution but blob URL seems to be broken and empty while file is rightly readed.
<input type="file" accept=".mp3" onchange="autoplay()">
<script>
var file, url, audio, source;
function autoplay(){
window.URL = window.URL || window.webkitURL;
file = document.querySelector("input[type=file]").files[0];
url = decodeURIComponent(window.URL.createObjectURL(file));
audio = document.createElement("audio");
source = document.createElement("source");
source.src = url;
audio.appendChild(source);
document.body.appendChild(audio);
audio.play();
}
</script>
Blob size is wrong, I've put bigger file
EDIT:
I used older version with FileReader, maybe this is not good choice but it works...
Don't use decodeURIComponent just do URL.createObjectURL
window.URL = window.URL || window.webkitURL;
function autoplay(evt) {
var file = document.querySelector("input[type=file]").files[0];
var url = URL.createObjectURL(file);
var audio = new Audio();
audio.src = url;
audio.play().catch(function(err){
console.error(err) // could not play audio
});
audio.controls = true;
document.body.appendChild(audio);
}
document.querySelector("input[type=file]").onchange = autoplay
<input type="file" accept=".mp3">
btw, I get problem playing it directly, it's weird since the event.isTrusted is true, that's why i appended the audio to the DOM
I have URL of pdf file for exa url is "test.example.com/incoice/1/download?auth_token="some_token", when I visit this url, url will show me PDF in browser.
Now I want to open this pdf with print function, I mean user do not have to press CTRL+P I want to do this from my side.
I tried iframe but it gives me error of cross origin.
This is demo code which i used
//first try
let _printIframe;
var iframe = _printIframe;
if (!_printIframe) {
iframe = _printIframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.id = "printf";
iframe.name = "printf";
iframe.onload = function() {
setTimeout(function() {
iframe.focus();
iframe.contentWindow.print();
}, 1);
};
}
// second try
// SRC of pdf
iframe.src = "Some API URl " + "/download?access_token=" +
this.authenticationService.currentTokenDetails.access_token;
let url = iframe.src + "&output=embed";
window.frames["printf"].focus();
window.frames["printf"].print();
var newWin = window.frames["printf"];
newWin.document.write('<body onload="window.print()">dddd</body>');
newWin.document.close();
I created a demo in plunker for print pdf. http://embed.plnkr.co/WvaB9HZicxK6tC3OAUEw/ In this plunker i open pdf in new window but i want to directly print that pdf. how can i do that ?
Any suggestion will be appreciate, and you can correct if I am wrong.
Thanks
So here I got the solution for my problem
In my situation my API was returning binary data of pdf, and browser did not print that binary data into window.print, so for this first I convert binary data in blob data and then create Iframe for print
Following is code for it.
const url = request URL // e.g localhost:3000 + "/download?access_token=" + "sample access token";
this.http.get(url, {
responseType: ResponseContentType.Blob
}).subscribe(
(response) => { // download file
var blob = new Blob([response.blob()], {type: 'application/pdf'});
const blobUrl = URL.createObjectURL(blob);
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = blobUrl;
document.body.appendChild(iframe);
iframe.contentWindow.print();
});
Here you go!!
I hope this can help anyone have this problem :)
The previous solution may cause some security issues in newer browsers so we need to use the DOMSanitizer to make it a safe resource.
export class PrintPdfService {
constructor(protected sanitizer: DomSanitizer) {}
printPdf(res) {
const pdf = new Blob([res], { type: 'application/pdf' });
const blobUrl = URL.createObjectURL(pdf);
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = this.sanitizer.sanitize(SecurityContext.RESOURCE_URL, this.sanitizer.bypassSecurityTrustResourceUrl(blobUrl));
document.body.appendChild(iframe);
iframe.contentWindow.print();
}
}
Angular DOMSanitizer
Look at https://github.com/devintyler/real-time-angular2/tree/master/plugin/print-pdf
simple and nice implementation.
I am getting following response which is in json format
{"filename":"copyofabc.pdf","filedata":[37,80,68,70,45,49,46,53,13,10,37,-75,-75,-75,-75,13,10,49,32,48,32,111,98,106,13,10,60,60,47,84,121,112,101,47,67,97,116,97,108,111,103,47,80,97,103,101,115,32,50,32,48,32,82,47,76,97,110,103,40,101,110,45,73,78,41,32,47,83,116,114,117,99,116,84,114,101,101,82,111,111,11.....]}
enter code here
var blob = new Blob($(this).attr('filedata'), {
type: 'application/pdf'
});
var objectURL = URL.createObjectURL(blob);
// Create an iframe to demonstrate it:
var iframe = document.createElement('iframe');
iframe.className = 'sample-iframe';
iframe.src = objectURL;
document.body.appendChild(iframe);
above code i am using to display pdf from byte array
This works for me on Chrome, but not on IE:
// base64DataFromWebAPI comes from a Web API, in the form of base 64 string
var pdfData = base64DataFromWebAPI;
var x = window.open();
var iframe = x.document.createElement('iframe')
iframe.width = '100%'
iframe.height = '100%'
iframe.frameBorder = 0
iframe.style = "border: 0"
iframe.src = "data:application/pdf;base64, " + pdfData
x.document.body.appendChild(iframe);
I got it from the following Stack Oveflow question: JsPDF - Not allowed to navigate top frame to data URL
Using Chrome*, you can also simply paste the following code in the address bar:
data:application/pdf;base64, YOUR_PDF_DATA_HERE
It will open it in the included PDF viewer of the browser.
*didn't tested other browsers