How to generate PDF in javascript with example.

137 views 5:45 am 0 Comments June 24, 2024

Here’s a complete example that demonstrates how to use jsPDF to create a PDF document with text, shapes, and an image. Make sure you have included the jsPDF library in your HTML file as described earlier.

For example:




<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Generate PDF Example</title>
<!-- Include jsPDF library -->
<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
var doc = new jsPDF();

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

// Add a rectangle
doc.rect(20, 20, 50, 50);

// Add an image (using Data URI obtained from a placeholder image)
var imgData = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBYRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAF6dpAAQAAAABAAAAJ6kAAwAAAABAAABK...'; // Replace with your image data
doc.addImage(imgData, 'JPEG', 10, 70, 50, 50);

// Set font size and style
doc.setFontSize(16);
doc.setFontStyle('italic');

// Add more text
doc.text('This is a sample PDF document generated using jsPDF.', 10, 140);

// Save the PDF with name "example.pdf"
doc.save('example.pdf');
}
</script>
</body>
</html>