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