Add direct image download to pdf-to-bmp

This commit is contained in:
Sebastian Espei
2026-03-09 16:53:59 +01:00
parent 7c09768109
commit 92d5e40ac3
2 changed files with 170 additions and 135 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

@@ -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>