Search code examples
javascriptreactjsjspdf

How to generate a multipage PDF Using jsPDF using .html() method without jquery


I have a certain functionality where I have to export all tabs into the PDF, each tab in separate page. For tabs I have used react-tabs (https://www.npmjs.com/package/react-tabs).

It has one property called forceRenderTabPanel. While its true all the tabs will be rendered into the DOM.

I have used the jsPDF library for Exporting HTML(Tabs) to PDF.
jspdf has one method called .HTML(), which will take HTML renderer in its argument, I'm giving parent div into the argument.

As u can see in this example: Link to my codesandbox

As you can see in exported PDF there are only one (Active Tab) is exporting, even though All 3 tabs has been rendered into the Dom, what I'm looking for is Each Tab should be exported in Separate Pages.

How do I make multipage PDF from HTML using jspdf's .HTML() method or any other method with CSS from external file? or How Do I Add multipage inside .html() method's callback Can we carried out these task using another library or method? Any suggestion would be appreciable!!!

const doc = new jsPDF("p", "pt", "a4");    
doc.html(document.getElementById("Page1"), {
       callback: function (pdf) {
         pdf.addPage(
           [1500, 1500],
           "l"
         );
         pdf.html(document.getElementById("Page2"), {
           callback: function (pdf2) {
             pdf2.addPage(
               [1500, 1500],
               "l"
             );
             pdf2.html(document.getElementById("Page3"), {
               callback: function (pdf3) {
                 pdf3.save("3pageFS.pdf");
               },
               y: 1500,
             });
           },
         });
       },

I've tried using this way but I'm getting second and third blank pages, only First Page is visible!


Solution

  • I Found a Sort of trick For my requirement of exporting multipage PDF using .HTML() method, U can use nested callback functions like these & give X, and Y Coordinates based on Page Size

       const doc = new jsPDF("p", "pt", "a4");   
       doc.html(document.getElementById("Page1"), {
          callback: function (pdf) {
            pdf.addPage("a4", "l");
            pdf.html(document.getElementById("Page2"), {
              callback: function (pdf2) {
                pdf2.addPage("a4", "l");
                pdf2.html(document.getElementById("Page3"), {
                  callback: function (pdf3) {
                    pdf3.save("multipage.pdf")
                  },
                  x: 0,
                  y: 2 * pageHeight,
                });
              },
              x: 0,
              y: pageHeight,
            });
          },
          x: 0,
          y: 0,
        });
    

    Any Suggestions on How to make these code dynamic using for loop, based on number of Pages?