Adding image in the body of the email using href - html

I have a link in my page that once click it will open the email client.
My code is below:
<a href="mailto:?subject=Testing&body=AttachImage">
My question is how can I add an image in the body of the email. I tried image src but it does not work. Any suggestions?

Suppose you have your image defined like :
<img id="myimage" src="http://www.myserver.com/images/myimage"></img>
And its equivalent base64 encoded here that you would like to send by mail :
<img id="b64" src=""></img>
You can use base64 encoded form, such as :
function getBase64Image() {
//return LOGO;
var dataURL = '';
try {
var img = document.getElementById('myimage');
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to guess the
// original format, but be aware the using "image/jpg" will re-encode the image.
dataURL = canvas.toDataURL("image/jpg");
}
catch(e) {
console.log('Could not retrieve Base64 image with userAgent : ' + navigator.userAgent + ' \nException : ' + e);
}
return dataURL;
}
var base64Image = getBase64Image();
And then set your img src :
document["b64"].src = base64Image ;

Add that image inside <a> tag.
<a href="mailto:?subject=Testing">
<img src="your image path">
</a>
Hope it will help.

It's working, you might have not defined img width and height.
img{
width:100px;
height:100px;
}
<a href="mailto:?subject=Testing&body=AttachImage">
<img src = "https://source.unsplash.com/random">
</a>

Related

Passing a variable from Jquery into HTML

I have a jquery function that works out the width and height of an image I upload through umbraco. How can I call this.width and this.height into my img src in html at the bottom of the page?
<script>
function getMeta(varA, varB) {
if (typeof varB !== 'undefined') {
alert(varA + ' width ' + varB + ' height');
} else {
var img = new Image();
img.src = varA;
img.onload = function () {
getMeta(this.width, this.height);
}
}
}
getMeta("#image.Url()")
</script>
<img src="#image.Url()" width="" height="" border="0" alt="#Model.Value("mapImage")
mapImage" usemap="#Map" />
I've left the width and height empty but that's where I want it to equal this.width and this.height. I need it to automatically call it for other functions I have as it needs to change depending on the size of the image uploaded.
Thanks in advance for any help :)
Well.. good news - this is native JS - no jquery used the code you've posted
Second - you don't need to send the width and height to your data model - just update your image element. so...
img.onload = function () {
const imgElement = document.querySelector('img'); // select the image element in you HTML page
imgElement.style.width = `${this.width}px`; // set a proper with using pixels as unit
imgElement.style.height = `${this.height}px`; // set height the same way
}
This should update your image proportions to be an exact fit to the image provided
Assuming that I understood you well and you have an uploaded pic (that you get its source by calling #image.Url()), and you want to apply its dimensions of another pic (with id templateImg), this is the code:
<img id="templateImg" src="https://cdn.vox-cdn.com/thumbor/prZDWmD_4e4Js7KCRJ2JDrJOqO0=/0x0:939x704/1400x1050/filters:focal(0x0:939x704):format(jpeg)/cdn.vox-cdn.com/uploads/chorus_image/image/49610677/homersimpson.0.0.jpg" />
<script type = "text/javascript">
var uploadedPic = 'https://i.pinimg.com/736x/dd/50/38/dd5038cdbfde2a8f1583bd84f992f862.jpg';
function getMeta(src) {
return new Promise(resolve => {
var img = new Image();
img.src = src;
img.onload = function () {
resolve({
width: this.width,
height: this.height
});
}
})
}
getMeta(uploadedPic)
.then(dimensions => {
document.getElementById('templateImg').style.width = `${dimensions.width}px`;
document.getElementById('templateImg').style.height = `${dimensions.height}px`;
});
</script>
It was working example with real pictures, now you just replace the line var uploadedPic... with this Razor code:
<text>
var uploadedPic = '#image.Url()';
</text>
(assuming this is the path to your uploaded picture) and you'll be fine.

issue with showing croped image in another div with jquery

I want to use image cropper tool for that I have use cropper.js.
image cropper is working fine but I want to show image after cropping in another image tag
for that I have use below code
canvas.toBlob(function(blob) {
url = URL.createObjectURL(blob);
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var base64data = reader.result;
var croppedImageDataURL = $('.preview').cropper('getCroppedCanvas').toDataURL("image/png");
}
});
but it is not working myfor my full code I have made jsfiddle.
can anybody help me in this

