4

I need to add the jsPDF library to my Magento 2 Luma theme, so I can use it on the checkout success page.

1
1

You can create a module using that structure below.

1 - Add you PHTML with the JS call via PHTML

app/code/MyCompany/MyModule/view/frontend/layout/checkout_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="JSPDF" template="MyCompany_MyModule::js_pdf.phtml" />
        </referenceContainer>
    </body>
</page>

2 - Create your PHTML in order to instantiate the JS Library

app/code/MyCompany/MyModule/view/frontend/templates/js_pdf.phtml

<script type="text/javascript">
    //<![CDATA[[
    require(['jquery', 'jspdf' ], function ($, jsPDF) { 
        const pdf = new jsPDF(); 
        $('.print_button_pdf').click(function (){ 
            pdf.text(10, 40, Order); pdf.save('order.pdf');
        });    
    });
    // ]]>
</script>

3 - Call the script via RequireJS

app/code/MyCompany/MyModule/view/frontend/requirejs-config.js

var config = {
    paths: {
        'jsPDF' : ['//unpkg.com/jspdf@latest/dist/jspdf.min', 'MyCompany_MyModule/jspdf.min']
    },
    shim: {
        'jsPDF' : ['jquery']
    }
};
5
  • U have to call $, jsPdf in your script, and i download the library and add it to my module view/frontend/web/js
    – Vlade
    Aug 13 '18 at 7:22
  • <script type="text/javascript" >// <![CDATA[ require(['jquery', 'jspdf' ], function ($, jsPDF,) { const pdf = new jsPDF(); $('.print_button_pdf').click(function (){ pdf.text(10, 40, Order); pdf.save('order.pdf'); }); }); // ]]></script>
    – Vlade
    Aug 13 '18 at 7:24
  • How come you've added JS to a PHTML file? Wouldn't JS be better in a JS file?
    – Ben Crook
    Aug 20 '18 at 15:17
  • @BenCrook in my opinion, it would be better if there are a lot of DOM manipulations relative to this module, or if the dev. wants to abstract the DOM manipulations of the theme, it is not something that we can't find in the core though. github.com/magento/magento2/blob/2.2-develop/app/code/Magento/… Aug 20 '18 at 15:28
  • can you please send the download link in magento 2.3 extension link Oct 1 '19 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.