JavaScript does not recognize jsPDF

After importing the jsPDF library, I attempted to export to PDF but encountered a JavaScript error stating that jsPDF is not defined.

I tried various solutions from similar posts but none of them seemed to work for me.

You can find the fiddle here: https://jsfiddle.net/aybhvf8e/1/

<script type="text/javascript" src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>

$( document ).ready(function() {

var doc = new jsPDF();
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};
})

$('#cmd').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});


<div id="content">
     <h3>Hello, this is a H3 tag</h3>

    <p>A paragraph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>

Answer №1

It appears that your code is correct, but there may be an issue with the cdn link. I have used a debug version for testing purposes.

Here is a functional example I have created for reference. If you are unable to download the PDF due to restrictions, you can try using this fiddle.

Demo: Download PDF

The CDN link I utilized is: JsPDF CDN Link. Feel free to explore other versions available.

function createPdf() {

  var doc = new jsPDF();
  
  source = $('#content')[0];
  
  specialElementHandlers = {
        '#editor': function (element, renderer) {
            return true
        }
    };
  
  doc.fromHTML(
    source,
    15,
    15, 
    {
      'width': 170,
      'elementHandlers': specialElementHandlers
    }
  );
  doc.save('sample-file.pdf')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="content">
     <h3>Hello, this is a H3 tag</h3>

    <p>A paragraph</p>
</div>
<div id="editor"></div>
<button onclick="javascript:createPdf()" id="cmd">generate PDF</button>

Answer №2

To resolve the issue of 'jsPDF is not defined', I found that using const doc = new jspdf.jsPDF() was the key, as illustrated in the example below:

<!DOCTYPE html>
<html lang="en>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
  <title>Convert <div> to PDF</title>
</head>
    <body>

        <div id="content">
            <h1>Hello, World!</h1>
        </div>

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

        <script>
        function generatePDF() {
        // Default export is a4 paper, portrait, using millimeters for units
        **const doc = new jspdf.jsPDF();**

        doc.text("Hello world!", 10, 10);
        doc.save("a4.pdf");
        }
        </script>

    </body>
</html>

Answer №3

After encountering a couple of key issues, I was able to find solutions by forking this repository. The first issue I identified was the lack of a link to jspdf. This can easily be rectified by including the following script tag in the html code:

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

The second issue pertained to adding the click event listener outside the ready() function. By doing so, you face two problems: the event might not be properly attached (ensure that you troubleshoot the ready() function) and variables defined within the ready() function are inaccessible (out of scope) in the click function. To resolve these issues, it is recommended to place the click listener inside the ready listener as shown below:

$( document ).ready(function() {

var doc = new jsPDF();
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};
$('#cmd').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});

})

Answer №4

When I think about VQR, it always brings up one question in my mind. Sometimes my app works in places without network connection. In those instances, the next line won't function without a network, right?

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

So, to address this issue, I decided to install it...

npm install jspdf --save

Now, the question is, which files do I need to copy to my Js folder for the line to work properly?

var doc = new jsPDF(); 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing the statusText of a 403 response in Axios (React, Express, Node.js)

