Detailed jsPDF Tutorial & Demo
Developed by: Md Shagor
What is jsPDF?
jsPDF is a popular open-source JavaScript library that allows you to generate PDF files directly in the browser, without server-side code. This makes it great for client-side PDF creation and downloads.
How to use jsPDF?
- Include the jsPDF library via CDN or locally.
- Create a
jsPDF
object instance in JavaScript. - Add content like text, images, shapes using built-in methods.
- Save or open the PDF file in browser with
save()
oroutput()
.
Basic Example Code
const {'{'} jsPDF {'}'} = window.jspdf; const doc = new jsPDF(); doc.text("Hello from Md Shagor!", 20, 20); doc.save("example.pdf");
More Examples & Features
1. Adding Multiple Lines of Text
const doc = new jsPDF(); doc.text("Line 1: Hello!", 10, 10); doc.text("Line 2: jsPDF is awesome.", 10, 20); doc.text("Line 3: Created by Md Shagor.", 10, 30); doc.save("multiline.pdf");
2. Setting Font Size and Color
doc.setFontSize(22); doc.setTextColor("#FF0000"); doc.text("Red Big Text", 15, 50); doc.save("color-text.pdf");
3. Adding a Rectangle Shape
doc.setDrawColor(0); doc.setFillColor(0, 255, 0); // green fill doc.rect(10, 60, 50, 20, "F"); // x, y, width, height, style 'F' fill doc.save("rectangle.pdf");
4. Adding a New Page
doc.text("Page 1 content", 10, 10); doc.addPage(); doc.text("Page 2 content", 10, 10); doc.save("multipage.pdf");
5. Adding Images
(Base64 Image Example)
const imgData = 'data:image/jpeg;base64,...'; // your base64 encoded image string here doc.addImage(imgData, 'JPEG', 15, 40, 180, 160); doc.save("image.pdf");
6. Saving the PDF
Finally, use doc.save("filename.pdf")
to prompt the user to download the PDF file.
Full JavaScript Code for This Page's Demo
function generatePDF() { const {'{'} jsPDF {'}'} = window.jspdf; const doc = new jsPDF(); doc.setFontSize(22); doc.setTextColor("#0056b3"); doc.text("jsPDF PDF Export Example", 20, 30); doc.setFontSize(16); doc.setTextColor("#333"); doc.text("Developed by: Md Shagor", 20, 45); doc.setFontSize(14); doc.text("This PDF is generated with jsPDF library in browser.", 20, 60); doc.setFontSize(12); doc.text("Features demonstrated:", 20, 80); doc.text("- Add text with different sizes and colors", 30, 90); doc.text("- Draw shapes like rectangles", 30, 100); doc.text("- Add multiple pages", 30, 110); // Draw a green filled rectangle doc.setDrawColor(0); doc.setFillColor(0, 180, 0); doc.rect(20, 120, 50, 25, "F"); // Add new page and some text there doc.addPage(); doc.setFontSize(16); doc.setTextColor("#007bff"); doc.text("Second Page", 20, 30); doc.setFontSize(12); doc.setTextColor("#555"); doc.text("Generated by Md Shagor with jsPDF.", 20, 45); doc.save("Md_Shagor_jsPDF_Detailed_Demo.pdf"); }