Jspdf: Error: jsPDF is not a constructor

Created on 8 Apr 2020  路  4Comments  路  Source: MrRio/jsPDF

OK, I think you messed with automatic bundlers like everybody these days...

Replace first lines with these:

(function (factory) {
  if(typeof define === 'function' && define.amd)
      define(factory) 
  else
   window.jsPDF = factory();
}(function () { 'use strict';
...

Now we can make:

var x = new jsPDF();

without errors.

File I'm referred to: jspdf.debug.js at the dist folder of your project.

Now let's include minified version from CDN:

<!doctype html>
<html>
   <head>
      <meta charset="utf-8">
      <title>Test jsPDF</title>
   </head>
   <body style="">
   ...
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
   </body>
</html>

browser prints at console:

Script error.
at: https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js
line: 0

The above happens when we dynamically append the <script> tag at the bottom of <body> (using custom code here).
Amazingly, no error prints out if we hard-code the <script> tag!

From stackoverflow one proposes:

const jsPDF = require('jspdf')
var pdf = new jsPDF('p', 'pt', 'letter')

but you have to check what is the result in terms of javascript code when we issue a require in the Node environment - I mean what's the code that the browser runs? (browser javascript is not Node javascript).

Now can you change the CDN version of the library?

no-issue-activity

Most helpful comment

Always use
const { jsPDF } = require("jspdf"); ---> define like this in nodejs if your file is .js extension

`const doc = new jsPDF('p');`

Then like this, it will work smoothly

All 4 comments

This issue is stale because it has been open 90 days with no activity. It will be closed soon. Please comment/reopen if this issue is still relevant.

Currently working on that...

This issue is stale because it has been open 90 days with no activity. It will be closed soon. Please comment/reopen if this issue is still relevant.

Always use
const { jsPDF } = require("jspdf"); ---> define like this in nodejs if your file is .js extension

`const doc = new jsPDF('p');`

Then like this, it will work smoothly

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MelanieCroce picture MelanieCroce  路  4Comments

NoFootDancer picture NoFootDancer  路  3Comments

palmoni picture palmoni  路  4Comments

tarekis picture tarekis  路  4Comments

MaxCodeDE picture MaxCodeDE  路  4Comments