JsPDF - Not allowed to navigate top frame to data URL

After updating Google Chrome, the report jsPDF in a new Window does not work any more.
The console shows the message:
Not allowed to navigate top frame to data URL:
data:application/pdf;base64,JVBERi0xLjMKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL1....
Can you help-me?
Thanks.
This works well now that chrome has removed top frame navigation. Only downloading the pdf in chrome gives problem. Download works in well in firefox tho.
var string = doc.output('datauristring');
var iframe = "<iframe width='100%' height='100%' src='" + string + "'></iframe>"
var x = window.open();
x.document.open();
x.document.write(iframe);
x.document.close();
Apparently Google Chrome has removed support for top-frame navigation, you can see more informations here: https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/GbVcuwg_QjM
You may try to render the jsPDF to an iFrame
I recently had the same problem using FileReader object to read content and show my JSReport.
var reader = new FileReader();
reader.onload = function (e) {
window.open(reader.result, "_blank");
}
reader.readAsDataURL(blob);
Unfortunatly after chrome update all my report stopped working.
I tried to fix this by using Blob object and it's still working but if you have a popup blocker it will not work.
var file = new Blob([blob], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
I finally find a way to avoid this problem by creating the iFrame dynamically after reading this topic and i decided to share the solution.
var file = new Blob([blob], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
var win = window.open();
win.document.write('<iframe src="' + fileURL + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>')
Maybe can help, create a function to export with the download attribute html5:
var docPdf = doc.output();
exportToFile(docPdf,defaults.type);
function exportToFile(data,type){
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/'+type+';filename='+'exportar.'+type+';'+'charset=utf-8,' + encodeURI(data);
hiddenElement.target = '_blank';
hiddenElement.download = 'exportar.'+type;
hiddenElement.click();
}
the download property of the a element has to contain a file name.
function window_download( datauri )
{
const match = datauri.match(/(filename=)([^;]+)/);
const fileName = match ? match[2] : '' ;
if ( fileName )
{
const downloadLink = document.createElement("a");
downloadLink.download = fileName;
downloadLink.innerHTML = "Download File";
downloadLink.href = datauri ;
downloadLink.click();
}
else
{
throw 'missing download file name' ;
}
// get contents of pdf from jsPDF as a data uri.
const uri = pdf.output('datauristring', 'packing-list.pdf' );
window_download( uri ) ;
<iframe id="ManualFrame"
frameborder="0"
style="border:0"
allowfullscreen>
</iframe>
<script>
$(function () {
setManualFrame();
});
function setManualFrame() {
$("#ManualFrame").attr("height", screen.height);
$("#ManualFrame").attr("width", screen.width);
$("#ManualFrame").attr("src", "data:application/pdf;base64," + Your_PDF_Data);
}
</script>
var pdfUrl = doc.output('datauri').substring(doc.output('datauri').indexOf(',')+1);
var binary = atob(pdfUrl.replace(/\s/g, ''));
var len = binary.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
view[i] = binary.charCodeAt(i);
}
var blob = new Blob( [view], { type: "application/pdf" });
var url = URL.createObjectURL(blob);
function openPDF(){
window.open(url);
}
As chrome removed its support for - Top-frame navigation. Luckily jsPDF has an API - "save()", which offers the same functionality as doc.output('datauri')
Below is the example implementation of save()
var doc = new jsPDF();
doc.addImage(imgData, 'JPEG', 0, 0, 300, 160);
doc.save('fileName.pdf');
save(filename, options) → {jsPDF|Promise}
Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf'). Uses FileSaver.js-method saveAs.
Refer JSPDF documentation for more information -
Add attrbute download
Based on Joyston's answer, but without reparsing and therefore without additional need to escape something:
x=window.open();
iframe=x.document.createElement('iframe')
iframe.width='100%'
iframe.height='100%'
iframe.frameBorder=0
iframe.style="border: 0"
iframe.src='data:text/html........' //data-uri content here
x.document.body.appendChild(iframe);
Not related to jspdf, but did help me here (and this question is the top hit at google): If specifying a download="..." attribute to the anchor tag, the download prompt will properly open up.
#kuldeep-choudhary
Hi, in fact, to solve i'm using object tag with angularJS 1.5.xx
<object ng-attr-data="{{data}}" type="application/pdf"></object>
and in script:
$scope.doc.data = $sce.trustAsResourceUrl(doc.output("datauristring"));
In pure javascript, maybe like this works:
html:
<object id="obj" type="application/pdf" ></object>
js:
document.elementById('obj').data = doc.output("datauristring");
please, try and correct-me if I wrong.
Using download="" made me able to download the file
/**
* Creates an anchor element `<a></a>` with
* the base64 pdf source and a filename with the
* HTML5 `download` attribute then clicks on it.
* #param {string} pdf
* #return {void}
*/
function downloadPDF(pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "vct_illustration.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
Source from: https://medium.com/octopus-labs-london/downloading-a-base-64-pdf-from-an-api-request-in-javascript-6b4c603515eb
In angular2+ -
app.component.html -
<object id="obj" [attr.data] type="application/pdf"> </object>
app.component.ts
document.getElementById('obj').dataset.data = doc.output("datauristring");
var blob = doc.output("blob");
window.open(URL.createObjectURL(blob));

Static max/min width for an img of arbitrary size

The max- and min-width attributes on an <img> tag are very useful, particularly the max width which can prevent an img from streching larger than its original size.
Now this is easy when you are using a specific image, so you can set it to be the same as the size of the image. But what if you want to apply this to a general image, for example one which is uploaded by a user? (so you don't know what the dimensions are) In other words, set the max/min width to the exact dimension of the image, for an arbitrary image.
this should do it...
<html>
<script src="http://code.jquery.com/jquery-1.11.1.min.js">
</script>
...
<div id="img-container"></div>
...
</html>
<script>
function loadImage(imgSrc) {
var newImg = new Image();
newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
$(newImg).css({
'max-width':width,
'max-height':height
});
$("#img-container").append(newImg);
}
newImg.src = imgSrc; // this must be done AFTER setting onload
}
loadImage('youimage.jpg');
</script>
you could also use server side code to get the image size.
try like this
var _URL = window.URL || window.webkitURL;
$("#file").change(function(e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function() {
alert(this.width + " " + this.height);
};
img.onerror = function() {
alert( "not a valid file: " + file.type);
};
img.src = _URL.createObjectURL(file);
}
});
Working demo:
http://jsfiddle.net/4N6D9/1/

Rendering HTML elements to <canvas>

Is there a way to have an arbitrary HTML element rendered in a canvas (and then access its buffer...).
You won't get real HTML rendering to <canvas> per se currently, because canvas context does not have functions to render HTML elements.
There are some emulations:
html2canvas project http://html2canvas.hertzen.com/index.html (basically a HTML renderer attempt built on Javascript + canvas)
HTML to SVG to <canvas> might be possible depending on your use case:
https://github.com/miohtama/Krusovice/blob/master/src/tools/html2svg2canvas.js
Also if you are using Firefox you can hack some extended permissions and then render a DOM window to <canvas>
https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_Graphics_with_Canvas?redirectlocale=en-US&redirectslug=Drawing_Graphics_with_Canvas#Rendering_Web_Content_Into_A_Canvas
Take a look on MDN (archived)
It will render html element using creating SVG images.
For Example:
There is <em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span> HTML element. And I want to add it into <canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas> Canvas Element.
Here is Javascript Code to add HTML element to canvas.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
'<em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span>' +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {
type: 'image/svg+xml;charset=utf-8'
});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
}
img.src = url;
<canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
Here is code to render arbitrary HTML into a canvas:
function render_html_to_canvas(html, ctx, x, y, width, height) {
var xml = html_to_xml(html);
xml = xml.replace(/\#/g, '%23');
var data = "data:image/svg+xml;charset=utf-8,"+'<svg xmlns="http://www.w3.org/2000/svg" width="'+width+'" height="'+height+'">' +
'<foreignObject width="100%" height="100%">' +
xml+
'</foreignObject>' +
'</svg>';
var img = new Image();
img.onload = function () {
ctx.drawImage(img, x, y);
}
img.src = data;
}
function html_to_xml(html) {
var doc = document.implementation.createHTMLDocument('');
doc.write(html);
// You must manually set the xmlns if you intend to immediately serialize
// the HTML document to a string as opposed to appending it to a
// <foreignObject> in the DOM
doc.documentElement.setAttribute('xmlns', doc.documentElement.namespaceURI);
// Get well-formed markup
html = (new XMLSerializer).serializeToString(doc.body);
return html;
}
example:
const ctx = document.querySelector('canvas').getContext('2d');
const html = `
<p>this
<p>is <span style="color:red; font-weight: bold;">not</span>
<p><i>xml</i>!
<p><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABWElEQVQ4jZ2Tu07DQBBFz9jjvEAQqAlQ0CHxERQ0/AItBV9Ew8dQUNBQIho6qCFE4Nhex4u85OHdWAKxzfWsx0d3HpazdGITA4kROjl0ckFrnYJmQlJrKsQZxFOIMyEqIMpADGhSZpikB1hAGsovdxABGuepC/4L0U7xRTG/riG3J8fuvdifPKnmasXp5c2TB1HNPl24gNTnpeqsgmj1eFgayoHvRDWbLBOKJbn9WLGYflCCpmM/2a4Au6/PTjdH+z9lCJQ9vyeq0w/ve2kA3vaOnI6k4Pz+0Y24yP3Gapy+Bw6qdfsCRZfWSWgclCCVXTZu5LZFXKJJ2sepW2KYNCENB3U5pw93zLoDjNK6E7rTFcgbkGYJtiLckxCiw4W1OURsxUE5BokQiQj3JIToVtKwlhsurq+YDYbMBjuU/W3KtT3xIbrpAD7E60lwQohuaMtP8ldI0uMbGfC1r1zyWPUAAAAASUVORK5CYII=">`;
render_html_to_canvas(html, ctx, 0, 0, 300, 150);
function render_html_to_canvas(html, ctx, x, y, width, height) {
var data = "data:image/svg+xml;charset=utf-8," + '<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '">' +
'<foreignObject width="100%" height="100%">' +
html_to_xml(html) +
'</foreignObject>' +
'</svg>';
var img = new Image();
img.onload = function() {
ctx.drawImage(img, x, y);
}
img.src = data;
}
function html_to_xml(html) {
var doc = document.implementation.createHTMLDocument('');
doc.write(html);
// You must manually set the xmlns if you intend to immediately serialize
// the HTML document to a string as opposed to appending it to a
// <foreignObject> in the DOM
doc.documentElement.setAttribute('xmlns', doc.documentElement.namespaceURI);
// Get well-formed markup
html = (new XMLSerializer).serializeToString(doc.body);
return html;
}
<canvas></canvas>
The CSS element() function may eventually help some people here, even though it's not a direct answer to the question. It allows you to use an element (and all children, including videos, cross-domain iframes, etc.) as a background image (and anywhere else that you'd normally use url(...) in your CSS code). Here's a blog post that shows what you can do with it.
It has been implemented in Firefox since 2011, and is being considered in Chromium/Chrome (don't forget to give the issue a star if you care about this functionality).
RasterizeHTML is a very good project, but if you need to access the canvas it wont work on chrome. due to the use of <foreignObject>.
If you need to access the canvas then you can use html2canvas
I am trying to find another project as html2canvas is very slow in performance
According to the HTML specification you can't access the elements of the Canvas. You can get its context, and draw in it manipulate it, but that is all.
BUT, you can put both the Canvas and the html element in the same div with a aposition: relative and then set the canvas and the other element to position: absolute.
This ways they will be on the top of each other. Then you can use the left and right CSS properties to position the html element.
If the element doesn't shows up, maybe the canvas is before it, so use the z-index CSS property to bring it before the canvas.