Within my component, there is a register function that makes an API call. The API checks if the email already exists and provides an appropriate status and statusText based on the result. Below is the API call handler in my Express app: router.post(' ...

Utilizing jQuery to submit the form

After clicking the search icon, it displays an alert with the message ok, but not h. Based on the code snippet below, it is intended to display alerts for both ok and h. <?php if(isset($_POST['search'])){ echo "<script type='text/ ...

What steps should I take to ensure that clicking this button triggers the API request and returns the data in JSON format?

I'm attempting to have the button with id 'testp' return an api request in json format, however it seems to not be functioning properly. You can find the HTML code link here: https://github.com/atullu1234/REST-API-Developer-1/blob/main/js-bu ...

Vuetify's <v-text-field> feature automatically clears the input after selecting a result from Google Maps autocomplete

A dilemma I'm facing is with a page that has a <v-text-field> containing GoogleMaps autocomplete. The problem arises when Vuetify clears the input once an address is selected by the user. I have discovered that this complication is connected to ...

How to extract the HTML content from specific text nodes using Javascript

I have a piece of HTML that looks like this: <div id="editable_phrase"> <span data-id="42">My</span> <span data-id="43">very</span> <span data-id="1">first</span> <span data-id="21">phrase< ...

I must adjust the size of images based on the size of the viewer's screen

Hello everyone, I could really use some assistance as I am not an expert programmer but just a site admin. My issue is this: I have a website running on PHP and I want to display images to my members while keeping them within specific size limits so they ...

Angular.js can efficiently handle waiting for multiple resource calls and AJAX requests

I'm facing a challenge in my Angular.js application where I need to make three separate resource calls and then use the data together once all the requests are complete. Here are the three calls I need to make: # Retrieve the curriculum $scope.curric ...

Any ideas on how I can adjust this basic JSON to avoid triggering the "Circular structure to JSON" error?

Learning Journey I am currently teaching myself JavaScript and exploring JSON along the way. My current project involves developing a JavaScript WebScraper where I plan to store my results in JSON format. While I am aware of other methods like using data ...

Instruction on inserting NativeBase footer into my React Native application?

As someone new to React Native, I am trying to include a footer bar in my app. Below is the code snippet from my dashboard.js file where I attempted to add the footer bar, but it doesn't seem to be working as expected: import React, { memo } from &ap ...

Regular expression pattern for consistently capitalizing the phrases "CA" and "USA" in an address string

end_address = 'joe's home, 123 test avenue, los angeles, ca, usa 90210'; end_address = end_address.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); The outcome of this code will ...

Ways to retrieve dictionary keys as an array in Angular

Here is an example of an Angular dictionary: { ARRAY1: [{...}, {...}, {...}] ARRAY2: [{...}, {...}, {...}] ARRAY3: [{...}, {...}] ARRAY4: [{...}] } I want to show all the keys of arrays from this dictionary on an HTML page. I attempted to do ...

What is the process for storing an array in AdonisJs migrations?

Having trouble saving an array into a PostgreSQL database! 'use strict' const Schema = use('Schema'); class UsersSchema extends Schema { up () { this.create('users', (table) => { table.increments(); t ...

Can we establish communication between the backend and frontend in React JS by utilizing localstorage?

Trying to implement affiliate functionality on my eCommerce platform. The idea is that users who generate links will receive a commission if someone makes a purchase through those links. However, the challenge I'm facing is that I can't store the ...

Converting a JavaScript function to CoffeeScript, accepting jQuery's .map function and Selectors as parameters

I'm in the process of converting some JavaScript code into CoffeeScript and encountering an issue with a particular function. Here is the original functioning JS: $(".comformt_QA").change(function(){ var array = $(".comformt_QA").map(function() { ...

Is there a way to create a duplicate form without any pre-filled text when clicking the "next" button using JavaScript?

This form contains the details that I would like to display on the page again when clicking the "Add Another Module" button. <div> <form class="in-line" id="module_info"></form> <div style="display: flex;"> < ...

Save a PHP variable and then use it on an HTML page

Is there a way to preserve the value of LAST_INSERT_ID(), also known as Case_ID, so that it can be accessed in another HTML page? If so, what would be the best approach to achieve this? $query.= "insert into Picture (Case_Pic,Case_ID) values ...

Error: The call stack has reached the maximum size limit in nodejs and reactjs

When I attempt to submit the token received from my registration using the code snippet below, I encounter an error stating "maximum call stack exceeded." exports.activationController = (req, res) => { const { token } = req.body; exports.activation ...

The enigmatic loop traversal

Can you figure out why the name property of the merged object is properly set in the code below, even though the for-loop starts with i = 1? function merge(root){ for ( var i = 1; i < arguments.length; i++ ){ for ( var key in arguments[i] ){ ...

Using Angular.js, apply the "visible" class conditionally based on a variable

My Cordova application is built with angular.js and consists of the following 2 files: app.html <div ng-controller="MyAppCtrl as myApp" ng-class="myApp.isWindows() ? 'windows' : ''"> and app.controller MyAppCtrl.$inject = [&ap ...

Is there a way to guide users to their designated page on Node.js?

My goal is to seamlessly redirect users to their designated pages based on their role. If the user is a regular user, they should be redirected to the user menu. On the other hand, if it's an employee, they should be directed to the employee menu. E ...