Is there a way to combine multiple images into one PDF document using Html2Canvas and JsPDF?

Trying to understand the HTML2Canvas API has been quite challenging due to the limited documentation available. My goal is to place multiple div elements, each representing a different page, into a single PDF file. It might sound simple at first, but in reality, it's much more complex. I've experimented with various approaches to achieve this, only to discover that the asynchronous nature of JavaScript adds another layer of difficulty.

This is what I currently have:


html2canvas($("#monthly_agg_report_container"), {
    onrendered: function(canvas) {
        var doc = new jsPDF('landscape', 'pt','a2');
        var imgData = canvas.toDataURL("image/png");

        doc.addImage(imgData,'PNG',0,0,canvas.width*1.33,canvas.height*1.33);

        doc.save('report.pdf');
    }
}).then(function(){
    // Another html2canvas attempt didn't work properly, resulting in an empty page in the PDF.
    alert('done');
})

Answer №1

I found this solution to be effective:

function generatePDF() {


    var document = new jsPDF('landscape', 'pt','a2');
    console.log(document);

   html2canvas($("#monthly_agg_report_container"), {

            onrendered: function(canvas)
            {

                var imgData = canvas.toDataURL("image/png");


                document.addImage(imgData,'PNG',0,0,canvas.width*1.33,canvas.height*1.33);

            //  document.save('report.pdf')  ;
            }
            }).then(function(){


                        html2canvas($("#descriptor_stats_container"), {

                            onrendered: function(canvas)
                            {
                                console.log('Second document '+document); 
                                document.addPage();
                                var imgData = canvas.toDataURL("image/png", 1.0);


                                document.addImage(imgData,'PNG',0,0,canvas.width*1.33,canvas.height*1.33);

                                //document.save('report.pdf')    ;
                            }
                            }).then(function(){
                                alert('Process completed')

                                    html2canvas($("#alerts_stats_container"), {

                                    onrendered: function(canvas)
                                    {
                                        console.log('Second document '+document); 
                                        document.addPage();
                                        var imgData = canvas.toDataURL("image/png");


                                        document.addImage(imgData,'PNG',0,0,canvas.width*1.33,canvas.height*1.33);

                                        document.save('report.pdf')  ;
                                    }
                                    })

                            })
                    })





}

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

Using Polymer 0.5 in real-world applications

While using some of the polymer 0.5 components in production, I noticed some deprecations related to deep and shadow dom being emitted in the console. This made me question if the 0.5 components are built on experimental APIs. Is there a possibility that t ...

increasing the size of a picture without resorting to a pop-up window

Struggling to implement a product details tab within a table that features a clickable image. When the image is clicked, it should enlarge but the width doesn't adjust accordingly. I'm using bootstrap 5.3 and can't seem to identify the root ...

What could be causing my asynchronous JavaScript/Node.js function to bypass a significant portion of the code?

Upon calling the function below: async function sql_func(){ console.log('anothertest') async () => { console.log('third test') try { await sql.connect('heres the connection data') ...

Stop the execution of jQuery ready handlers

I am facing a situation where I need to prevent jQuery ready handlers from firing on the DOMContentReady event under certain conditions. These handlers are set up in different places like include files, plugins, and more. While one approach could involve s ...

Implementing Vue method to apply filter criteria on an array for efficient data filtering

Having trouble filtering listItems by filterCriteria before rendering. The issue arises when attempting to pass the filterCriteria into the filter function using Array.prototype.filter. Is there a more efficient method of passing it without having to ...

Angular - Javascript - Oops! The variable 'google' seems to have gone missing after reloading the page

For my website, I utilized Angular 2+ and integrated the Google Maps Api by adding the following code to my index.html file: <script async defer src="//maps.googleapis.com/maps/api/js?[myKey]&libraries=places"> </script> ...

Storing knockout view model data in a database and fetching it back

I am currently working on a web form that utilizes knockout, and I need to add a new feature that allows users to save the form as a draft in the database. Later on, they should be able to load it again to make modifications or submit it. Is there a built ...

SSE and the power of NodeJS through Express

Having trouble receiving SSE events in the browser. This is the server-side code (using Express): app.all('/callme', function(req, res){ res.writeHead(200, { 'Connection': 'keep-alive', 'Content-Type&apo ...

Could someone assist me with understanding how to use the Load function in JQuery?

I have a set of links with the class "ajax" that are meant to fetch content from an element with the id "test" in the file "data.html" located in the same directory. This content should then be inserted into the div with the id "content" on my page: <s ...

Instructions on creating a countdown timer that reveals a hidden div once it reaches zero, remains visible for a set period, and then resets

I created a countdown timer that displays a div when the timer reaches zero. However, I am struggling with getting the timer to reset and start counting down again after displaying the div. For instance, if I set the timer for 7 days and it reaches the de ...

The Redux Toolkit Slice Reducer fails to function properly when incorporating an extra Reducer that is not compatible

I am relatively new to the world of Redux and have been attempting to use RTK right from the start. It has been quite a challenging and confusing experience for me so far. Recently, I decided to include a standard Reducer instead of an extraReducer in my ...

How can I implement BoxHelper on an Object3D containing children in Three.js?

I am exploring the possibility of using the THREE.BoxHelper to generate a bounding box for an Object3D that has children. My goal is to render a wireframe bounding box for the object while omitting diagonals on the box's faces. Upon inspecting the sou ...

The functionality for the "OnChange" event in the <html:select> field does not seem to be functioning properly

My JavaScript function isn't functioning properly. I can't see any alert messages on my webpage. Can someone please assist me? Below is my HTML code function checkProjectStatus() { alert("Helloo"); var dropdownType = document.getElementById( ...

How to instantly return progress bar to zero in bootstrap without any animations

I am currently working on a task that involves multiple actions, and I have implemented a bootstrap progress bar to visually represent the progress of each action. However, after completion of an action, the progress bar is reset to zero using the followi ...

What is the best way to calculate the combined total of radio button values using jQuery or JavaScript?

I recently came across a tutorial on how to sum radio button values using JavaScript or jQuery, and I decided to implement it in my code. However, I encountered some issues as it didn't work as expected. My goal was to offer users the option to downlo ...

Using Bootstrap4 to merge rows into a single column or apply rowspan in Bootstrap

Hey there, I have a specific requirement that I need help with. Check out the image here. I want to enable the LCM information box when the LCM checkbox is checked. Below is my code: <div class="panel-body "> <div class="c ...

Is there a way to eliminate an object from a multidimensional nested array in JavaScript and retrieve the parent array?

Can anyone help me figure out how to delete the "fields" object with id 47 from this nested array using JavaScript and return the entire parent array? [{ "id": 10, "name": "phone", "fields": [ { ...

Angular 1.5 - Component for fetching HTML content with dynamic data

Help needed with using Angular Component method. Developing a main html file with its main controller containing a JSON list of client data: clients: [{ "name": "John Jackson", "age": "21", "hair": "brown", }, { "name": "Janet Doe", ...

Using JavaScript to locate a child element within its parent

What is the most effective approach to locate a child element (using class or ID) of a specific parent element using only pure JavaScript without relying on jQuery or other frameworks? In this scenario, I am interested in finding child1 or child2 within p ...

Struggling to retrieve unpredictable data in a Vue.js component

Help! I'm trying to randomly display one of these names in my HTML, but I can't seem to make it work: Vue.component('modal', { template: '#modal-template', data: { items: [ { name: 'Elena' }, { na ...