Here’s a simple example of HTML and JavaScript code to convert an image to a PDF using the jsPDF library.
1. First, include the jsPDF library in your HTML.
2. Add an image input and a button to trigger the conversion.
3. Use JavaScript to convert the selected image to PDF.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image to PDF</title>
</head>
<body>
<h2>Convert Image to PDF</h2>
<!-- Image upload -->
<input type="file" id="imageInput" accept="image/*">
<!-- Button to convert to PDF -->
<button onclick="convertToPDF()">Convert to PDF</button>
<!-- jsPDF library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script>
function convertToPDF() {
// Get the file input element
var input = document.getElementById('imageInput');
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
// Create a new PDF document
const { jsPDF } = window.jspdf;
var doc = new jsPDF();
// Load the image data
var imgData = e.target.result;
// Add the image to the PDF
doc.addImage(imgData, 'JPEG', 10, 10, 180, 160); // Adjust dimensions accordingly
// Save the PDF
doc.save('image.pdf');
};
// Read the image file as a Data URL
reader.readAsDataURL(input.files[0]);
} else {
alert("Please select an image file.");
}
}
</script>
</body>
</html>
Explanation:
1. Image Input: The user can upload an image using the <input> element.
2. Convert to PDF Button: Clicking the button triggers the convertToPDF() function.
3. jsPDF Library: This library is used to generate the PDF from the image.
4. FileReader API: Reads the uploaded image file and converts it into a base64-encoded URL that jsPDF can use to add the image to the PDF.
You can adjust the image size and position within the PDF by changing the parameters in doc.addImage().
👍 thanks bro...
ReplyDeleteWelcome
ReplyDelete