jspdf doesn't work when loaded from a CDN

Advertisements

I am going to use package(jspdf) loaded from **CDN **

this is CDN

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

and I have loaded it like this in a page :

mounted() {
  if (document.getElementById('myScript')) { return }
  let src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js'
  let script = document.createElement('script')
  script.setAttribute('src', src)
  script.setAttribute('type', 'text/javascript')
  script.setAttribute('id', 'myScript')
  document.head.appendChild(script)
}

and I have a button that when you click on it a below method will called and some pdf will be generated.

generateReport() {
  var doc = new jsPDF('l', 'mm', [62, 32])
  const margins = {
    top: 0,
    bottom: 60,
    left: 0,
    width: 122
  }

  doc.fromHTML(this.$refs.print, margins.left, margins.top, {
    width: margins.width
  })

  doc.save('test.pdf')
}

BUT I get an error

So, how can I fix this error?

>Solution :

You can use const { jsPDF } = window.jspdf; as shown in the official documentation if you want to use the CDN.

Even tho, I still do recommend the NPM package way (so does the package itself).

Leave a ReplyCancel reply