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:
- 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>
- Create a button or trigger that will initiate the PDF creation process. For example:
<button onclick="generatePDF()">Generate PDF</button>
- 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.
- 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.