To create a basic PDF file using JavaScript and allow the user to download it, you can use popular jsPDF libray. You can either download it or use a CDN
Generate a PDF file.
Clicked the getPDF button below
Basic Example: of Download PDF
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create PDF with jsPDF</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js" defer></script>
</head>
<body>
<h1>Generate PDF File Example</h1>
<button onclick="generatePDF()">Download PDF</button>
<script>
function generatePDF() {
// Load jsPDF
const { jsPDF } = window.jspdf;
// Create a new PDF document
const doc = new jsPDF();
// Add some text
doc.text("Hello World!", 10, 10);
// Download the PDF
doc.save("example.pdf");
}
</script>
</body>
</html>
Explanation
jsPDF: A popular JavaScript library for creating PDF files.
doc.text("Hello world!!",10,10) This method adds the text "Hello World!" at the coordinates (10, 10) on the PDF page.
doc.save(pdfExample.pdf): This saves and triggers the download of the PDF file name pdfExample.pdf