How to Generate PDF File in JavaScript

To generate a PDF file using JavaScript, you can utilize a library called jsPDF. It is a popular library that allows you to create PDF documents programmatically. Here’s an example of how to generate a basic PDF using jsPDF:

First, include the jsPDF library in your HTML file:

<!DOCTYPE html>
<html>
<head>
  <title>PDF Generation Example</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
</head>
<body>
  <button onclick="generatePDF()">Generate PDF</button>

  <script>
    function generatePDF() {
      // Create a new jsPDF instance
      const doc = new jsPDF();

      // Add content to the PDF
      doc.text('Hello, World!', 10, 10);

      // Save the PDF
      doc.save('sample.pdf');
    }
  </script>
</body>
</html>

In the example above, we have a simple HTML page with a button. When the button is clicked, the generatePDF function is called. Inside the function:

  1. We create a new instance of jsPDF using const doc = new jsPDF();.
  2. We add content to the PDF using doc.text('Hello, World!', 10, 10);. This adds the text “Hello, World!” at the position (10, 10) in the PDF.
  3. Finally, we save the PDF using doc.save('sample.pdf');. The generated PDF will be named “sample.pdf”.

When you click the “Generate PDF” button, it will create and download the PDF file. You can modify the content and formatting of the PDF according to your requirements using the various methods provided by the jsPDF library.

Remember to include the latest version of the jsPDF library by updating the script source URL in the HTML example to ensure you have the most up-to-date version of the library.

Comments

comments