-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
54 lines (42 loc) · 1.75 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
function convertToPDF() {
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
let input = document.getElementById('imageInput');
if (input.files.length === 0) {
alert('Please select at least one image.');
return;
}
let promises = [];
for (let i = 0; i < input.files.length; i++) {
const file = input.files[i];
const reader = new FileReader();
promises.push(new Promise((resolve) => {
reader.onload = function(event) {
const img = new Image();
img.src = event.target.result;
img.onload = function() {
const width = img.width;
const height = img.height;
const pageWidth = doc.internal.pageSize.getWidth();
const pageHeight = doc.internal.pageSize.getHeight();
// Fit the image within the PDF page, maintaining aspect ratio
const scaleFactor = Math.min(pageWidth / width, pageHeight / height);
const scaledWidth = width * scaleFactor;
const scaledHeight = height * scaleFactor;
doc.addImage(img, 'JPEG', 0, 0, scaledWidth, scaledHeight);
if (i < input.files.length - 1) {
doc.addPage();
}
resolve();
};
};
reader.readAsDataURL(file);
}));
}
Promise.all(promises).then(() => {
doc.save("converted.pdf");
});
}
if (window.innerWidth < 1024) {
document.querySelector("meta[name=viewport]").setAttribute("content", "width=1024");
}