I am going to print an Image (embeded as a property into an object), which retrieved from a WebApi.
So far, I could load the image and show it perfectly on my page like the following:
<img ng-src="data:image/jpeg;base64,{{t.Image}}"/>
However the problem is I don't know how can I print this image?
I have tried out the following listing but I am faced with crashed google chrome page.
var img= window.open($scope.t.Image);
img.print();
Question is How can I print the Image?
This is my Object coming from WebApi:
public class TestImage
{
public string Name { get; set; }
public byte[] Image { get; set; }
}
and the following is how I call the Get method:
$scope.getData = function (val) {
return $http.get('http://localhost:2740/GetData', {
params: {
name: val
}
}).then(function (response) {
$scope.t = response.data;
return response.data;
});
};
********UPDATED********
$scope.imgName = "myImage";
$scope.print = function () {
var printContents = document.getElementById($scope.imgName);
var popupWin = window.open('', '_blank', 'width=300,height=300');
popupWin.document.open();
popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</html>');
popupWin.document.close();
}
<img id="{{imgName}}" ng-src="data:image/jpeg;base64,{{t.Image}}" />
Sorry I misread your question...
Try this ... You will need to assign and ID to the image tag.
$scope.printImg = function(imgName) {
var printContents = document.getElementById(imgName);
var popupWin = window.open();
popupWin.document.open()
popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</html>');
popupWin.document.close();
}
Related
I'm trying to implement a functionality in a website so a user can save the contact details from a website to their phone (android/iPhone) by clicking on an HTML button.
This is what I tried so far
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="save-btn">Save Contact</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
var saveBtn = document.getElementById("save-btn");
saveBtn.addEventListener("click", function () {
// Get the contact information from the website
var contact = {
name: "John Doe",
phone: "111551144111",
email: "john#doe.com"
};
// create a vcard file
var vcard = "BEGIN:VCARD\nVERSION:4.0\nFN:" + contact.name + "\nTEL;TYPE=work,voice:" + contact.phone + "\nEMAIL:" + contact.email + "\nEND:VCARD";
var blob = new Blob([vcard], { type: "text/vcard" });
var url = URL.createObjectURL(blob);
saveBtn.href = url;
saveBtn.download = contact.name + ".vcf";
});
For testing purpose, I uploaded this on a webserver but nothing is happening.
https://cheery-taiyaki-477ee0.netlify.app
You are very close. The trick is to make a new link and set that to your stuff, then click that:
var saveBtn = document.getElementById("save-btn");
saveBtn.addEventListener("click", function () {
// Get the contact information from the website
var contact = {
name: "John Smith",
phone: "555-555-5555",
email: "john#example.com"
};
// create a vcard file
var vcard = "BEGIN:VCARD\nVERSION:4.0\nFN:" + contact.name + "\nTEL;TYPE=work,voice:" + contact.phone + "\nEMAIL:" + contact.email + "\nEND:VCARD";
var blob = new Blob([vcard], { type: "text/vcard" });
var url = URL.createObjectURL(blob);
const newLink = document.createElement('a');
newLink.download = contact.name + ".vcf";
newLink.textContent = contact.name;
newLink.href = url;
newLink.click();
});
Demo: https://codepen.io/cjhaas/pen/jOpYYvq
I am trying to print a specific content area of my page. My problem is I have created separate CSS file for the content of this print area. But that external CSS is not working (loading) in browser print popup. I am sure file path is correct.
This is how I tried it:
function printReceipt(el) {
var docHead = "<html>\
<head>\
<title></title>\
<link rel='stylesheet' href='css/receipt-print.css' type='text/css' media='print' />\
</head>\
<body>";
var docFoot = " </body>\
</html>";
var docBody = document.getElementById(el).innerHTML;
var defaultBody = document.body.innerHTML;
document.body.innerHTML = docHead+docBody+docFoot;
//document.close();
//window.focus();
//setTimeout(function() {
window.print();
document.body.innerHTML = defaultBody;
//}, 1000);
//return true;
}
UPDATE:
Also check in this way. Problem is sill same.
function printReceipt(el) {
var w = window.open();
w.document.write('<html><head><title></title>');
w.document.write('<link rel="stylesheet" type="text/css" href="css/receipt-print.css">');
w.document.write('</head><body >');
w.document.write(document.getElementById(el).innerHTML);
w.document.write('</body></html>');
w.document.close();
w.focus();
w.print();
w.close();
return true;
}
Any ideas and suggestion would be appreciated.
The issue was you were printing the page without waiting for the styles and resources to load.
You should wait for the page to load before trying to print it or you can try using inline styles.
function printReceipt(el) {
var w = window.open();
w.document.write('<html><head><title></title>');
w.document.write('<link rel="stylesheet" type="text/css" href="css/receipt-print.css">');
w.document.write('</head><body >');
w.document.write(document.getElementById(el).innerHTML);
w.document.write('<script type="text/javascript">addEventListener("load", () => { print(); close(); })</script></body></html>');
w.document.close();
w.focus();
}
Hello i am trying to call a method from a js file from Blazor.
My file structure is like this:
-root
-JSInterop.cs
-js(folder)
-meth.js (file containing the js method)
I keep getting the following error :
Could not find 'methods' in 'window'.
**Cs class that calls the js **
public class JSInterop {
public static async Task<string> ChangeText() {
try {
var data = await JSRuntime.Current.InvokeAsync<string>("./js/meth/methods.print","mymessage");
Console.WriteLine($"ReturnedFromJS:{data}");
return data;
} catch (Exception ex) {
return ex.Message;
}
}
}
Js file
function print(message){
return "fromJs"+message;
}
window.methods = {
print: function (message) {
return "from js" + message;
}
}
I have tried both putting just the method and putting it as a property in the window.I am not sure in the first case how do you refer a method from a file in js.
"[path to file]/[containingfile]/[methodname]" ?
or i have also tried "[path to file] / window.[methodname]"
to no avail (in the second case)
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width">
<title>Sms.Studio.Web</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/site.css" rel="stylesheet" />
</head>
<body>
<app>Loading...</app>
<!-- browser -->
<script src="_framework/blazor.webassembly.js"></script>
<script src="../interop/js/meth.js"></script>
</body>
</html>
JSRuntime.Current.InvokeAsync takes a js function identifier relative to the global window scope as its first argument. So in your js file you may have :
window.methods = {
print: function (message) {
return "from js" + message
}
Add your js file in index.html
<script src="css/bootstrap/bootstrap-native.min.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
<script src="js/meth.js"></script>
and call it from .Net as follows
await JSRuntime.Current.InvokeAsync<string>("methods.print","mymessage");
// Try this:
// Don't call your class JSInterop
public class MyJSInterop {
public static async Task<string> ChangeText() {
try {
var data = await JSRuntime.Current.InvokeAsync<string>("methods.print","mymessage");
Console.WriteLine($"ReturnedFromJS:{data}");
return data;
} catch (Exception ex) {
return ex.Message;
}
}
}
// Js file
window.methods = {
print: function (message) {
return "from js" + message;
}
};
Below is an end to end example of writing cookie.
step 1 - Add MatButton and sets it onClick attribute to delegate.
<MatButton TrailingIcon="favorite" #onclick="#(async () => await AddItemtoShoppingCart(#item))" Label="add"></MatButton>
Step 2
#code{
public async Task AddItemtoShoppingCart(FoodItem selectedItem)
{
var test = await JSRuntime.InvokeAsync<object>("blazorExtensions.WriteCookie", "cookieName", "cookieValue", "cookieExpiryDate");
}
}
Step 3 - Add below javasceipt in_Host.cshtml
<script>
window.blazorExtensions = {
WriteCookie: function (name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
}
</script>
//app.js
const SEARCH_VIEW = document.getElementById('search_view');
const RESULTS_VIEW = document.getElementById('results_view');
const FORECAST_VIEW = document.getElementById('forecast_view')
function loadCities(){
const cities = ["London", "Paris", "Madrid", "Lisbon","Ohrid"];
var options = null;
var dest = document.getElementById('dest');
//Looping the cities
cities.forEach(city => {
options += '<option>' + city +'</options>';
});
dest.innerHTML = options;
}
function gettingWeather(){
// 1. Open the Url
var dest = document.getElementById('dest').value;
var url = ('http://api.openweathermap.org/data/2.5/weather?q='+ dest + '&appid=exampleAppId');
console.log(url);
console.log(dest);
// 2. Fetch the URL
fetch(url)
.then(response => {
if(response.status !== 200){
console.error("API failed, Status Code " + response.status);
return;
}
console.log(response);
// 3.We make the response .json and open the data
response.json().then(data => {
console.log(data);
RESULTS_VIEW.style.visibility = 'visible';
// Temperature
document.getElementById('Temperature').textContent = data.main.temp;
//Wind
document.querySelector('.Wind').textContent = data.wind.speed * data.wind.deg;
//Description
document.querySelector('.Description').textContent = data.weather[0].description;
});
}).catch(err => {
console.error("Fetch error "+ err);
});
}
function forecast(){
const API_BASE = 'http://api.openweathermap.org/data/2.5/forecast?mode=json&';
const API_KEY = 'appid=exampleAppId&';
var dest = document.getElementById('dest').value;
var url = API_BASE + API_KEY + 'q=' + dest.value;
console.log(url);
console.log(dest.value);
// 2. Fetch the URL
fetch(url)
.then(response => {
if(response.status !== 200){
console.error("API failed, Status Code " + response.status);
return;
}
console.log(response);
// 3.We make the response .json and open the data
response.json().then(data => {
console.log(data);
RESULTS_VIEW.style.visibility = 'hidden';
FORECAST_VIEW.style.visibility= 'visible';
});
}).catch(err => {
console.error("Fetch error "+ err);
});
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>Weather App</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width ,initial-scale=1">
<link href="styles.css" type="text/css" rel="stylesheet">
</head>
<body onload="loadCities();">
<div class="container">
<div id = "results_view">
<div class="inputWrapper">
<h1> Weather App </h1>
<p>Choose a city.</p>
<select id="dest" onchange="gettingWeather();" width=150 style="width:150px" ></select><br>
<label>Temperature</label>
<label class="Temperature" id="Temperature"></label><br>
<label>Wind</label>
<label class="Wind" id="Wind"></label><br>
<label>Description</label>
<h1 class="Description" id="Description"></h1>
<button onclick="forecast();">Forecast</button>
</div><!-- InputWrapper -->
</div>
<div id="forecast_view">
<h1>ForeCast</h1>
</div>
</div> <!-- end container -->
<script src="app.js"></script>
</body>
</html>
My task is to choose random 5 European cities and show some attributes but when a button is clicked I need to show a forecast of that city. I attempt to use Lexical Scoping to and half of my application works the easy part where i show some attribute taken from the API, when i clicked the button forecast I have error with the response Error but the error is also the city i choose.If I use any city the, in the forecast is undefined. I am not sure why I have this error and i dont have any insides tried closure If you don't know any answer I would appreciate even an insight or reference of work similar done.
Thank you
The problem is that your variable "dest" already contains the value. So you have in "dest" the name of your city and you use dest.value which is undefined because dest is a string and has no property called value.
to fix your code just remove .value in the url:
const API_BASE = 'http://api.openweathermap.org/data/2.5/forecast?mode=json&';
const API_KEY = 'appid=6c345b20d0c8fac21a36761eb7d6cd38&';
var dest = document.getElementById('dest').value;
var url = API_BASE + API_KEY + 'q=' + dest; // only dest NOT dest.value
console.log(dest); // the city selected
Javascript newbie here. I have a javascript function that works nested in an html file, I import an external library abaaso, then declare the function and then call it:
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<script src="abaaso.js"></script>
</head>
<body>
<script>
var baseurl = "https://example.com";
var baseapi = baseurl + "/api/v1/";
var api_username = "user";
var api_key = "key";
var credentials = "?api_username=" + api_username + "&api_key=" + api_key;
var rawdata = {};
(function ($$) {
/* login */
login = function(username, password) {
var calledUrl = baseapi + "user/login/" + credentials;
calledUrl.post(
function (content) {
/*console.log("success" + JSON.stringify(content, null, 4));*/
},
function (e) {
console.log("it failed! -> " + e);
},
{
"username": username,
"password": password
},
{"Accept" : "application/json"}
);
}
})(abaaso);
login('test#example.com', 'passwd');
</script>
</body>
</html>
I want to put it in an external .js file and import it and only use the call to the function login('test#example.com', 'passwd');. I don't want to import abaaso from the html file but from the new .js.
How can I do that? Is there a particular structure to respect? Do I need to create a global function to the js file?
I don't want to import abaaso from the html file but from the new .js.
You can't do that. However, you can import both abaaso and the new .js:
<head>
<title>title</title>
<script src="abaaso.js"></script>
<script src="new.js"></script>
</head>