JSPDF - addHTML() Multiple Canvas Page

后端 未结 4 1199
[愿得一人]
[愿得一人] 2020-12-29 08:55

I noticed already have a release \"addHTML() can now split the canvas into multiple pages\" which can find through this link : https://github.com/MrRio/jsPDF/releases/tag/v1

4条回答
  •  清歌不尽
    2020-12-29 09:32

    None of the above helped me so I'll put this here for anyone who arrives at this page looking to use addHTML() to create a single pdf split into multiple pages with a different html element on each page. I used recursion so I'm not sure of the performance implications of this approach. It worked for me to create a 4 page pdf from 4 div elements.

    var pdf = new jsPDF('landscape');
            var pdfName = 'test.pdf';
    
            var options = {};
    
            var $divs = $('.myDivClass')                //jQuery object of all the myDivClass divs
            var numRecursionsNeeded = $divs.length -1;     //the number of times we need to call addHtml (once per div)
            var currentRecursion=0;
    
            //Found a trick for using addHtml more than once per pdf. Call addHtml in the callback function of addHtml recursively.
            function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){
                //Once we have done all the divs save the pdf
                if(currentRecursion==totalRecursions){
                    pdf.save(pdfName);
                }else{
                    currentRecursion++;
                    pdf.addPage();
                    //$('.myDivClass')[currentRecursion] selects one of the divs out of the jquery collection as a html element
                    //addHtml requires an html element. Not a string like fromHtml.
                    pdf.addHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                        console.log(currentRecursion);
                        recursiveAddHtmlAndSave(currentRecursion, totalRecursions)
                    });
                }
            }
    
            pdf.addHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                recursiveAddHtmlAndSave(currentRecursion, numRecursionsNeeded);
            });
    }
    

提交回复
热议问题