Skip to content

Instantly share code, notes, and snippets.

@tomerof
Created May 16, 2023 18:48
Show Gist options
  • Save tomerof/6d2172b982bf7456226eac77d680a865 to your computer and use it in GitHub Desktop.
Save tomerof/6d2172b982bf7456226eac77d680a865 to your computer and use it in GitHub Desktop.
Generate PDF using Javascript and HTML

To create a PDF using JavaScript and HTML, you can utilize a JavaScript library called "jsPDF." jsPDF is a popular open-source library that allows you to generate PDF files programmatically. Here's an example of how you can use jsPDF to create a PDF document:

  1. Include the jsPDF library in your HTML file by adding the following script tag within the <head> section:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.3/jspdf.umd.min.js"></script>
  1. Create a button or trigger that will initiate the PDF creation process. For example:
<button onclick="generatePDF()">Generate PDF</button>
  1. Write JavaScript code to generate the PDF using jsPDF. In the script tag or external JavaScript file, define the generatePDF function:
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');
}

In this example, the generatePDF function creates a new jsPDF instance, adds the text "Hello, World!" to the PDF document at coordinates (10, 10), and saves the resulting PDF file with the name "sample.pdf" when the doc.save() method is called.

  1. Run the HTML file in a web browser and click the "Generate PDF" button. This will trigger the generatePDF function, generating and saving the PDF file.

Note: Depending on your requirements, you can add various elements, images, and styles to the PDF using the available methods and options provided by jsPDF. The library documentation (https://github.com/MrRio/jsPDF) offers detailed information on the features and capabilities of jsPDF, enabling you to customize your PDF creation as needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment