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,179 +1,214 @@
import { showLoader, hideLoader, showAlert } from '../ui.js'; 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 { createIcons, icons } from 'lucide';
import JSZip from 'jszip'; import JSZip from 'jszip';
import * as pdfjsLib from 'pdfjs-dist'; 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[] = []; let files: File[] = [];
const updateUI = () => { const updateUI = () => {
const fileDisplayArea = document.getElementById('file-display-area'); const fileDisplayArea = document.getElementById('file-display-area');
const optionsPanel = document.getElementById('options-panel'); const optionsPanel = document.getElementById('options-panel');
const dropZone = document.getElementById('drop-zone'); const dropZone = document.getElementById('drop-zone');
if (!fileDisplayArea || !optionsPanel || !dropZone) return; if (!fileDisplayArea || !optionsPanel || !dropZone) return;
fileDisplayArea.innerHTML = ''; fileDisplayArea.innerHTML = '';
if (files.length > 0) { if (files.length > 0) {
optionsPanel.classList.remove('hidden'); optionsPanel.classList.remove('hidden');
files.forEach((file) => { files.forEach((file) => {
const fileDiv = document.createElement('div'); 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'); const infoContainer = document.createElement('div');
infoContainer.className = 'flex flex-col overflow-hidden'; infoContainer.className = 'flex flex-col overflow-hidden';
const nameSpan = document.createElement('div'); const nameSpan = document.createElement('div');
nameSpan.className = 'truncate font-medium text-gray-200 text-sm mb-1'; nameSpan.className = 'truncate font-medium text-gray-200 text-sm mb-1';
nameSpan.textContent = file.name; nameSpan.textContent = file.name;
const metaSpan = document.createElement('div'); const metaSpan = document.createElement('div');
metaSpan.className = 'text-xs text-gray-400'; metaSpan.className = 'text-xs text-gray-400';
metaSpan.textContent = `${formatBytes(file.size)} • Loading pages...`; // Initial state metaSpan.textContent = `${formatBytes(file.size)} • Loading pages...`; // Initial state
infoContainer.append(nameSpan, metaSpan); infoContainer.append(nameSpan, metaSpan);
// Add remove button // Add remove button
const removeBtn = document.createElement('button'); const removeBtn = document.createElement('button');
removeBtn.className = 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0'; removeBtn.className =
removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>'; 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.onclick = () => { removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>';
files = []; removeBtn.onclick = () => {
updateUI(); files = [];
}; updateUI();
};
fileDiv.append(infoContainer, removeBtn); fileDiv.append(infoContainer, removeBtn);
fileDisplayArea.appendChild(fileDiv); fileDisplayArea.appendChild(fileDiv);
// Fetch page count asynchronously // Fetch page count asynchronously
readFileAsArrayBuffer(file).then(buffer => { readFileAsArrayBuffer(file)
return getPDFDocument(buffer).promise; .then((buffer) => {
}).then(pdf => { return getPDFDocument(buffer).promise;
metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`; })
}).catch(e => { .then((pdf) => {
console.warn('Error loading PDF page count:', e); metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`;
metaSpan.textContent = formatBytes(file.size); })
}); .catch((e) => {
console.warn('Error loading PDF page count:', e);
metaSpan.textContent = formatBytes(file.size);
}); });
});
// Initialize icons immediately after synchronous render // Initialize icons immediately after synchronous render
createIcons({ icons }); createIcons({ icons });
} else { } else {
optionsPanel.classList.add('hidden'); optionsPanel.classList.add('hidden');
} }
}; };
const resetState = () => { const resetState = () => {
files = []; files = [];
const fileInput = document.getElementById('file-input') as HTMLInputElement; const fileInput = document.getElementById('file-input') as HTMLInputElement;
if (fileInput) fileInput.value = ''; if (fileInput) fileInput.value = '';
updateUI(); updateUI();
}; };
async function convert() { async function convert() {
if (files.length === 0) { if (files.length === 0) {
showAlert('No File', 'Please upload a PDF file first.'); showAlert('No File', 'Please upload a PDF file first.');
return; return;
} }
showLoader('Converting to BMP...'); showLoader('Converting to BMP...');
try { try {
const pdf = await getPDFDocument( const pdf = await getPDFDocument(await readFileAsArrayBuffer(files[0]))
await readFileAsArrayBuffer(files[0]) .promise;
).promise;
const zip = new JSZip();
for (let i = 1; i <= pdf.numPages; i++) { if (pdf.numPages === 1) {
const page = await pdf.getPage(i); const page = await pdf.getPage(1);
const viewport = page.getViewport({ scale: 2.0 }); const blob = await renderPage(page);
const canvas = document.createElement('canvas'); downloadFile(blob, getCleanPdfFilename(files[0].name) + '.bmp');
const context = canvas.getContext('2d'); } else {
canvas.height = viewport.height; const zip = new JSZip();
canvas.width = viewport.width; for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
await page.render({ canvasContext: context!, viewport: viewport, canvas }).promise; const blob = await renderPage(page);
if (blob) {
const blob = await new Promise<Blob | null>((resolve) => zip.file(`page_${i}.bmp`, blob);
canvas.toBlob(resolve, 'image/bmp')
);
if (blob) {
zip.file(`page_${i}.bmp`, blob);
}
} }
}
const zipBlob = await zip.generateAsync({ type: 'blob' }); const zipBlob = await zip.generateAsync({ type: 'blob' });
downloadFile(zipBlob, 'converted_images.zip'); downloadFile(zipBlob, getCleanPdfFilename(files[0].name) + '_bmps.zip');
showAlert('Success', 'PDF converted to BMPs successfully!', 'success', () => {
resetState();
});
} catch (e) {
console.error(e);
showAlert(
'Error',
'Failed to convert PDF to BMP. The file might be corrupted.'
);
} finally {
hideLoader();
} }
showAlert(
'Success',
'PDF converted to BMPs successfully!',
'success',
() => {
resetState();
}
);
} catch (e) {
console.error(e);
showAlert(
'Error',
'Failed to convert PDF to BMP. The file might be corrupted.'
);
} finally {
hideLoader();
}
}
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', () => { document.addEventListener('DOMContentLoaded', () => {
const fileInput = document.getElementById('file-input') as HTMLInputElement; const fileInput = document.getElementById('file-input') as HTMLInputElement;
const dropZone = document.getElementById('drop-zone'); const dropZone = document.getElementById('drop-zone');
const processBtn = document.getElementById('process-btn'); const processBtn = document.getElementById('process-btn');
const backBtn = document.getElementById('back-to-tools'); const backBtn = document.getElementById('back-to-tools');
if (backBtn) { if (backBtn) {
backBtn.addEventListener('click', () => { backBtn.addEventListener('click', () => {
window.location.href = import.meta.env.BASE_URL; window.location.href = import.meta.env.BASE_URL;
}); });
}
const handleFileSelect = (newFiles: FileList | null) => {
if (!newFiles || newFiles.length === 0) return;
const validFiles = Array.from(newFiles).filter(
(file) => file.type === 'application/pdf'
);
if (validFiles.length === 0) {
showAlert('Invalid File', 'Please upload a PDF file.');
return;
} }
const handleFileSelect = (newFiles: FileList | null) => { files = [validFiles[0]];
if (!newFiles || newFiles.length === 0) return; updateUI();
const validFiles = Array.from(newFiles).filter( };
(file) => file.type === 'application/pdf'
);
if (validFiles.length === 0) { if (fileInput && dropZone) {
showAlert('Invalid File', 'Please upload a PDF file.'); fileInput.addEventListener('change', (e) => {
return; handleFileSelect((e.target as HTMLInputElement).files);
} });
files = [validFiles[0]]; dropZone.addEventListener('dragover', (e) => {
updateUI(); e.preventDefault();
}; dropZone.classList.add('bg-gray-700');
});
if (fileInput && dropZone) { dropZone.addEventListener('dragleave', (e) => {
fileInput.addEventListener('change', (e) => { e.preventDefault();
handleFileSelect((e.target as HTMLInputElement).files); dropZone.classList.remove('bg-gray-700');
}); });
dropZone.addEventListener('dragover', (e) => { dropZone.addEventListener('drop', (e) => {
e.preventDefault(); e.preventDefault();
dropZone.classList.add('bg-gray-700'); dropZone.classList.remove('bg-gray-700');
}); handleFileSelect(e.dataTransfer?.files ?? null);
});
dropZone.addEventListener('dragleave', (e) => { fileInput.addEventListener('click', () => {
e.preventDefault(); fileInput.value = '';
dropZone.classList.remove('bg-gray-700'); });
}); }
dropZone.addEventListener('drop', (e) => { if (processBtn) {
e.preventDefault(); processBtn.addEventListener('click', convert);
dropZone.classList.remove('bg-gray-700'); }
handleFileSelect(e.dataTransfer?.files ?? null);
});
fileInput.addEventListener('click', () => {
fileInput.value = '';
});
}
if (processBtn) {
processBtn.addEventListener('click', convert);
}
}); });

View File

@@ -1,193 +1,237 @@
import { showLoader, hideLoader, showAlert } from '../ui.js'; 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 { createIcons, icons } from 'lucide';
import JSZip from 'jszip'; import JSZip from 'jszip';
import * as pdfjsLib from 'pdfjs-dist'; 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[] = []; let files: File[] = [];
const updateUI = () => { const updateUI = () => {
const fileDisplayArea = document.getElementById('file-display-area'); const fileDisplayArea = document.getElementById('file-display-area');
const optionsPanel = document.getElementById('options-panel'); const optionsPanel = document.getElementById('options-panel');
const dropZone = document.getElementById('drop-zone'); const dropZone = document.getElementById('drop-zone');
if (!fileDisplayArea || !optionsPanel || !dropZone) return; if (!fileDisplayArea || !optionsPanel || !dropZone) return;
fileDisplayArea.innerHTML = ''; fileDisplayArea.innerHTML = '';
if (files.length > 0) { if (files.length > 0) {
optionsPanel.classList.remove('hidden'); optionsPanel.classList.remove('hidden');
files.forEach((file) => { files.forEach((file) => {
const fileDiv = document.createElement('div'); 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'); const infoContainer = document.createElement('div');
infoContainer.className = 'flex flex-col overflow-hidden'; infoContainer.className = 'flex flex-col overflow-hidden';
const nameSpan = document.createElement('div'); const nameSpan = document.createElement('div');
nameSpan.className = 'truncate font-medium text-gray-200 text-sm mb-1'; nameSpan.className = 'truncate font-medium text-gray-200 text-sm mb-1';
nameSpan.textContent = file.name; nameSpan.textContent = file.name;
const metaSpan = document.createElement('div'); const metaSpan = document.createElement('div');
metaSpan.className = 'text-xs text-gray-400'; metaSpan.className = 'text-xs text-gray-400';
metaSpan.textContent = `${formatBytes(file.size)} • Loading pages...`; // Initial state metaSpan.textContent = `${formatBytes(file.size)} • Loading pages...`; // Initial state
infoContainer.append(nameSpan, metaSpan); infoContainer.append(nameSpan, metaSpan);
const removeBtn = document.createElement('button'); const removeBtn = document.createElement('button');
removeBtn.className = 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0'; removeBtn.className =
removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>'; 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.onclick = () => { removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>';
files = []; removeBtn.onclick = () => {
updateUI(); files = [];
}; updateUI();
};
fileDiv.append(infoContainer, removeBtn); fileDiv.append(infoContainer, removeBtn);
fileDisplayArea.appendChild(fileDiv); fileDisplayArea.appendChild(fileDiv);
// Fetch page count asynchronously // Fetch page count asynchronously
readFileAsArrayBuffer(file).then(buffer => { readFileAsArrayBuffer(file)
return getPDFDocument(buffer).promise; .then((buffer) => {
}).then(pdf => { return getPDFDocument(buffer).promise;
metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`; })
}).catch(e => { .then((pdf) => {
console.warn('Error loading PDF page count:', e); metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`;
metaSpan.textContent = formatBytes(file.size); })
}); .catch((e) => {
console.warn('Error loading PDF page count:', e);
metaSpan.textContent = formatBytes(file.size);
}); });
});
// Initialize icons immediately after synchronous render // Initialize icons immediately after synchronous render
createIcons({ icons }); createIcons({ icons });
} else { } else {
optionsPanel.classList.add('hidden'); optionsPanel.classList.add('hidden');
} }
}; };
const resetState = () => { const resetState = () => {
files = []; files = [];
const fileInput = document.getElementById('file-input') as HTMLInputElement; const fileInput = document.getElementById('file-input') as HTMLInputElement;
if (fileInput) fileInput.value = ''; if (fileInput) fileInput.value = '';
const qualitySlider = document.getElementById('jpg-quality') as HTMLInputElement; const qualitySlider = document.getElementById(
const qualityValue = document.getElementById('jpg-quality-value'); 'jpg-quality'
if (qualitySlider) qualitySlider.value = '0.9'; ) as HTMLInputElement;
if (qualityValue) qualityValue.textContent = '90%'; const qualityValue = document.getElementById('jpg-quality-value');
updateUI(); if (qualitySlider) qualitySlider.value = '0.9';
if (qualityValue) qualityValue.textContent = '90%';
updateUI();
}; };
async function convert() { async function convert() {
if (files.length === 0) { if (files.length === 0) {
showAlert('No File', 'Please upload a PDF file first.'); showAlert('No File', 'Please upload a PDF file first.');
return; return;
} }
showLoader('Converting to JPG...'); showLoader('Converting to JPG...');
try { try {
const pdf = await getPDFDocument( const pdf = await getPDFDocument(await readFileAsArrayBuffer(files[0]))
await readFileAsArrayBuffer(files[0]) .promise;
).promise;
const zip = new JSZip();
const qualityInput = document.getElementById('jpg-quality') as HTMLInputElement; const qualityInput = document.getElementById(
const quality = qualityInput ? parseFloat(qualityInput.value) : 0.9; 'jpg-quality'
) as HTMLInputElement;
const quality = qualityInput ? parseFloat(qualityInput.value) : 0.9;
for (let i = 1; i <= pdf.numPages; i++) { if (pdf.numPages === 1) {
const page = await pdf.getPage(i); const page = await pdf.getPage(1);
const viewport = page.getViewport({ scale: 2.0 }); const blob = await renderPage(page, quality);
const canvas = document.createElement('canvas'); downloadFile(blob, getCleanPdfFilename(files[0].name) + '.jpg');
const context = canvas.getContext('2d'); } else {
canvas.height = viewport.height; const zip = new JSZip();
canvas.width = viewport.width; for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
await page.render({ canvasContext: context!, viewport: viewport, canvas }).promise; const blob = await renderPage(page, quality);
if (blob) {
const blob = await new Promise<Blob | null>((resolve) => zip.file(`page_${i}.jpg`, blob);
canvas.toBlob(resolve, 'image/jpeg', quality)
);
if (blob) {
zip.file(`page_${i}.jpg`, blob);
}
} }
}
const zipBlob = await zip.generateAsync({ type: 'blob' }); const zipBlob = await zip.generateAsync({ type: 'blob' });
downloadFile(zipBlob, 'converted_images.zip'); downloadFile(zipBlob, getCleanPdfFilename(files[0].name) + '_jpgs.zip');
showAlert('Success', 'PDF converted to JPGs successfully!', 'success', () => {
resetState();
});
} catch (e) {
console.error(e);
showAlert(
'Error',
'Failed to convert PDF to JPG. The file might be corrupted.'
);
} finally {
hideLoader();
} }
showAlert(
'Success',
'PDF converted to JPGs successfully!',
'success',
() => {
resetState();
}
);
} catch (e) {
console.error(e);
showAlert(
'Error',
'Failed to convert PDF to JPG. The file might be corrupted.'
);
} finally {
hideLoader();
}
}
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', () => { document.addEventListener('DOMContentLoaded', () => {
const fileInput = document.getElementById('file-input') as HTMLInputElement; const fileInput = document.getElementById('file-input') as HTMLInputElement;
const dropZone = document.getElementById('drop-zone'); const dropZone = document.getElementById('drop-zone');
const processBtn = document.getElementById('process-btn'); const processBtn = document.getElementById('process-btn');
const backBtn = document.getElementById('back-to-tools'); const backBtn = document.getElementById('back-to-tools');
const qualitySlider = document.getElementById('jpg-quality') as HTMLInputElement; const qualitySlider = document.getElementById(
const qualityValue = document.getElementById('jpg-quality-value'); 'jpg-quality'
) as HTMLInputElement;
const qualityValue = document.getElementById('jpg-quality-value');
if (backBtn) { if (backBtn) {
backBtn.addEventListener('click', () => { backBtn.addEventListener('click', () => {
window.location.href = import.meta.env.BASE_URL; window.location.href = import.meta.env.BASE_URL;
}); });
}
if (qualitySlider && qualityValue) {
qualitySlider.addEventListener('input', () => {
qualityValue.textContent = `${Math.round(parseFloat(qualitySlider.value) * 100)}%`;
});
}
const handleFileSelect = (newFiles: FileList | null) => {
if (!newFiles || newFiles.length === 0) return;
const validFiles = Array.from(newFiles).filter(
(file) => file.type === 'application/pdf'
);
if (validFiles.length === 0) {
showAlert('Invalid File', 'Please upload a PDF file.');
return;
} }
if (qualitySlider && qualityValue) { files = [validFiles[0]];
qualitySlider.addEventListener('input', () => { updateUI();
qualityValue.textContent = `${Math.round(parseFloat(qualitySlider.value) * 100)}%`; };
});
}
const handleFileSelect = (newFiles: FileList | null) => { if (fileInput && dropZone) {
if (!newFiles || newFiles.length === 0) return; fileInput.addEventListener('change', (e) => {
const validFiles = Array.from(newFiles).filter( handleFileSelect((e.target as HTMLInputElement).files);
(file) => file.type === 'application/pdf' });
);
if (validFiles.length === 0) { dropZone.addEventListener('dragover', (e) => {
showAlert('Invalid File', 'Please upload a PDF file.'); e.preventDefault();
return; dropZone.classList.add('bg-gray-700');
} });
files = [validFiles[0]]; dropZone.addEventListener('dragleave', (e) => {
updateUI(); e.preventDefault();
}; dropZone.classList.remove('bg-gray-700');
});
if (fileInput && dropZone) { dropZone.addEventListener('drop', (e) => {
fileInput.addEventListener('change', (e) => { e.preventDefault();
handleFileSelect((e.target as HTMLInputElement).files); dropZone.classList.remove('bg-gray-700');
}); handleFileSelect(e.dataTransfer?.files ?? null);
});
dropZone.addEventListener('dragover', (e) => { fileInput.addEventListener('click', () => {
e.preventDefault(); fileInput.value = '';
dropZone.classList.add('bg-gray-700'); });
}); }
dropZone.addEventListener('dragleave', (e) => { if (processBtn) {
e.preventDefault(); processBtn.addEventListener('click', convert);
dropZone.classList.remove('bg-gray-700'); }
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('bg-gray-700');
handleFileSelect(e.dataTransfer?.files ?? null);
});
fileInput.addEventListener('click', () => {
fileInput.value = '';
});
}
if (processBtn) {
processBtn.addEventListener('click', convert);
}
}); });

