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
Try this:
As well, try to make your button click handler is set up properly. Check down for edits;
Now should work, I believe assuming npm installation is correct and bundler is configured properly to handle ES module imports.
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: