Get a Blob as a PNG File

Hope you had a wonderful Christmas holiday!

Just to clarify, I am new to JS and may make some unconventional attempts in trying to download my Blob in PNG format.

I am facing an issue with exporting all the visual content of a DIV in either PDF or image format upon clicking a button(the div has a consistent class name).

After researching, I learned that I need to convert the div to canvas for downloading it. I attempted to modify the code from this discussion: How to take screenshot of a div with JavaScript?

However, despite various tweaks and tests, nothing happens when I click on the button... Here's a snippet of my code:

<html lang="fr">
<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>Export Visualisation QS</title>
</head>
<body>
    <div class="qvt-sheet-container">
        <h1>EXPORT PNG</h1> 
        <img src="Logo-Qlik.png">
    </div>
    <a id="link"><button id="btn-export-qs">Export PNG</button></a>
</body>

<script language="JavaScript" type="text/javascript" src="jquery-3.6.0.min.js">
var a = document.getElementById("link");
function export_feuille() {
    $("#btn-export-qs").click(function() {
        html2canvas($(".qvt-sheet-container"), {
            onrendered: function(canvas) {
                //theCanvas = canvas;
                canvas.toBlob(function(blob) {
                    //saveAs(blob, "Dashboard.png");
                    url = window.URL.createObjectURL(blob);
                    a.href = url;
                    a.download = "export_qs.png";
                    a.click();
                    window.URL.revokeObjectURL(url);
                });
            }
        });
    });
};

document.getElementById("btn-export-qs").addEventListener ("click", export_feuille, false);

</script>
</html>

If anyone can offer insight into what might be going wrong or guide me in the right direction, I would greatly appreciate it :)

Answer №1

Upon reviewing your code, it seems that there is some redundancy present.

In the section of your code:

document.getElementById("btn-export-qs").addEventListener ("click", export_feuille, false);

The above snippet indicates that you are adding a click event listener to a button. When clicked, it calls the export_feuille function. However, within the export_feuille function, you are using jQuery to achieve the same functionality once again, which is unnecessary.

You have wrapped a <button> element inside an <a> tag. This setup utilizes the anchor tag unnecessarily to trigger the download event when the button is pressed. Here's a recommended modification:

HTML: I have removed the <a> tag

<div class="qvt-sheet-container">
    <h1>EXPORT PNG</h1>
    <img src="your-image.jpg" style="width: 150px;height: 150px">
</div>

<button id="btn-export-qs">Export PNG</button>

Javascript:

$("#btn-export-qs").click(function () {
    html2canvas(
        document.querySelector('.qvt-sheet-container'),
        {
            allowTaint: true,
            useCORS: true
        }
    ).then(canvas => {
        download(canvas)
    })
});

const download = function (canvas) {
    const link = document.createElement('a');
    link.download = 'filename.png';
    link.href = canvas.toDataURL()
    link.click();
}

Find the complete code here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a Product Box design with CSS and incorporating visual elements

I have created a simple box design in Photoshop that I want to use to display product information. The box consists of a Header, Body, and Button, each as separate images. How can I assemble these elements using CSS/HTML? I only need the header text at th ...

Preserving the position of inline text

I've been working on a button design that I want to make look more realistic by moving the text down 1px inside the button when it's pressed. To achieve this effect, I added an extra pixel to the top and removed one from the bottom. However, the ...

What could be causing the "Error - Only secure origins are permitted" message to appear for my service worker?

Whenever I attempt to implement a service worker on my progressive web application page, why does the browser console display this specific error message? ERROR "Uncaught (in promise) DOMException: Only secure origins are allowed JavaScript Code: ...

Struggling to link variables and functions to an angularJS controller

When using the $scope object to bind functions and variables, and making changes accordingly in HTML, the code works fine. But when using a different object, it doesn't work as expected. Here is an example of a working code snippet: ...

Can the AJAX URL be loaded onto a new page?

