How to download img with JQUERY? - javascript

I have <img id="barcode"> and I need to download image from src. The image is generated with base64, and src contain this string:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADoAAACOCAYAAABg4BtLAAADgUlEQVR4Xu2czyt8URjGnyErWfgLWClLCUuxsmCDoijJwpo0GT+S/EhSFmyUErGQ2LBQFrJEmrKxmuIvsLRAo3vM+M5M3c6drnO/hs8s77n3zPu+zznP8z4zZyaWTqfT+gOvGIn+MpRB9JcBKhAF0RKtAEu3RIHzDTsworFYLG+SbEOVvV7YYP2v636ZkmhhZUA0s6RZugXmyPXeZY8GtWnsUfbop+5GTVLsUfZowRqAjCAjyMgpG8O6sC6s+1kBPmHIrATXdsxvfsgIMoKMIKO8NQAZOTYBsC6sC+vCurBubgVcyw6sC+vCurAurAvr5lTgu2QHeUFekBfkBXlBXpCXfxUoVl/RUXQUHUVH0VF0FB1FR78qwBkGn9aI370UFoZjrI6/waap9ykw7gX3gnvBveBecC+4F9wL7sWvI8pex73gXjIV4OcgmUIUa6++637cC+4F94J7wb3gXnAvuBfcC+4l25LSGdEZ0RnRGdEZ0RnRGdEZ0RnRGfmsAY7fcPymRP9FzsZqP3088LdpPz0RW3wkaqtQqY2DaKkhZosXRG0VKnb88fFRy8vLOj4+1uvrqzo6OjQ5OamGhgYVdl3Fzh3k/kgQfXh40PDwsK6vr/Niqqmp0e7urlpbW4PEGuoe54m+vLxobGxM5+fnWlxcVE9Pj8rKynR0dKSZmRk1Nzdra2tL1dXVoRKxPew80fv7e/X29hpE4/G4ysvLTUzv7+9aXV3VxsaGTk9P1djYaIs11LjzRA8PDw2iucm8vb3p8vJS09PTur291f7+vgYGBkIlYnvYeaLr6+tmH3oJ19XVKZlMam5uTmdnZ1+xeSSVSCRssYYad57owsKCLi4utLS0pO3tbe3t7amqqsos55GREbNP29vbNTs7GyoR28POE/UQHR8f/4qjs7NT8/PzRlZSqZT6+/sNQZU8ogcHBxocHFRTU5PRUQ89j3W9193dnbq6uuQVo6+vzwZKqHHniGaTmZiYMKSUe0LMS3Btbe13sO7z87NGR0d1c3Nj5KS7u9sgc3JyYuSmra1Nm5ubqqysDIWY7WHniHoBXF1daWhoSE9PT3nxtLS0aGdnR/X19bY4Q49Hkqh3EtSTlZWVFdMhVVRUGAKamppSbW1t6CSCTBBJokECcX0PibqucNTzg2jUFXf9fiDqusJRzw+iUVfc9fuBqOsKRz3/n0H0A2kqGPz1ouCnAAAAAElFTkSuQmCC
How to download this image with jquery?
I m trying to do this:
$('#save_but').click(function() {
var img = document.getElementById('barcode');
img.src =$('#barcode').attr('src');
window.location.href = img.src.replace('image/png', 'image/octet-stream');
});
File is downloading but I cannot assign name and format (example: img.png) to it.

you can use the download attribute on an a tag ...
<img src="data:image/jpeg;base64,/9j/4AAQSkZ..."/>
see more: https://developer.mozilla.org/en/HTML/element/a#attr-download

Ok, that's solution for my problem:
1) Download this 5kb plugin: download.js
2) Write
<script>
$('#save_but').click(function() {
download($('#barcode').attr('src'),"strcode.png","image/png");
});
</script>
Working in Chrome, FireFox, IE ver. 9+

