Ask Your Question

Revision history [back]

To use jsPDF with an HTML and JavaScript form, the following steps can be followed:

  1. First, include the jsPDF library in the HTML file by adding the following line in the head section of the HTML document:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
  1. Inside the JavaScript file, create a function that extracts the data from the form fields and passes it to jsPDF to generate a PDF document. For example:
function generatePDF() {
  // Extracting data from form fields
  const name = document.getElementById("name").value;
  const email = document.getElementById("email").value;
  const phone = document.getElementById("phone").value;

  // Creating a new instance of jsPDF
  const doc = new jsPDF();

  // Adding the data to the PDF document
  doc.text(`Name: ${name}`, 10, 10);
  doc.text(`Email: ${email}`, 10, 20);
  doc.text(`Phone: ${phone}`, 10, 30);

  // Saving the PDF document
  doc.save("form-data.pdf");
}
  1. In the HTML file, add a button that calls the above function when clicked. For example:
<button onclick="generatePDF()">Generate PDF</button>
  1. Finally, add form fields in the HTML file for users to input data. For example:
<form>
  <label for="name">Name:</label>
  <input type="text" id="name" name="name"><br><br>

  <label for="email">Email:</label>
  <input type="email" id="email" name="email"><br><br>

  <label for="phone">Phone:</label>
  <input type="tel" id="phone" name="phone"><br><br>
</form>

With the above setup, when a user fills in the form fields and clicks the "Generate PDF" button, the data will be extracted and added to the PDF document using jsPDF, and the document will be downloadable with the filename "form-data.pdf".