Bellow I have attach my code.
I am trying to print the excel file using angular with out user pressing the ctrl+P. I did found the relevant code in below link and I am able to open the print popup but with just blank white page with no content on it. Thank you for you suggestions in advance.
printListXcel() {
this.listService.getListExcel(this.ListId).subscribe(data => {
const blobData = new Blob([data], {
type:'application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet'});
const blobUrl = URL.createObjectURL(blobData);
const iframexcel = document.createElement('iframe');
iframexcel.style.display = 'none';
iframexcel.src = blobUrl;
document.body.appendChild(iframexcel);
iframexcel.contentWindow.print();
});
}
how to print pdf in Angular 2
Related
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 want to paste image from my clipboard to whatsapp chat from clipboard i tried using document exec command with different parameters like insertHTML , insertImage these two add image in content editable div but does not enable the send button. I also tried using document exec command paste but its pasting nothing. I double checked and images exists on clipboard.
async function sendToChat(blob) {
setToClipboardImg(blob)
try {
document.querySelector('._6h3Ps ._13NKt').focus()
} catch (e) {
document.querySelector('textarea').focus()
}
// const data = [new ClipboardItem({
// [text.type]: text
// })]
// await navigator.clipboard.write(data)
document.execCommand("Paste", null, null);
//setToClipboardWithTextInsta()
}
var setToClipboardImg = async blob => {
window.focus();
const data = [new ClipboardItem({
[blob.type]: blob
})]
await navigator.clipboard.write(data);
}
I needed exactly the same funcionality, I was able to resolve it using html2canvas, you can convert an html element into an image and then send it through whatsapp from the clipboard, here is how I implemented it:
document.querySelector("#btn").onclick(function () {
var table = document.querySelector("#table");
var elementContainer = document.querySelector("#previewImage");
try {
// Prevent duplicates since the element will be appended to the container
if (elementContainer.innerHTML) {
elementContainer.innerHTML = "";
}
html2canvas(table).then(canvas => {
elementContainer.appendChild(canvas);
canvas.toBlob(blob => navigator.clipboard.write([new
ClipboardItem({'image/png': blob})]));
alert('😁 The screenshot for the table currently displayed was copied to the clipboard, you can now paste into the WhatsApp chats 😁');
});
}
catch(err){
document.querySelector("#output").innerHTML = err.message;
}
}
Then in the head of the document add the following cdn:
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
I am making a PDF Viewer. I am using ADOBE View SDK. I have a File input but the problem is that I want to show the file in different views - Full Screen, Half Screen and In-Line. But when the user selects a file and selects a different view the whole page reloads and then the user has to select the file again. I don't want the user to select the file again.
File Input:
<input type='file' onchange="listenForFileUpload(this);" id="file-picker" accept="application/pdf">
listenForFileUpload function:
var fileToRead = document.getElementById("file-picker");
fileToRead.addEventListener("change", function (event) {
var files = fileToRead.files;
var input = document.getElementById('file-data').value
input = files
console.log(files)
document.getElementById('file-form').submit()
if (files.length > 0 && isValidPDF(files[0])) {
var fileName = files[0].name;
var reader = new FileReader();
reader.onloadend = function (e) {
var filePromise = Promise.resolve(e.target.result);
previewFile(filePromise, fileName);
};
reader.readAsArrayBuffer(files[0]);
}
}, false);
}
Please help me to change the view without reloading.
It's this line here:
document.getElementById('file-form').submit()
You are submitting the form there. I'd just remove it.
im new to angular and i have to add a button to an app so when i click, it should start downloading a file already recorded.
i have this code
var _RecordStopCallback = function(blob){
if (!blob && blob.length==0){
$scope.isRecorded = false;
return;
}
$scope.recordObj.recordedData = blob;
const url = URL.createObjectURL(blob);
var el = $("#downloads").html("");
var hf = $("<a></a>");
hf.attr({
src:url,
href:url,
download:$scope.recordFilename
}).html($scope.recordFilename);
hf.appendTo(el);
$scope.isStoping = false;
$scope.recordStatus = false;
$scope.isRecorded = true;
$scope.recordStatusText = "Start";
$scope.streamError = "";
_changeStatusText();
$scope.$apply();
$scope.saveProcess();
and in the HTML file this:
<div ng-show="isRecorded" class="color-info"> Recorded File : <span id='downloads'></span>
<button ng-click="{{recordFilename}}" class="btn-circle btn-circle-default">
<i class="zmdi zmdi-download"></i></button>
this line:
<span id='downloads'></span>
displays the recoded filename and makes it as a link so when you click on it you can directly donwload it, but i dont know how to make the button do the same thing?
any help would be appreciated!
You may register a callback for the button getting clicked and there you can create the same link you showed in your question, style it as hidden, insert it into the DOM and call .click() on it.
Inserting into DOM is required as some browsers will not start the download otherwise.
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.