Add direct image download to pdf-to-jpg
This commit is contained in:
@@ -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);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
Reference in New Issue
Block a user