HTML File:
<div id="html-content-holder" style="background-color: #F0F0F1; color: #00cc65; width: 500px; padding-left: 25px; padding-top: 10px;">
<strong>Codepedia.info</strong><hr />
<h3 style="color: #3e4b51;">
Html to canvas, and canvas to proper image
</h3>
<p style="color: #3e4b51;">
<b>Codepedia.info</b> is a programming blog. Tutorials focused on Programming ASP.Net,C#, jQuery, AngularJs, Gridview, MVC, Ajax, Javascript, XML, MS SQL-Server, NodeJs, Web Design, Software
</p>
<p style="color: #3e4b51;">
<b>html2canvas</b> script allows you to take "screenshots" of webpages or parts of it, directly on the user's browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation.
</p>
</div>
<a id="btn-Convert-Html2Image" href="#">Download</a>
<br />
<div id="previewImage" style="display: none;">
</div>
Inside the Script tag:
<script>
$(document).ready(function () {
var element = $("#html-content-holder"); // global variable
var getCanvas; // global variable
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
}
});
$("#btn-Convert-Html2Image").on('click', function () {
var imgageData = getCanvas.toDataURL("image/png");
// Now browser starts downloading it instead of just showing it
var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#btn-Convert-Html2Image").attr("download", "your_pic_name.png").attr("href", newData);
});
});
</script>

Related

How i download a string base64 in javascript using internet explorer browser

Hi i am trying to download a base64 using the internet explorer browser but when i am clicking the link, the console of the browser pop up the next error "The data area transferred to a system call is too small."
Is there another form to download the document, if there is it can you share the code please?
Let me share my code. Note: The base64 string is incomplete
<DOCTYPE!html>
<script>
var pdf = 'data:application/octet-stream;base64,' +
'JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIvTGFu';
window.downloadPDF = function downloadPDF() {
var dlnk = document.getElementById('dwnldLnk');
dlnk.href = pdf;
dlnk.click();
alert('toma');
}
</script>
<body>
<div style="border: 1px solid black; padding:100px;">
<a id='dwnldLnk' download='base64file.pdf' style="display:none;" />
<a href="#" onclick="downloadPDF();" title='base64file.pdf'>click to download</a>
</div>
<body>
</html>

javascript: hide the div if external .php file has .. inline style never changes

