Search code examples
xpages

JSPDF-autotable : jsPDF is not defined


Trying to give the possibility to generate a pdf in xpages The code I have :

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">

<xp:this.resources>
<xp:script src="generate.js" clientSide="true"></xp:script>
</xp:this.resources>
<script type='text/javascript' src='js/jspdf.min.js'></script>
<script type="text/javascript"  src="js/jspdf.plugin.autotable.js"></script>

<button onclick="generate()">Generate PDF</button>

<xp:br></xp:br>
<xp:br></xp:br>
<table id="basic-table" >
<thead>
<tr>
  <th>ID</th>
  <th>First name</th>
  <th>Last name</th>
  <th>Email</th>
  <th>Country</th>
  <th>IP-address</th>
</tr>
</thead>
<tbody>
<tr>
  <td align="right">1</td>
  <td>Donna</td>
  <td>Moore</td>
  <td>dmoore0@furl.net</td>
  <td>China</td>
  <td>211.56.242.221</td>
</tr>
    <tr>
      <td align="right">2</td>
      <td>Janice</td>
      <td>Henry</td>
      <td>jhenry1@theatlantic.com</td>
      <td>Ukraine</td>
      <td>38.36.7.199</td>
     </tr>
     <tr>
      <td align="right">3</td>
      <td>Ruth</td>
      <td>Wells</td>
      <td>rwells2@constantcontact.com</td>
      <td>Trinidad and Tobago</td>
      <td>19.162.133.184</td>
    </tr>
    <tr>
      <td align="right">4</td>
      <td>Jason</td>
      <td>Ray</td>
      <td>jray3@psu.edu</td>
      <td>Brazil</td>
      <td>10.68.11.42</td>
    </tr>
    <tr>
      <td align="right">5</td>
      <td>Jane</td>
      <td>Stephens</td>
      <td>jstephens4@go.com</td>
      <td>United States</td>
      <td>47.32.129.71</td>
    </tr>
    <tr>
      <td align="right">6</td>
      <td>Adam</td>
      <td>Nichols</td>
      <td>anichols5@com.com</td>
      <td>Canada</td>
      <td>18.186.38.37</td>
    </tr>
  </tbody>
</table>

    <xp:br></xp:br>
</xp:view>

I'm getting an error in the console :

Uncaught ReferenceError: jsPDF is not defined at generate (generate:3) at HTMLButtonElement.onclick (test_pdf2.xsp:20) generate @ generate:3 onclick @ test_pdf2.xsp:20

and line 3 of generate.js = var doc = new jsPDF('p','pt');

When I have a look at the sources I can see under js the 2 libraries

What's wrong ?


Solution

  • jsPDF uses AMD. Here's a snippet from the jspdf.min.js source code where AMD is used:

    function"==typeof define&&define.amd?define(e)
    

    Unfortunately AMD loading conflicts with Dojo in XPages. See this answer on how to remove AMD loading.

    You need to change the AMD loading part by changing the code in jspdf.min.js to this:

    function"==typeof define&&false?define(e)
    

    jspdf.plugin.autotable.js uses AMD too. Here you need to replace define.amd with false too.