https://i.stack.imgur.com/5l63v.pngPardon the poorly phrased question, but I need some guidance on a specific requirement regarding opening a URL in a new page. Currently, I have designed an AJAX URL and I'm wondering if it's possible to open thi ...

Unexpected Behavior when Passing @Input() Data Between Parent and Child Components in Angular 2 Application

I am currently in the process of abstracting out a tabular-data display to transform it into a child component that can be loaded into different parent components. The main aim behind this transformation is to ensure that the overall application remains "d ...

Using the split and join methods in PHP for Javascript operations

Can you assist me with writing this code in PHP? I've attempted multiple times but I can't seem to get it right. Any help would be greatly appreciated! return s.split(/\r?\n/).join("<br>"); Thank you in advance! ...

What strategies can be implemented to avoid re-rendering in Angular 6 when the window is resized or loses focus?

I am currently working with a component in Angular 6.0.8 that consists of only an iframe element. Here is the code in page.component.html: <iframe [src]="url"> The logic for setting the URL is handled in page.component.ts: ngOnInit() { this.u ...

The error handler function is missing in Zepto's $.post method

When I was using Zepto instead of jQuery, I noticed that while the $.ajax method has an error handler, other methods like $.post and $.get do not. Do you know why this is the case? Function Signature $.post(url, [data], function(data, status, xhr){ ... }, ...

Error encountered: 'applePaySession.completeMerchantValidation' is not a valid object reference when attempting to process a successful apple pay payment

So, I'm having an issue with the user's payment going through but encountering undefined value when checking compatibility. I've been trying to debug this problem in my code snippet below: setCanDisplayApplePay() { var client = n ...

Creating an array using Vue.js

When I initialize a Vue data array like this [0: Object, 2: Object];, the console log in Vue shows the array as [0: Object, 1: undefined 2: Object];. This causes issues when iterating through with 'v-for="cell in row.cells"' as it results in tryi ...

Keystroke to activate Ant Design Select and start searching

I'm currently using the 'react-hotkeys-hook' library and have successfully implemented a hotkey that logs in the console when triggered (via onFocus()). My goal now is to use a hotkey that will open a Select component and add the cursor to i ...

Refining search outcomes using multiple Multiselect boxes in VueJS

In my Vue component, I have successfully displayed results from a data object and created multiple multiselect boxes. However, I am facing challenges with filtering. I understand how to set and compare a single value from the multiselect for displaying sp ...

Press the jQuery button and inform me once it has been activated

My jQuery code is set up to automatically press buttons for me every second. Occasionally, some pages take a long time to load until the button appears. Here is the current code I am using: (function($){ setInterval(function(){ $('.play-b ...

Concealing specific elements in Angular by utilizing ng-class conditions

Here's the code snippet I am currently working with: <tr ng-repeat="version in allVersions" ng-class="{{ version['active'] == 'true' ? 'active' : 'inactive' }}"> </tr> The ng-class is functioning ...

Refreshing div with updated form/content using jQuery and AJAX

Is it possible to use jQuery/AJAX functions to replace a form (or any content) with another form when a button is clicked, without reloading the page? Essentially creating a multi-part form dynamically. Can I achieve this with the following code snippet? ...

Utilizing a class instance as a static property - a step-by-step guide

In my code, I am trying to establish a static property for a class called OuterClass. This static property should hold an instance of another class named InnerClass. The InnerClass definition consists of a property and a function as shown below: // InnerC ...

The Angular 2 Router's navigation functionality seems to be malfunctioning within a service

Currently, I am facing an issue with using Angular2 Router.navigate as it is not functioning as expected. import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { Router } from '@angular/ ...

The Wonders of Flex Box and Media Queries

Can a website still be made responsive without relying on media queries when flexbox is already implemented? Are there specific scenarios where the utilization of media queries offers enhanced control? ...

Apple's iPhone does not adhere to media query specifications

My responsive website was functioning perfectly on desktop, Android, and Windows Phone devices. However, when I asked my friends to check it on their iPhones running iOS 10, they informed me that the media queries were being ignored on iPhone models 5, 5s, ...