View File

@@ -1,193 +1,231 @@
import { showLoader, hideLoader, showAlert } from '../ui.js'; 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 { createIcons, icons } from 'lucide';
import JSZip from 'jszip'; import JSZip from 'jszip';
import * as pdfjsLib from 'pdfjs-dist'; 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[] = []; let files: File[] = [];
const updateUI = () => { const updateUI = () => {
const fileDisplayArea = document.getElementById('file-display-area'); const fileDisplayArea = document.getElementById('file-display-area');
const optionsPanel = document.getElementById('options-panel'); const optionsPanel = document.getElementById('options-panel');
const dropZone = document.getElementById('drop-zone'); const dropZone = document.getElementById('drop-zone');
if (!fileDisplayArea || !optionsPanel || !dropZone) return; if (!fileDisplayArea || !optionsPanel || !dropZone) return;
fileDisplayArea.innerHTML = ''; fileDisplayArea.innerHTML = '';
if (files.length > 0) { if (files.length > 0) {
optionsPanel.classList.remove('hidden'); optionsPanel.classList.remove('hidden');
files.forEach((file) => { files.forEach((file) => {
const fileDiv = document.createElement('div'); 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'); const infoContainer = document.createElement('div');
infoContainer.className = 'flex flex-col overflow-hidden'; infoContainer.className = 'flex flex-col overflow-hidden';
const nameSpan = document.createElement('div'); const nameSpan = document.createElement('div');
nameSpan.className = 'truncate font-medium text-gray-200 text-sm mb-1'; nameSpan.className = 'truncate font-medium text-gray-200 text-sm mb-1';
nameSpan.textContent = file.name; nameSpan.textContent = file.name;
const metaSpan = document.createElement('div'); const metaSpan = document.createElement('div');
metaSpan.className = 'text-xs text-gray-400'; metaSpan.className = 'text-xs text-gray-400';
metaSpan.textContent = `${formatBytes(file.size)} • Loading pages...`; // Initial state metaSpan.textContent = `${formatBytes(file.size)} • Loading pages...`; // Initial state
infoContainer.append(nameSpan, metaSpan); infoContainer.append(nameSpan, metaSpan);
const removeBtn = document.createElement('button'); const removeBtn = document.createElement('button');
removeBtn.className = 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0'; removeBtn.className =
removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>'; 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.onclick = () => { removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>';
files = []; removeBtn.onclick = () => {
updateUI(); files = [];
}; updateUI();
};
fileDiv.append(infoContainer, removeBtn); fileDiv.append(infoContainer, removeBtn);
fileDisplayArea.appendChild(fileDiv); fileDisplayArea.appendChild(fileDiv);
// Fetch page count asynchronously // Fetch page count asynchronously
readFileAsArrayBuffer(file).then(buffer => { readFileAsArrayBuffer(file)
return getPDFDocument(buffer).promise; .then((buffer) => {
}).then(pdf => { return getPDFDocument(buffer).promise;
metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`; })
}).catch(e => { .then((pdf) => {
console.warn('Error loading PDF page count:', e); metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`;
metaSpan.textContent = formatBytes(file.size); })
}); .catch((e) => {
console.warn('Error loading PDF page count:', e);
metaSpan.textContent = formatBytes(file.size);
}); });
});
// Initialize icons immediately after synchronous render // Initialize icons immediately after synchronous render
createIcons({ icons }); createIcons({ icons });
} else { } else {
optionsPanel.classList.add('hidden'); optionsPanel.classList.add('hidden');
} }
}; };
const resetState = () => { const resetState = () => {
files = []; files = [];
const fileInput = document.getElementById('file-input') as HTMLInputElement; const fileInput = document.getElementById('file-input') as HTMLInputElement;
if (fileInput) fileInput.value = ''; if (fileInput) fileInput.value = '';
const scaleSlider = document.getElementById('png-scale') as HTMLInputElement; const scaleSlider = document.getElementById('png-scale') as HTMLInputElement;
const scaleValue = document.getElementById('png-scale-value'); const scaleValue = document.getElementById('png-scale-value');
if (scaleSlider) scaleSlider.value = '2.0'; if (scaleSlider) scaleSlider.value = '2.0';
if (scaleValue) scaleValue.textContent = '2.0x'; if (scaleValue) scaleValue.textContent = '2.0x';
updateUI(); updateUI();
}; };
async function convert() { async function convert() {
if (files.length === 0) { if (files.length === 0) {
showAlert('No File', 'Please upload a PDF file first.'); showAlert('No File', 'Please upload a PDF file first.');
return; return;
} }
showLoader('Converting to PNG...'); showLoader('Converting to PNG...');
try { try {
const pdf = await getPDFDocument( const pdf = await getPDFDocument(await readFileAsArrayBuffer(files[0]))
await readFileAsArrayBuffer(files[0]) .promise;
).promise;
const zip = new JSZip();
const scaleInput = document.getElementById('png-scale') as HTMLInputElement; const scaleInput = document.getElementById('png-scale') as HTMLInputElement;
const scale = scaleInput ? parseFloat(scaleInput.value) : 2.0; const scale = scaleInput ? parseFloat(scaleInput.value) : 2.0;
for (let i = 1; i <= pdf.numPages; i++) { if (pdf.numPages === 1) {
const page = await pdf.getPage(i); const page = await pdf.getPage(1);
const viewport = page.getViewport({ scale }); const blob = await renderPage(page, scale);
const canvas = document.createElement('canvas'); downloadFile(blob, getCleanPdfFilename(files[0].name) + '.png');
const context = canvas.getContext('2d'); } else {
canvas.height = viewport.height; const zip = new JSZip();
canvas.width = viewport.width; for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
await page.render({ canvasContext: context!, viewport: viewport, canvas }).promise; const blob = await renderPage(page, scale);
if (blob) {
const blob = await new Promise<Blob | null>((resolve) => zip.file(`page_${i}.png`, blob);
canvas.toBlob(resolve, 'image/png')
);
if (blob) {
zip.file(`page_${i}.png`, blob);
}
} }
}
const zipBlob = await zip.generateAsync({ type: 'blob' }); const zipBlob = await zip.generateAsync({ type: 'blob' });
downloadFile(zipBlob, 'converted_images.zip'); downloadFile(zipBlob, getCleanPdfFilename(files[0].name) + '_pngs.zip');
showAlert('Success', 'PDF converted to PNGs successfully!', 'success', () => {
resetState();
});
} catch (e) {
console.error(e);
showAlert(
'Error',
'Failed to convert PDF to PNG. The file might be corrupted.'
);
} finally {
hideLoader();
} }
showAlert(
'Success',
'PDF converted to PNGs successfully!',
'success',
() => {
resetState();
}
);
} catch (e) {
console.error(e);
showAlert(
'Error',
'Failed to convert PDF to PNG. The file might be corrupted.'
);
} finally {
hideLoader();
}
}
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', () => { document.addEventListener('DOMContentLoaded', () => {
const fileInput = document.getElementById('file-input') as HTMLInputElement; const fileInput = document.getElementById('file-input') as HTMLInputElement;
const dropZone = document.getElementById('drop-zone'); const dropZone = document.getElementById('drop-zone');
const processBtn = document.getElementById('process-btn'); const processBtn = document.getElementById('process-btn');
const backBtn = document.getElementById('back-to-tools'); const backBtn = document.getElementById('back-to-tools');
const scaleSlider = document.getElementById('png-scale') as HTMLInputElement; const scaleSlider = document.getElementById('png-scale') as HTMLInputElement;
const scaleValue = document.getElementById('png-scale-value'); const scaleValue = document.getElementById('png-scale-value');
if (backBtn) { if (backBtn) {
backBtn.addEventListener('click', () => { backBtn.addEventListener('click', () => {
window.location.href = import.meta.env.BASE_URL; window.location.href = import.meta.env.BASE_URL;
}); });
}
if (scaleSlider && scaleValue) {
scaleSlider.addEventListener('input', () => {
scaleValue.textContent = `${parseFloat(scaleSlider.value).toFixed(1)}x`;
});
}
const handleFileSelect = (newFiles: FileList | null) => {
if (!newFiles || newFiles.length === 0) return;
const validFiles = Array.from(newFiles).filter(
(file) => file.type === 'application/pdf'
);
if (validFiles.length === 0) {
showAlert('Invalid File', 'Please upload a PDF file.');
return;
} }
if (scaleSlider && scaleValue) { files = [validFiles[0]];
scaleSlider.addEventListener('input', () => { updateUI();
scaleValue.textContent = `${parseFloat(scaleSlider.value).toFixed(1)}x`; };
});
}
const handleFileSelect = (newFiles: FileList | null) => { if (fileInput && dropZone) {
if (!newFiles || newFiles.length === 0) return; fileInput.addEventListener('change', (e) => {
const validFiles = Array.from(newFiles).filter( handleFileSelect((e.target as HTMLInputElement).files);
(file) => file.type === 'application/pdf' });
);
if (validFiles.length === 0) { dropZone.addEventListener('dragover', (e) => {
showAlert('Invalid File', 'Please upload a PDF file.'); e.preventDefault();
return; dropZone.classList.add('bg-gray-700');
} });
files = [validFiles[0]]; dropZone.addEventListener('dragleave', (e) => {
updateUI(); e.preventDefault();
}; dropZone.classList.remove('bg-gray-700');
});
if (fileInput && dropZone) { dropZone.addEventListener('drop', (e) => {
fileInput.addEventListener('change', (e) => { e.preventDefault();
handleFileSelect((e.target as HTMLInputElement).files); dropZone.classList.remove('bg-gray-700');
}); handleFileSelect(e.dataTransfer?.files ?? null);
});
dropZone.addEventListener('dragover', (e) => { fileInput.addEventListener('click', () => {
e.preventDefault(); fileInput.value = '';
dropZone.classList.add('bg-gray-700'); });
}); }
dropZone.addEventListener('dragleave', (e) => { if (processBtn) {
e.preventDefault(); processBtn.addEventListener('click', convert);
dropZone.classList.remove('bg-gray-700'); }
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('bg-gray-700');
handleFileSelect(e.dataTransfer?.files ?? null);
});
fileInput.addEventListener('click', () => {
fileInput.value = '';
});
}
if (processBtn) {
processBtn.addEventListener('click', convert);
}
}); });

