Merge pull request #215 from Skillkiller/pdf-to-image-direct-image

Pdf to image direct image
This commit is contained in:
Alam
2026-03-09 22:05:19 +05:30
committed by GitHub
11 changed files with 966 additions and 725 deletions

View File

@@ -1,10 +1,20 @@
import { showLoader, hideLoader, showAlert } from '../ui.js';
import { downloadFile, formatBytes, readFileAsArrayBuffer, getPDFDocument } from '../utils/helpers.js';
import {
downloadFile,
formatBytes,
readFileAsArrayBuffer,
getPDFDocument,
getCleanPdfFilename,
} from '../utils/helpers.js';
import { createIcons, icons } from 'lucide';
import JSZip from 'jszip';
import * as pdfjsLib from 'pdfjs-dist';
import { PDFPageProxy } from 'pdfjs-dist';
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).toString();
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url
).toString();
let files: File[] = [];
@@ -22,7 +32,8 @@ const updateUI = () => {
files.forEach((file) => {
const fileDiv = document.createElement('div');
fileDiv.className = 'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
fileDiv.className =
'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
const infoContainer = document.createElement('div');
infoContainer.className = 'flex flex-col overflow-hidden';
@@ -39,7 +50,8 @@ const updateUI = () => {
// Add remove button
const removeBtn = document.createElement('button');
removeBtn.className = 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.className =
'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>';
removeBtn.onclick = () => {
files = [];
@@ -50,11 +62,14 @@ const updateUI = () => {
fileDisplayArea.appendChild(fileDiv);
// Fetch page count asynchronously
readFileAsArrayBuffer(file).then(buffer => {
readFileAsArrayBuffer(file)
.then((buffer) => {
return getPDFDocument(buffer).promise;
}).then(pdf => {
})
.then((pdf) => {
metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`;
}).catch(e => {
})
.catch((e) => {
console.warn('Error loading PDF page count:', e);
metaSpan.textContent = formatBytes(file.size);
});
@@ -81,34 +96,35 @@ async function convert() {
}
showLoader('Converting to BMP...');
try {
const pdf = await getPDFDocument(
await readFileAsArrayBuffer(files[0])
).promise;
const zip = new JSZip();
const pdf = await getPDFDocument(await readFileAsArrayBuffer(files[0]))
.promise;
if (pdf.numPages === 1) {
const page = await pdf.getPage(1);
const blob = await renderPage(page);
downloadFile(blob, getCleanPdfFilename(files[0].name) + '.bmp');
} else {
const zip = new JSZip();
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const viewport = page.getViewport({ scale: 2.0 });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
await page.render({ canvasContext: context!, viewport: viewport, canvas }).promise;
const blob = await new Promise<Blob | null>((resolve) =>
canvas.toBlob(resolve, 'image/bmp')
);
const blob = await renderPage(page);
if (blob) {
zip.file(`page_${i}.bmp`, blob);
}
}
const zipBlob = await zip.generateAsync({ type: 'blob' });
downloadFile(zipBlob, 'converted_images.zip');
showAlert('Success', 'PDF converted to BMPs successfully!', 'success', () => {
downloadFile(zipBlob, getCleanPdfFilename(files[0].name) + '_bmps.zip');
}
showAlert(
'Success',
'PDF converted to BMPs successfully!',
'success',
() => {
resetState();
});
}
);
} catch (e) {
console.error(e);
showAlert(
@@ -120,6 +136,25 @@ async function convert() {
}
}
async function renderPage(page: PDFPageProxy): Promise<Blob | null> {
const viewport = page.getViewport({ scale: 2.0 });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
await page.render({
canvasContext: context!,
viewport: viewport,
canvas,
}).promise;
const blob = await new Promise<Blob | null>((resolve) =>
canvas.toBlob(resolve, 'image/bmp')
);
return blob;
}
document.addEventListener('DOMContentLoaded', () => {
const fileInput = document.getElementById('file-input') as HTMLInputElement;
const dropZone = document.getElementById('drop-zone');

View File

@@ -1,10 +1,20 @@
import { showLoader, hideLoader, showAlert } from '../ui.js';
import { downloadFile, formatBytes, readFileAsArrayBuffer, getPDFDocument } from '../utils/helpers.js';
import {
downloadFile,
formatBytes,
readFileAsArrayBuffer,
getPDFDocument,
getCleanPdfFilename,
} from '../utils/helpers.js';
import { createIcons, icons } from 'lucide';
import JSZip from 'jszip';
import * as pdfjsLib from 'pdfjs-dist';
import { PDFPageProxy } from 'pdfjs-dist';
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).toString();
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url
).toString();
let files: File[] = [];
@@ -22,7 +32,8 @@ const updateUI = () => {
files.forEach((file) => {
const fileDiv = document.createElement('div');
fileDiv.className = 'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
fileDiv.className =
'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
const infoContainer = document.createElement('div');
infoContainer.className = 'flex flex-col overflow-hidden';
@@ -38,7 +49,8 @@ const updateUI = () => {
infoContainer.append(nameSpan, metaSpan);
const removeBtn = document.createElement('button');
removeBtn.className = 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.className =
'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>';
removeBtn.onclick = () => {
files = [];
@@ -49,11 +61,14 @@ const updateUI = () => {
fileDisplayArea.appendChild(fileDiv);
// Fetch page count asynchronously
readFileAsArrayBuffer(file).then(buffer => {
readFileAsArrayBuffer(file)
.then((buffer) => {
return getPDFDocument(buffer).promise;
}).then(pdf => {
})
.then((pdf) => {
metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`;
}).catch(e => {
})
.catch((e) => {
console.warn('Error loading PDF page count:', e);
metaSpan.textContent = formatBytes(file.size);
});
@@ -70,7 +85,9 @@ const resetState = () => {
files = [];
const fileInput = document.getElementById('file-input') as HTMLInputElement;
if (fileInput) fileInput.value = '';
const qualitySlider = document.getElementById('jpg-quality') as HTMLInputElement;
const qualitySlider = document.getElementById(
'jpg-quality'
) as HTMLInputElement;
const qualityValue = document.getElementById('jpg-quality-value');
if (qualitySlider) qualitySlider.value = '0.9';
if (qualityValue) qualityValue.textContent = '90%';
@@ -84,37 +101,40 @@ async function convert() {
}
showLoader('Converting to JPG...');
try {
const pdf = await getPDFDocument(
await readFileAsArrayBuffer(files[0])
).promise;
const zip = new JSZip();
const pdf = await getPDFDocument(await readFileAsArrayBuffer(files[0]))
.promise;
const qualityInput = document.getElementById('jpg-quality') as HTMLInputElement;
const qualityInput = document.getElementById(
'jpg-quality'
) as HTMLInputElement;
const quality = qualityInput ? parseFloat(qualityInput.value) : 0.9;
if (pdf.numPages === 1) {
const page = await pdf.getPage(1);
const blob = await renderPage(page, quality);
downloadFile(blob, getCleanPdfFilename(files[0].name) + '.jpg');
} else {
const zip = new JSZip();
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const viewport = page.getViewport({ scale: 2.0 });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
await page.render({ canvasContext: context!, viewport: viewport, canvas }).promise;
const blob = await new Promise<Blob | null>((resolve) =>
canvas.toBlob(resolve, 'image/jpeg', quality)
);
const blob = await renderPage(page, quality);
if (blob) {
zip.file(`page_${i}.jpg`, blob);
}
}
const zipBlob = await zip.generateAsync({ type: 'blob' });
downloadFile(zipBlob, 'converted_images.zip');
showAlert('Success', 'PDF converted to JPGs successfully!', 'success', () => {
downloadFile(zipBlob, getCleanPdfFilename(files[0].name) + '_jpgs.zip');
}
showAlert(
'Success',
'PDF converted to JPGs successfully!',
'success',
() => {
resetState();
});
}
);
} catch (e) {
console.error(e);
showAlert(
@@ -126,12 +146,36 @@ async function convert() {
}
}
async function renderPage(
page: PDFPageProxy,
quality: number
): Promise<Blob | null> {
const viewport = page.getViewport({ scale: 2.0 });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
await page.render({
canvasContext: context!,
viewport: viewport,
canvas,
}).promise;
const blob = await new Promise<Blob | null>((resolve) =>
canvas.toBlob(resolve, 'image/jpeg', quality)
);
return blob;
}
document.addEventListener('DOMContentLoaded', () => {
const fileInput = document.getElementById('file-input') as HTMLInputElement;
const dropZone = document.getElementById('drop-zone');
const processBtn = document.getElementById('process-btn');
const backBtn = document.getElementById('back-to-tools');
const qualitySlider = document.getElementById('jpg-quality') as HTMLInputElement;
const qualitySlider = document.getElementById(
'jpg-quality'
) as HTMLInputElement;
const qualityValue = document.getElementById('jpg-quality-value');
if (backBtn) {

View File

@@ -1,10 +1,20 @@
import { showLoader, hideLoader, showAlert } from '../ui.js';
import { downloadFile, formatBytes, readFileAsArrayBuffer, getPDFDocument } from '../utils/helpers.js';
import {
downloadFile,
formatBytes,
readFileAsArrayBuffer,
getPDFDocument,
getCleanPdfFilename,
} from '../utils/helpers.js';
import { createIcons, icons } from 'lucide';
import JSZip from 'jszip';
import * as pdfjsLib from 'pdfjs-dist';
import { PDFPageProxy } from 'pdfjs-dist';
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).toString();
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url
).toString();
let files: File[] = [];
@@ -22,7 +32,8 @@ const updateUI = () => {
files.forEach((file) => {
const fileDiv = document.createElement('div');
fileDiv.className = 'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
fileDiv.className =
'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
const infoContainer = document.createElement('div');
infoContainer.className = 'flex flex-col overflow-hidden';
@@ -38,7 +49,8 @@ const updateUI = () => {
infoContainer.append(nameSpan, metaSpan);
const removeBtn = document.createElement('button');
removeBtn.className = 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.className =
'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>';
removeBtn.onclick = () => {
files = [];
@@ -49,11 +61,14 @@ const updateUI = () => {
fileDisplayArea.appendChild(fileDiv);
// Fetch page count asynchronously
readFileAsArrayBuffer(file).then(buffer => {
readFileAsArrayBuffer(file)
.then((buffer) => {
return getPDFDocument(buffer).promise;
}).then(pdf => {
})
.then((pdf) => {
metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`;
}).catch(e => {
})
.catch((e) => {
console.warn('Error loading PDF page count:', e);
metaSpan.textContent = formatBytes(file.size);
});
@@ -84,37 +99,38 @@ async function convert() {
}
showLoader('Converting to PNG...');
try {
const pdf = await getPDFDocument(
await readFileAsArrayBuffer(files[0])
).promise;
const zip = new JSZip();
const pdf = await getPDFDocument(await readFileAsArrayBuffer(files[0]))
.promise;
const scaleInput = document.getElementById('png-scale') as HTMLInputElement;
const scale = scaleInput ? parseFloat(scaleInput.value) : 2.0;
if (pdf.numPages === 1) {
const page = await pdf.getPage(1);
const blob = await renderPage(page, scale);
downloadFile(blob, getCleanPdfFilename(files[0].name) + '.png');
} else {
const zip = new JSZip();
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const viewport = page.getViewport({ scale });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
await page.render({ canvasContext: context!, viewport: viewport, canvas }).promise;
const blob = await new Promise<Blob | null>((resolve) =>
canvas.toBlob(resolve, 'image/png')
);
const blob = await renderPage(page, scale);
if (blob) {
zip.file(`page_${i}.png`, blob);
}
}
const zipBlob = await zip.generateAsync({ type: 'blob' });
downloadFile(zipBlob, 'converted_images.zip');
showAlert('Success', 'PDF converted to PNGs successfully!', 'success', () => {
downloadFile(zipBlob, getCleanPdfFilename(files[0].name) + '_pngs.zip');
}
showAlert(
'Success',
'PDF converted to PNGs successfully!',
'success',
() => {
resetState();
});
}
);
} catch (e) {
console.error(e);
showAlert(
@@ -126,6 +142,28 @@ async function convert() {
}
}
async function renderPage(
page: PDFPageProxy,
scale: number
): Promise<Blob | null> {
const viewport = page.getViewport({ scale });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
await page.render({
canvasContext: context!,
viewport: viewport,
canvas,
}).promise;
const blob = await new Promise<Blob | null>((resolve) =>
canvas.toBlob(resolve, 'image/png')
);
return blob;
}
document.addEventListener('DOMContentLoaded', () => {
const fileInput = document.getElementById('file-input') as HTMLInputElement;
const dropZone = document.getElementById('drop-zone');

View File

@@ -1,11 +1,21 @@
import { showLoader, hideLoader, showAlert } from '../ui.js';
import { downloadFile, formatBytes, readFileAsArrayBuffer, getPDFDocument } from '../utils/helpers.js';
import {
downloadFile,
formatBytes,
readFileAsArrayBuffer,
getPDFDocument,
getCleanPdfFilename,
} from '../utils/helpers.js';
import { createIcons, icons } from 'lucide';
import JSZip from 'jszip';
import * as pdfjsLib from 'pdfjs-dist';
import UTIF from 'utif';
import { PDFPageProxy } from 'pdfjs-dist';
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).toString();
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url
).toString();
let files: File[] = [];
@@ -23,7 +33,8 @@ const updateUI = () => {
files.forEach((file) => {
const fileDiv = document.createElement('div');
fileDiv.className = 'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
fileDiv.className =
'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
const infoContainer = document.createElement('div');
infoContainer.className = 'flex flex-col overflow-hidden';
@@ -39,7 +50,8 @@ const updateUI = () => {
infoContainer.append(nameSpan, metaSpan);
const removeBtn = document.createElement('button');
removeBtn.className = 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.className =
'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>';
removeBtn.onclick = () => {
files = [];
@@ -50,11 +62,14 @@ const updateUI = () => {
fileDisplayArea.appendChild(fileDiv);
// Fetch page count asynchronously
readFileAsArrayBuffer(file).then(buffer => {
readFileAsArrayBuffer(file)
.then((buffer) => {
return getPDFDocument(buffer).promise;
}).then(pdf => {
})
.then((pdf) => {
metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`;
}).catch(e => {
})
.catch((e) => {
console.warn('Error loading PDF page count:', e);
metaSpan.textContent = formatBytes(file.size);
});
@@ -81,45 +96,38 @@ async function convert() {
}
showLoader('Converting to TIFF...');
try {
const pdf = await getPDFDocument(
await readFileAsArrayBuffer(files[0])
).promise;
const zip = new JSZip();
const pdf = await getPDFDocument(await readFileAsArrayBuffer(files[0]))
.promise;
if (pdf.numPages === 1) {
const page = await pdf.getPage(1);
const blob = await renderPage(page, 1);
downloadFile(
blob.blobData,
getCleanPdfFilename(files[0].name) + '.' + blob.ending
);
} else {
const zip = new JSZip();
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const viewport = page.getViewport({ scale: 2.0 });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
await page.render({ canvasContext: context!, viewport: viewport, canvas }).promise;
const imageData = context!.getImageData(0, 0, canvas.width, canvas.height);
const rgba = imageData.data;
try {
const tiffData = UTIF.encodeImage(new Uint8Array(rgba), canvas.width, canvas.height);
const tiffBlob = new Blob([tiffData], { type: 'image/tiff' });
zip.file(`page_${i}.tiff`, tiffBlob);
} catch (encodeError: any) {
console.warn(`TIFF encoding failed for page ${i}, using PNG fallback:`, encodeError);
// Fallback to PNG if TIFF encoding fails (e.g., PackBits compression issues)
const pngBlob = await new Promise<Blob | null>((resolve) =>
canvas.toBlob(resolve, 'image/png')
);
if (pngBlob) {
zip.file(`page_${i}.png`, pngBlob);
}
const blob = await renderPage(page, i);
if (blob.blobData) {
zip.file(`page_${i}.` + blob.ending, blob.blobData);
}
}
const zipBlob = await zip.generateAsync({ type: 'blob' });
downloadFile(zipBlob, 'converted_images.zip');
showAlert('Success', 'PDF converted to TIFFs successfully!', 'success', () => {
downloadFile(zipBlob, getCleanPdfFilename(files[0].name) + '_tiffs.zip');
}
showAlert(
'Success',
'PDF converted to TIFFs successfully!',
'success',
() => {
resetState();
});
}
);
} catch (e) {
console.error(e);
showAlert(
@@ -131,6 +139,59 @@ async function convert() {
}
}
async function renderPage(
page: PDFPageProxy,
pageNumber: number
): Promise<{ blobData: Blob | null; ending: string }> {
const viewport = page.getViewport({ scale: 2.0 });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
await page.render({
canvasContext: context!,
viewport: viewport,
canvas,
}).promise;
const imageData = context!.getImageData(0, 0, canvas.width, canvas.height);
const rgba = imageData.data;
try {
const tiffData = UTIF.encodeImage(
new Uint8Array(rgba),
canvas.width,
canvas.height
);
const tiffBlob = new Blob([tiffData], { type: 'image/tiff' });
return {
blobData: tiffBlob,
ending: 'tiff',
};
} catch (encodeError: any) {
console.warn(
`TIFF encoding failed for page ${pageNumber}, using PNG fallback:`,
encodeError
);
// Fallback to PNG if TIFF encoding fails (e.g., PackBits compression issues)
const pngBlob = await new Promise<Blob | null>((resolve) =>
canvas.toBlob(resolve, 'image/png')
);
if (pngBlob) {
return {
blobData: pngBlob,
ending: 'png',
};
}
}
return {
blobData: null,
ending: 'tiff',
};
}
document.addEventListener('DOMContentLoaded', () => {
const fileInput = document.getElementById('file-input') as HTMLInputElement;
const dropZone = document.getElementById('drop-zone');

View File

@@ -1,10 +1,20 @@
import { showLoader, hideLoader, showAlert } from '../ui.js';
import { downloadFile, formatBytes, readFileAsArrayBuffer, getPDFDocument } from '../utils/helpers.js';
import {
downloadFile,
formatBytes,
readFileAsArrayBuffer,
getPDFDocument,
getCleanPdfFilename,
} from '../utils/helpers.js';
import { createIcons, icons } from 'lucide';
import JSZip from 'jszip';
import * as pdfjsLib from 'pdfjs-dist';
import { PDFPageProxy } from 'pdfjs-dist';
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).toString();
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url
).toString();
let files: File[] = [];
@@ -22,7 +32,8 @@ const updateUI = () => {
files.forEach((file) => {
const fileDiv = document.createElement('div');
fileDiv.className = 'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
fileDiv.className =
'flex items-center justify-between bg-gray-700 p-3 rounded-lg text-sm';
const infoContainer = document.createElement('div');
infoContainer.className = 'flex flex-col overflow-hidden';
@@ -38,7 +49,8 @@ const updateUI = () => {
infoContainer.append(nameSpan, metaSpan);
const removeBtn = document.createElement('button');
removeBtn.className = 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.className =
'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>';
removeBtn.onclick = () => {
files = [];
@@ -49,11 +61,14 @@ const updateUI = () => {
fileDisplayArea.appendChild(fileDiv);
// Fetch page count asynchronously
readFileAsArrayBuffer(file).then(buffer => {
readFileAsArrayBuffer(file)
.then((buffer) => {
return getPDFDocument(buffer).promise;
}).then(pdf => {
})
.then((pdf) => {
metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`;
}).catch(e => {
})
.catch((e) => {
console.warn('Error loading PDF page count:', e);
metaSpan.textContent = formatBytes(file.size);
});
@@ -70,7 +85,9 @@ const resetState = () => {
files = [];
const fileInput = document.getElementById('file-input') as HTMLInputElement;
if (fileInput) fileInput.value = '';
const qualitySlider = document.getElementById('webp-quality') as HTMLInputElement;
const qualitySlider = document.getElementById(
'webp-quality'
) as HTMLInputElement;
const qualityValue = document.getElementById('webp-quality-value');
if (qualitySlider) qualitySlider.value = '0.85';
if (qualityValue) qualityValue.textContent = '85%';
@@ -84,37 +101,40 @@ async function convert() {
}
showLoader('Converting to WebP...');
try {
const pdf = await getPDFDocument(
await readFileAsArrayBuffer(files[0])
).promise;
const zip = new JSZip();
const pdf = await getPDFDocument(await readFileAsArrayBuffer(files[0]))
.promise;
const qualityInput = document.getElementById('webp-quality') as HTMLInputElement;
const qualityInput = document.getElementById(
'webp-quality'
) as HTMLInputElement;
const quality = qualityInput ? parseFloat(qualityInput.value) : 0.85;
if (pdf.numPages === 1) {
const page = await pdf.getPage(1);
const blob = await renderPage(page, quality);
downloadFile(blob, getCleanPdfFilename(files[0].name) + '.webp');
} else {
const zip = new JSZip();
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const viewport = page.getViewport({ scale: 2.0 });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
await page.render({ canvasContext: context!, viewport: viewport, canvas }).promise;
const blob = await new Promise<Blob | null>((resolve) =>
canvas.toBlob(resolve, 'image/webp', quality)
);
const blob = await renderPage(page, quality);
if (blob) {
zip.file(`page_${i}.webp`, blob);
}
}
const zipBlob = await zip.generateAsync({ type: 'blob' });
downloadFile(zipBlob, 'converted_images.zip');
showAlert('Success', 'PDF converted to WebPs successfully!', 'success', () => {
downloadFile(zipBlob, getCleanPdfFilename(files[0].name) + '_webps.zip');
}
showAlert(
'Success',
'PDF converted to WebPs successfully!',
'success',
() => {
resetState();
});
}
);
} catch (e) {
console.error(e);
showAlert(
@@ -126,12 +146,36 @@ async function convert() {
}
}
async function renderPage(
page: PDFPageProxy,
quality: number
): Promise<Blob | null> {
const viewport = page.getViewport({ scale: 2.0 });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
await page.render({
canvasContext: context!,
viewport: viewport,
canvas,
}).promise;
const blob = await new Promise<Blob | null>((resolve) =>
canvas.toBlob(resolve, 'image/webp', quality)
);
return blob;
}
document.addEventListener('DOMContentLoaded', () => {
const fileInput = document.getElementById('file-input') as HTMLInputElement;
const dropZone = document.getElementById('drop-zone');
const processBtn = document.getElementById('process-btn');
const backBtn = document.getElementById('back-to-tools');
const qualitySlider = document.getElementById('webp-quality') as HTMLInputElement;
const qualitySlider = document.getElementById(
'webp-quality'
) as HTMLInputElement;
const qualityValue = document.getElementById('webp-quality-value');
if (backBtn) {

View File

@@ -29,7 +29,7 @@ export function getStandardPageName(width: any, height: any) {
}
export function convertPoints(points: any, unit: any) {
let result = 0;
let result: number;
switch (unit) {
case 'in':
result = points / 72;
@@ -460,3 +460,22 @@ export function formatRawDate(raw: string): string {
}
return raw;
}
/**
* Returns a sanitized PDF filename.
*
* The provided filename is processed as follows:
* - Removes a trailing `.pdf` file extension (case-insensitive)
* - Trims leading and trailing whitespace
* - Truncates the name to a maximum of 80 characters
*
* @param filename The original filename (including extension)
* @returns The sanitized filename without the `.pdf` extension, limited to 80 characters
*/
export function getCleanPdfFilename(filename: string): string {
let clean = filename.replace(/\.pdf$/i, '').trim();
if (clean.length > 80) {
clean = clean.slice(0, 80);
}
return clean;
}

View File

@@ -160,7 +160,7 @@
<div id="options-panel" class="hidden mt-6">
<button id="process-btn" class="btn-gradient w-full">
Download All as ZIP
Download All
</button>
</div>
</div>

View File

@@ -190,7 +190,7 @@
</div>
<button id="process-btn" class="btn-gradient w-full">
Download All as ZIP
Download All
</button>
</div>
</div>

View File

@@ -187,7 +187,7 @@
</div>
<button id="process-btn" class="btn-gradient w-full">
Download All as ZIP
Download All
</button>
</div>
</div>

View File

@@ -155,7 +155,7 @@
<div id="file-display-area" class="mt-4 space-y-2"></div>
<div id="options-panel" class="hidden mt-6">
<button id="process-btn" class="btn-gradient w-full">
Download All as ZIP
Download All
</button>
</div>
</div>

View File

@@ -187,7 +187,7 @@
</div>
<button id="process-btn" class="btn-gradient w-full">
Download All as ZIP
Download All
</button>
</div>
</div>