story: hide the iframe if the .php is deleted or similar. So i try to hide the div that contains the iframe. Website of customer A can iframe a video from my website (external-website). But if the video is deleted, it should hide the complete iframe (the div). The complete php will be deleted or renamed if the video is not available.
Hide the <div> if external file (i want to iframe)
is not available or named as .php?=123456 or has not a <div "id", whatever.
The inline style never changes.
I tried each of this above, i don`t get it working.
I can edit the external .php file (my website too).
I do not get the script to change the inline style whatever i try.
What i want to do, hide the div if "something".
<div id="hide-me">
<iframe src="https://www.external-website.com/subfolder/1250.php" style="background-color: white;border: 0;height: auto;text-align:center;width: auto;max-height: 100%;" scrolling="no"></iframe>
</div>
<script>
function yourFunctionName () {
var anyname = document.getElementById("hide-me").style.display;
if(document.getElementById("id-in-external-php").src == 'https://www.external-website.com/subfolder/1250.php'){
document.getElementById("hide-me").style.display="block";
} else {
document.getElementById("hide-me").style.display="none";
}
}
</script>
I asked a similar question here, but it did not give a solution
enter link description here
content of https://www.external-website.com/subfolder/1250.php :
<div id="id-in-external-php">this is content for the iframe</div>
This is how I ran your code again and it worked, so you can try it:
<div id="hide-me" style="display: none;">
<iframe style="display: none;" id="id-in-external-php" src="https://www.external-website.com/subfolder/1250.php" style="background-color: white;border: 0;height: auto;text-align:center;width: auto;max-height: 100%;" scrolling="no"></iframe>
</div>
<script>
const yourFunctionName = () => {
const anyname = document.getElementById("hide-me");
const frameId = document.getElementById("id-in-external-php");
const check = frameId.contentDocument.body.children
const c = check[0].innerText;
if(c.startsWith('Cannot')) {
anyname.style.display="none";
frameId.style.display="none";
} else {
anyname.style.display="block";
frameId.style.display="block";
}
}
window.addEventListener("load", yourFunctionName, false);
</script>
I did not see where you invoked the function, so i invoked mine when window load

Error while taking an screenshot with js

I have a web page and I need a button where this takes a screenshot of the screen. Right now, I have the following js function that is excecuted by a button on html:
var takeScreenShot = function() {
html2canvas(document.getElementById("container"), {
onrendered: function (canvas) {
var tempcanvas=document.createElement('canvas');
tempcanvas.width=550;
tempcanvas.height=650;
var context=tempcanvas.getContext('2d');
context.drawImage(canvas,0,0,tempcanvas.width,tempcanvas.height,0,0,tempcanvas.width,tempcanvas.height);
var link=document.createElement("a");
link.href=tempcanvas.toDataURL('image/jpg');
link.download = 'screenshot.jpg';
link.click();
}
});
}
Then, the html has the following:
<div style="margin-right: 100px; margin-left: 600px" id="container">
<table class="myTable">
<th class="titles">Title</th>
<!-- code code code -->
<button onclick="takeScreenShot()">Table Screenshot</button>
</table>
</div>
This works but the problem is that the screen taken come with errors. The next image is how is taking the screenshot:
Screenshot taken with the button
And this is how it should be.
Screenshot taken manually

html to pdf conversion using javascript (jsPDF and html2canvas)

I've been looking into converting an HTML page into a PDF on the client side. I found a method with Javascript using html2canvas to parse the DOM and calculate the styles applied, and jsPDF to create the PDF. Link to my page - http://www.choosenj.com/html-to-pdf/
I'm struggling with a couple issues I need resolved:
The Canvased image is rendering the whole page as a single PDF, is there a way to split the long image into a multi page PDF?
Currently panels load as you scroll down, is there a way to load the entire page when clicking the "Create PDF button"?
If I wanted to canvas only panels that had a checkbox selected, how would I edit my JS?
Here my code below (Note: Most include html2canvas and jsPDF javascript libraries):
// Html to PDF
$(window).load(function(){
var
form = $('#Content'),
cache_width = form.width(),
a4 =[ 850, 2000]; // for a4 size paper width and height
$('#create_pdf').on('click',function(){
$('body').scrollTop(0);
createPDF();
});
//create pdf
function createPDF(){
getCanvas().then(function(canvas){
var
img = canvas.toDataURL("image/png"),
doc = new jsPDF({
unit:'px',
format:'a4'
});
doc.addImage(img, 'JPEG', 0, 0, 180, 630);
doc.save('choosenj.pdf');
form.width(cache_width);
});
}
// create canvas object
function getCanvas(){
form.width(cache_width).css('max-width','none');
return html2canvas(form,{
imageTimeout:2000,
removeContainer:true
});
}
}());
<!-- #Content -->
<div id="Content">
<div class="content_wrapper clearfix">
<!-- .Main Content -->
<div class="sections_group">
<div class="entry-content" itemprop="mainContentOfPage">
<div style="margin: 10px 0;"><a id="create_pdf" class="vc_general vc_btn3 vc_btn3-size-md vc_btn3-shape-square vc_btn3-style-flat vc_btn3-color-green" style="margin:0 20px;cursor:pointer;color:#fff;font-family: 'FranklinGothicStd-ExtraCond', Arial, sans-serif !important;text-transform: uppercase !important;">Create PDF</a> </div>
<?php
while ( have_posts() ){
the_post(); // Post Loop
}
?>
</div>
<!-- Contact Section-->
<?php wp_reset_postdata(); ?>
<?php get_template_part('contact-us') ?>
</div>
</div>
</div>
Any insight would be greatly appreciated,
Chris G

change image SRC and Style

Hi I want to rewrite an image Src and Style element.
The image tag has an element called "data-orig-file" wich has the url that I want to write to the src element.
I came up with this but I'm not good at javascript:
function changeImageSrc(img) {
var newurl= document.getElementById("img").getAttribute('data-orig-file');
var oldurl= document.getElementById("img").src;
document.getElementById("img").src = img.src.replace(oldurl, newurl);
}
Now Secondly I want to grab the "Style" element with it's values from the grandparent div of the image and write that style to the image instead of the original style.
Finally I want to do these two things on all images inside a container div on a page when it is loaded (I suppose).
Any help is greatly apreciated!!
Thanks
update:
what I came up with so far is this:
function ChangeImageSrc() {
var image=document.getElementById("img");
var div=document.getElementById("LastPost");;
for each (image in div) {
var newurl= document.getElementById("img").getAttribute('data-orig-file');
var oldurl= document.getElementById("img").src;
document.getElementById("img").src = img.src.replace(oldurl, newurl);
}
}
window.onload = function()
{
ChangeImageSrc();
};
I also tried it with an "onload" event on the body element like this (instead of the wondow.onload part):
onload="javascript:ChangeImageSrc()
Both don't work this far :(
Ok AffluentOwl, here's the HTML:
<div class="gallery-group images-1" style="width: 677px; height: 507px;">
<div class="tiled-gallery-item tiled-gallery-item-large">
<a href="http://i0.wp.com/www.mydomain.com/wp-content/uploads/..../../image.jpg" class="zoom">
<img data-attachment-id="5786" data-orig-file="http://www.mydomain.com/wp-content/uploads/..../../image.jpg" data-orig-size="1333,1000" data-medium-file="http://www.mydomain.com/wp-content/uploads/..../../image-300x225.jpg" data-large-file="http://www.mydomain.com/wp-content/uploads/..../../image-1024x768.jpg" src="http://i0.wp.com/www.mydomain.com/wp-content/uploads/..../../image.jpg?resize=1191%2C893" align="left" title="shelter-childrens-farm" data-recalc-dims="1" style="width: 73px; height: 9px;">
</a>
</div>
</div>
As you can see there is a CDN prefix to the url that I'm trying to loose (for good reasons, it's opposed to me by wordpress and doesn't work for me).
The second thing is about the style of the image tag, that's somehow set to the wrong dimensions so I want to grab the right size from the first div (top of code).
Here's how you replace an images' src attribute with a url stored in an attribute on the image called data-orig-file when the page loads.
<html>
<script>
function ChangeImageSrc() {
var div = document.getElementsByClassName("gallery-group images-1")[0];
var images = div.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
images[i].setAttribute("src", images[i].getAttribute("data-orig-file"));
images[i].setAttribute("style", div.getAttribute("style"));
}
}
window.onload = ChangeImageSrc;
</script>
<div class="gallery-group images-1" style="width: 500px; height: 500px;">
<div class="tiled-gallery-item tiled-gallery-item-large">
<img src="a.jpg" data-orig-file="b.jpg" id="image_id" style="width: 100px; height: 100px">
<img src="c.png" data-orig-file="d.jpg" id="image_id" style="width: 100px; height: 100px">
<img src="e.png" data-orig-file="f.png" id="image_id" style="width: 100px; height: 100px">
</div>
</div>
</html>
It would probably be helpful for you to look into the element selection functions in Javascript.
getElementById
getElementsByClassName
getElementsByTagName
querySelector
You may even like to use jQuery which makes selecting elements much easier. In jQuery you could replace the <script> code with the following for the same result as above:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function() {
var div = $(".gallery-group.images-1");
var images = div.find("img");
images.each(function() {
$(this).attr("src", $(this).attr("data-orig-file"));
$(this).attr("style", div.attr("style"));
});
});
</script>

Categories

Resources