skip to Main Content

I am using jsPDF to convert my canvas into pdf but I ran into some problems so I made a simple one first. I’ve tried to use cdn to but it says jsPDF is not defined. I installed it with npm too.

This is my import statement:

import * as jsPDF from '../node_modules/jspdf/dist/jspdf.umd.min.js';

here is my button that returns jsPDF is not a constructor:

btnPrintCard.onclick = async function() {
    const pdf = new jsPDF();
    pdf.text('Hello, world!', 10, 10);
    pdf.save('document.pdf');
}

If I use this, it says The requested module ‘../node_modules/jspdf/dist/jspdf.umd.min.js’ does not provide an export named ‘default’

import jsPDF from '../node_modules/jspdf/dist/jspdf.umd.min.js';

If I use this, it says Failed to resolve module specifier "jspdf". Relative references must start with either "/", "./", or "../".

import jsPDF from 'jspdf';

If I use this:

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

it just says jsPDF is not defined

2

Answers


  1. Try this:

    import jsPDF from 'jspdf';
    

    As well, try to make your button click handler is set up properly. Check down for edits;

    btnPrintCard.onclick = async function() {
        const pdf = new jsPDF();
        pdf.text('Hello, world!', 10, 10);
        pdf.save('document.pdf');
    }
    

    Now should work, I believe assuming npm installation is correct and bundler is configured properly to handle ES module imports.

    Login or Signup to reply.
  2. The error "jsPDF is undefined" usually happens when the script hasn’t loaded yet, or the script tag is incorrectly set up.

    This worked out perfectly on my local:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script>
      document.addEventListener('DOMContentLoaded', function() {
        const btnPrintCard = document.getElementById('btnPrintCard');
    
        btnPrintCard.onclick = function() {
          const { jsPDF } = window.jspdf;
          const pdf = new jsPDF();
          pdf.text('Hello, world!', 10, 10);
          pdf.save('document.pdf');
        };
      });
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search