Ask Your Question
1

How can jsPDF be used with an HTML and JavaScript form?

asked 2023-06-10 17:55:06 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-10 18:18:01 +0000

huitzilopochtli gravatar image

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".

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-10 17:55:06 +0000

Seen: 17 times

Last updated: Jun 10 '23