View File

@@ -1,190 +1,251 @@
import { showLoader, hideLoader, showAlert } from '../ui.js'; 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 { createIcons, icons } from 'lucide';
import JSZip from 'jszip'; import JSZip from 'jszip';
import * as pdfjsLib from 'pdfjs-dist'; import * as pdfjsLib from 'pdfjs-dist';
import UTIF from 'utif'; 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[] = []; let files: File[] = [];
const updateUI = () => { const updateUI = () => {
const fileDisplayArea = document.getElementById('file-display-area'); const fileDisplayArea = document.getElementById('file-display-area');
const optionsPanel = document.getElementById('options-panel'); const optionsPanel = document.getElementById('options-panel');
const dropZone = document.getElementById('drop-zone'); const dropZone = document.getElementById('drop-zone');
if (!fileDisplayArea || !optionsPanel || !dropZone) return; if (!fileDisplayArea || !optionsPanel || !dropZone) return;
fileDisplayArea.innerHTML = ''; fileDisplayArea.innerHTML = '';
if (files.length > 0) { if (files.length > 0) {
optionsPanel.classList.remove('hidden'); optionsPanel.classList.remove('hidden');
files.forEach((file) => { files.forEach((file) => {
const fileDiv = document.createElement('div'); 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'); const infoContainer = document.createElement('div');
infoContainer.className = 'flex flex-col overflow-hidden'; infoContainer.className = 'flex flex-col overflow-hidden';
const nameSpan = document.createElement('div'); const nameSpan = document.createElement('div');
nameSpan.className = 'truncate font-medium text-gray-200 text-sm mb-1'; nameSpan.className = 'truncate font-medium text-gray-200 text-sm mb-1';
nameSpan.textContent = file.name; nameSpan.textContent = file.name;
const metaSpan = document.createElement('div'); const metaSpan = document.createElement('div');
metaSpan.className = 'text-xs text-gray-400'; metaSpan.className = 'text-xs text-gray-400';
metaSpan.textContent = `${formatBytes(file.size)} • Loading pages...`; // Initial state metaSpan.textContent = `${formatBytes(file.size)} • Loading pages...`; // Initial state
infoContainer.append(nameSpan, metaSpan); infoContainer.append(nameSpan, metaSpan);
const removeBtn = document.createElement('button'); const removeBtn = document.createElement('button');
removeBtn.className = 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0'; removeBtn.className =
removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>'; 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.onclick = () => { removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>';
files = []; removeBtn.onclick = () => {
updateUI(); files = [];
}; updateUI();
};
fileDiv.append(infoContainer, removeBtn); fileDiv.append(infoContainer, removeBtn);
fileDisplayArea.appendChild(fileDiv); fileDisplayArea.appendChild(fileDiv);
// Fetch page count asynchronously // Fetch page count asynchronously
readFileAsArrayBuffer(file).then(buffer => { readFileAsArrayBuffer(file)
return getPDFDocument(buffer).promise; .then((buffer) => {
}).then(pdf => { return getPDFDocument(buffer).promise;
metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`; })
}).catch(e => { .then((pdf) => {
console.warn('Error loading PDF page count:', e); metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`;
metaSpan.textContent = formatBytes(file.size); })
}); .catch((e) => {
console.warn('Error loading PDF page count:', e);
metaSpan.textContent = formatBytes(file.size);
}); });
});
// Initialize icons immediately after synchronous render // Initialize icons immediately after synchronous render
createIcons({ icons }); createIcons({ icons });
} else { } else {
optionsPanel.classList.add('hidden'); optionsPanel.classList.add('hidden');
} }
}; };
const resetState = () => { const resetState = () => {
files = []; files = [];
const fileInput = document.getElementById('file-input') as HTMLInputElement; const fileInput = document.getElementById('file-input') as HTMLInputElement;
if (fileInput) fileInput.value = ''; if (fileInput) fileInput.value = '';
updateUI(); updateUI();
}; };
async function convert() { async function convert() {
if (files.length === 0) { if (files.length === 0) {
showAlert('No File', 'Please upload a PDF file first.'); showAlert('No File', 'Please upload a PDF file first.');
return; return;
} }
showLoader('Converting to TIFF...'); showLoader('Converting to TIFF...');
try { try {
const pdf = await getPDFDocument( const pdf = await getPDFDocument(await readFileAsArrayBuffer(files[0]))
await readFileAsArrayBuffer(files[0]) .promise;
).promise;
const zip = new JSZip();
for (let i = 1; i <= pdf.numPages; i++) { if (pdf.numPages === 1) {
const page = await pdf.getPage(i); const page = await pdf.getPage(1);
const viewport = page.getViewport({ scale: 2.0 }); const blob = await renderPage(page, 1);
const canvas = document.createElement('canvas'); downloadFile(
const context = canvas.getContext('2d'); blob.blobData,
canvas.height = viewport.height; getCleanPdfFilename(files[0].name) + '.' + blob.ending
canvas.width = viewport.width; );
} else {
await page.render({ canvasContext: context!, viewport: viewport, canvas }).promise; const zip = new JSZip();
for (let i = 1; i <= pdf.numPages; i++) {
const imageData = context!.getImageData(0, 0, canvas.width, canvas.height); const page = await pdf.getPage(i);
const rgba = imageData.data; const blob = await renderPage(page, i);
if (blob.blobData) {
try { zip.file(`page_${i}.` + blob.ending, blob.blobData);
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 zipBlob = await zip.generateAsync({ type: 'blob' }); const zipBlob = await zip.generateAsync({ type: 'blob' });
downloadFile(zipBlob, 'converted_images.zip'); downloadFile(zipBlob, getCleanPdfFilename(files[0].name) + '_tiffs.zip');
showAlert('Success', 'PDF converted to TIFFs successfully!', 'success', () => {
resetState();
});
} catch (e) {
console.error(e);
showAlert(
'Error',
'Failed to convert PDF to TIFF. The file might be corrupted.'
);
} finally {
hideLoader();
} }
showAlert(
'Success',
'PDF converted to TIFFs successfully!',
'success',
() => {
resetState();
}
);
} catch (e) {
console.error(e);
showAlert(
'Error',
'Failed to convert PDF to TIFF. The file might be corrupted.'
);
} finally {
hideLoader();
}
}
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', () => { document.addEventListener('DOMContentLoaded', () => {
const fileInput = document.getElementById('file-input') as HTMLInputElement; const fileInput = document.getElementById('file-input') as HTMLInputElement;
const dropZone = document.getElementById('drop-zone'); const dropZone = document.getElementById('drop-zone');
const processBtn = document.getElementById('process-btn'); const processBtn = document.getElementById('process-btn');
const backBtn = document.getElementById('back-to-tools'); const backBtn = document.getElementById('back-to-tools');
if (backBtn) { if (backBtn) {
backBtn.addEventListener('click', () => { backBtn.addEventListener('click', () => {
window.location.href = import.meta.env.BASE_URL; window.location.href = import.meta.env.BASE_URL;
}); });
}
const handleFileSelect = (newFiles: FileList | null) => {
if (!newFiles || newFiles.length === 0) return;
const validFiles = Array.from(newFiles).filter(
(file) => file.type === 'application/pdf'
);
if (validFiles.length === 0) {
showAlert('Invalid File', 'Please upload a PDF file.');
return;
} }
const handleFileSelect = (newFiles: FileList | null) => { files = [validFiles[0]];
if (!newFiles || newFiles.length === 0) return; updateUI();
const validFiles = Array.from(newFiles).filter( };
(file) => file.type === 'application/pdf'
);
if (validFiles.length === 0) { if (fileInput && dropZone) {
showAlert('Invalid File', 'Please upload a PDF file.'); fileInput.addEventListener('change', (e) => {
return; handleFileSelect((e.target as HTMLInputElement).files);
} });
files = [validFiles[0]]; dropZone.addEventListener('dragover', (e) => {
updateUI(); e.preventDefault();
}; dropZone.classList.add('bg-gray-700');
});
if (fileInput && dropZone) { dropZone.addEventListener('dragleave', (e) => {
fileInput.addEventListener('change', (e) => { e.preventDefault();
handleFileSelect((e.target as HTMLInputElement).files); dropZone.classList.remove('bg-gray-700');
}); });
dropZone.addEventListener('dragover', (e) => { dropZone.addEventListener('drop', (e) => {
e.preventDefault(); e.preventDefault();
dropZone.classList.add('bg-gray-700'); dropZone.classList.remove('bg-gray-700');
}); handleFileSelect(e.dataTransfer?.files ?? null);
});
dropZone.addEventListener('dragleave', (e) => { fileInput.addEventListener('click', () => {
e.preventDefault(); fileInput.value = '';
dropZone.classList.remove('bg-gray-700'); });
}); }
dropZone.addEventListener('drop', (e) => { if (processBtn) {
e.preventDefault(); processBtn.addEventListener('click', convert);
dropZone.classList.remove('bg-gray-700'); }
handleFileSelect(e.dataTransfer?.files ?? null);
});
fileInput.addEventListener('click', () => {
fileInput.value = '';
});
}
if (processBtn) {
processBtn.addEventListener('click', convert);
}
}); });

View File

@@ -1,193 +1,237 @@
import { showLoader, hideLoader, showAlert } from '../ui.js'; 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 { createIcons, icons } from 'lucide';
import JSZip from 'jszip'; import JSZip from 'jszip';
import * as pdfjsLib from 'pdfjs-dist'; 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[] = []; let files: File[] = [];
const updateUI = () => { const updateUI = () => {
const fileDisplayArea = document.getElementById('file-display-area'); const fileDisplayArea = document.getElementById('file-display-area');
const optionsPanel = document.getElementById('options-panel'); const optionsPanel = document.getElementById('options-panel');
const dropZone = document.getElementById('drop-zone'); const dropZone = document.getElementById('drop-zone');
if (!fileDisplayArea || !optionsPanel || !dropZone) return; if (!fileDisplayArea || !optionsPanel || !dropZone) return;
fileDisplayArea.innerHTML = ''; fileDisplayArea.innerHTML = '';
if (files.length > 0) { if (files.length > 0) {
optionsPanel.classList.remove('hidden'); optionsPanel.classList.remove('hidden');
files.forEach((file) => { files.forEach((file) => {
const fileDiv = document.createElement('div'); 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'); const infoContainer = document.createElement('div');
infoContainer.className = 'flex flex-col overflow-hidden'; infoContainer.className = 'flex flex-col overflow-hidden';
const nameSpan = document.createElement('div'); const nameSpan = document.createElement('div');
nameSpan.className = 'truncate font-medium text-gray-200 text-sm mb-1'; nameSpan.className = 'truncate font-medium text-gray-200 text-sm mb-1';
nameSpan.textContent = file.name; nameSpan.textContent = file.name;
const metaSpan = document.createElement('div'); const metaSpan = document.createElement('div');
metaSpan.className = 'text-xs text-gray-400'; metaSpan.className = 'text-xs text-gray-400';
metaSpan.textContent = `${formatBytes(file.size)} • Loading pages...`; // Initial state metaSpan.textContent = `${formatBytes(file.size)} • Loading pages...`; // Initial state
infoContainer.append(nameSpan, metaSpan); infoContainer.append(nameSpan, metaSpan);
const removeBtn = document.createElement('button'); const removeBtn = document.createElement('button');
removeBtn.className = 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0'; removeBtn.className =
removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>'; 'ml-4 text-red-400 hover:text-red-300 flex-shrink-0';
removeBtn.onclick = () => { removeBtn.innerHTML = '<i data-lucide="trash-2" class="w-4 h-4"></i>';
files = []; removeBtn.onclick = () => {
updateUI(); files = [];
}; updateUI();
};
fileDiv.append(infoContainer, removeBtn); fileDiv.append(infoContainer, removeBtn);
fileDisplayArea.appendChild(fileDiv); fileDisplayArea.appendChild(fileDiv);
// Fetch page count asynchronously // Fetch page count asynchronously
readFileAsArrayBuffer(file).then(buffer => { readFileAsArrayBuffer(file)
return getPDFDocument(buffer).promise; .then((buffer) => {
}).then(pdf => { return getPDFDocument(buffer).promise;
metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`; })
}).catch(e => { .then((pdf) => {
console.warn('Error loading PDF page count:', e); metaSpan.textContent = `${formatBytes(file.size)}${pdf.numPages} page${pdf.numPages !== 1 ? 's' : ''}`;
metaSpan.textContent = formatBytes(file.size); })
}); .catch((e) => {
console.warn('Error loading PDF page count:', e);
metaSpan.textContent = formatBytes(file.size);
}); });
});
// Initialize icons immediately after synchronous render // Initialize icons immediately after synchronous render
createIcons({ icons }); createIcons({ icons });
} else { } else {
optionsPanel.classList.add('hidden'); optionsPanel.classList.add('hidden');
} }
}; };
const resetState = () => { const resetState = () => {
files = []; files = [];
const fileInput = document.getElementById('file-input') as HTMLInputElement; const fileInput = document.getElementById('file-input') as HTMLInputElement;
if (fileInput) fileInput.value = ''; if (fileInput) fileInput.value = '';
const qualitySlider = document.getElementById('webp-quality') as HTMLInputElement; const qualitySlider = document.getElementById(
const qualityValue = document.getElementById('webp-quality-value'); 'webp-quality'
if (qualitySlider) qualitySlider.value = '0.85'; ) as HTMLInputElement;
if (qualityValue) qualityValue.textContent = '85%'; const qualityValue = document.getElementById('webp-quality-value');
updateUI(); if (qualitySlider) qualitySlider.value = '0.85';
if (qualityValue) qualityValue.textContent = '85%';
updateUI();
}; };
async function convert() { async function convert() {
if (files.length === 0) { if (files.length === 0) {
showAlert('No File', 'Please upload a PDF file first.'); showAlert('No File', 'Please upload a PDF file first.');
return; return;
} }
showLoader('Converting to WebP...'); showLoader('Converting to WebP...');
try { try {
const pdf = await getPDFDocument( const pdf = await getPDFDocument(await readFileAsArrayBuffer(files[0]))
await readFileAsArrayBuffer(files[0]) .promise;
).promise;
const zip = new JSZip();
const qualityInput = document.getElementById('webp-quality') as HTMLInputElement; const qualityInput = document.getElementById(
const quality = qualityInput ? parseFloat(qualityInput.value) : 0.85; 'webp-quality'
) as HTMLInputElement;
const quality = qualityInput ? parseFloat(qualityInput.value) : 0.85;
for (let i = 1; i <= pdf.numPages; i++) { if (pdf.numPages === 1) {
const page = await pdf.getPage(i); const page = await pdf.getPage(1);
const viewport = page.getViewport({ scale: 2.0 }); const blob = await renderPage(page, quality);
const canvas = document.createElement('canvas'); downloadFile(blob, getCleanPdfFilename(files[0].name) + '.webp');
const context = canvas.getContext('2d'); } else {
canvas.height = viewport.height; const zip = new JSZip();
canvas.width = viewport.width; for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
await page.render({ canvasContext: context!, viewport: viewport, canvas }).promise; const blob = await renderPage(page, quality);
if (blob) {
const blob = await new Promise<Blob | null>((resolve) => zip.file(`page_${i}.webp`, blob);
canvas.toBlob(resolve, 'image/webp', quality)
);
if (blob) {
zip.file(`page_${i}.webp`, blob);
}
} }
}
const zipBlob = await zip.generateAsync({ type: 'blob' }); const zipBlob = await zip.generateAsync({ type: 'blob' });
downloadFile(zipBlob, 'converted_images.zip'); downloadFile(zipBlob, getCleanPdfFilename(files[0].name) + '_webps.zip');
showAlert('Success', 'PDF converted to WebPs successfully!', 'success', () => {
resetState();
});
} catch (e) {
console.error(e);
showAlert(
'Error',
'Failed to convert PDF to WebP. The file might be corrupted.'
);
} finally {
hideLoader();
} }
showAlert(
'Success',
'PDF converted to WebPs successfully!',
'success',
() => {
resetState();
}
);
} catch (e) {
console.error(e);
showAlert(
'Error',
'Failed to convert PDF to WebP. The file might be corrupted.'
);
} finally {
hideLoader();
}
}
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', () => { document.addEventListener('DOMContentLoaded', () => {
const fileInput = document.getElementById('file-input') as HTMLInputElement; const fileInput = document.getElementById('file-input') as HTMLInputElement;
const dropZone = document.getElementById('drop-zone'); const dropZone = document.getElementById('drop-zone');
const processBtn = document.getElementById('process-btn'); const processBtn = document.getElementById('process-btn');
const backBtn = document.getElementById('back-to-tools'); const backBtn = document.getElementById('back-to-tools');
const qualitySlider = document.getElementById('webp-quality') as HTMLInputElement; const qualitySlider = document.getElementById(
const qualityValue = document.getElementById('webp-quality-value'); 'webp-quality'
) as HTMLInputElement;
const qualityValue = document.getElementById('webp-quality-value');
if (backBtn) { if (backBtn) {
backBtn.addEventListener('click', () => { backBtn.addEventListener('click', () => {
window.location.href = import.meta.env.BASE_URL; window.location.href = import.meta.env.BASE_URL;
}); });
}
if (qualitySlider && qualityValue) {
qualitySlider.addEventListener('input', () => {
qualityValue.textContent = `${Math.round(parseFloat(qualitySlider.value) * 100)}%`;
});
}
const handleFileSelect = (newFiles: FileList | null) => {
if (!newFiles || newFiles.length === 0) return;
const validFiles = Array.from(newFiles).filter(
(file) => file.type === 'application/pdf'
);
if (validFiles.length === 0) {
showAlert('Invalid File', 'Please upload a PDF file.');
return;
} }
if (qualitySlider && qualityValue) { files = [validFiles[0]];
qualitySlider.addEventListener('input', () => { updateUI();
qualityValue.textContent = `${Math.round(parseFloat(qualitySlider.value) * 100)}%`; };
});
}
const handleFileSelect = (newFiles: FileList | null) => { if (fileInput && dropZone) {
if (!newFiles || newFiles.length === 0) return; fileInput.addEventListener('change', (e) => {
const validFiles = Array.from(newFiles).filter( handleFileSelect((e.target as HTMLInputElement).files);
(file) => file.type === 'application/pdf' });
);
if (validFiles.length === 0) { dropZone.addEventListener('dragover', (e) => {
showAlert('Invalid File', 'Please upload a PDF file.'); e.preventDefault();
return; dropZone.classList.add('bg-gray-700');
} });
files = [validFiles[0]]; dropZone.addEventListener('dragleave', (e) => {
updateUI(); e.preventDefault();
}; dropZone.classList.remove('bg-gray-700');
});
if (fileInput && dropZone) { dropZone.addEventListener('drop', (e) => {
fileInput.addEventListener('change', (e) => { e.preventDefault();
handleFileSelect((e.target as HTMLInputElement).files); dropZone.classList.remove('bg-gray-700');
}); handleFileSelect(e.dataTransfer?.files ?? null);
});
dropZone.addEventListener('dragover', (e) => { fileInput.addEventListener('click', () => {
e.preventDefault(); fileInput.value = '';
dropZone.classList.add('bg-gray-700'); });
}); }
dropZone.addEventListener('dragleave', (e) => { if (processBtn) {
e.preventDefault(); processBtn.addEventListener('click', convert);
dropZone.classList.remove('bg-gray-700'); }
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('bg-gray-700');
handleFileSelect(e.dataTransfer?.files ?? null);
});
fileInput.addEventListener('click', () => {
fileInput.value = '';
});
}
if (processBtn) {
processBtn.addEventListener('click', convert);
}
}); });

View File

@@ -29,7 +29,7 @@ export function getStandardPageName(width: any, height: any) {
} }
export function convertPoints(points: any, unit: any) { export function convertPoints(points: any, unit: any) {
let result = 0; let result: number;
switch (unit) { switch (unit) {
case 'in': case 'in':
result = points / 72; result = points / 72;
@@ -460,3 +460,22 @@ export function formatRawDate(raw: string): string {
} }
return raw; 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"> <div id="options-panel" class="hidden mt-6">
<button id="process-btn" class="btn-gradient w-full"> <button id="process-btn" class="btn-gradient w-full">
Download All as ZIP Download All
</button> </button>
</div> </div>
</div> </div>

View File

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

View File

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

View File

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

View File

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