feat(pdf-to-webp): direct download resulting image and adjust filename

This commit is contained in:
Sebastian Espei
2025-12-01 00:56:14 +01:00
parent 30b16a6bf1
commit 33ebcf4479
2 changed files with 39 additions and 19 deletions

View File

@@ -3,6 +3,7 @@ import { downloadFile, readFileAsArrayBuffer, getPDFDocument } from '../utils/he
import { state } from '../state.js';
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();
@@ -13,9 +14,30 @@ export async function pdfToWebp() {
const pdf = await getPDFDocument(
await readFileAsArrayBuffer(state.files[0])
).promise;
if(pdf.numPages === 1) {
const page = await pdf.getPage(1);
const blob = await pageToBlob(page);
downloadFile(blob, getCleanFilename(state.files[0].name) + '.webp');
} else {
const zip = new JSZip();
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const blob = await pageToBlob(page);
zip.file(`page_${i}.webp`, blob as Blob);
}
const zipBlob = await zip.generateAsync({ type: 'blob' });
downloadFile(zipBlob, getCleanFilename(state.files[0].name) + '_webps.zip');
}
} catch (e) {
console.error(e);
showAlert('Error', 'Failed to convert PDF to WebP.');
} finally {
hideLoader();
}
}
async function pageToBlob(page: PDFPageProxy): Promise<Blob> {
const viewport = page.getViewport({ scale: 2.0 });
const canvas = document.createElement('canvas');
canvas.height = viewport.height;
@@ -28,14 +50,13 @@ export async function pdfToWebp() {
const blob = await new Promise((resolve) =>
canvas.toBlob(resolve, 'image/webp', quality)
);
zip.file(`page_${i}.webp`, blob as Blob);
}
const zipBlob = await zip.generateAsync({ type: 'blob' });
downloadFile(zipBlob, 'converted_webp.zip');
} catch (e) {
console.error(e);
showAlert('Error', 'Failed to convert PDF to WebP.');
} finally {
hideLoader();
}
return blob as Blob;
}
function getCleanFilename(fileName: string): string {
let clean = fileName.replace(/\.pdf$/i, '').trim();
if (clean.length > 80) {
clean = clean.slice(0, 80);
}
return clean;
}

View File

@@ -868,8 +868,7 @@ export const toolTemplates = {
</div>
<p class="mt-1 text-xs text-gray-400">Higher quality = larger file size</p>
</div>
<p class="mb-4 text-white text-center">Your file is ready. Click the button to download a ZIP file containing all WebP images.</p>
<button id="process-btn" class="btn-gradient w-full">Download All as ZIP</button>
<button id="process-btn" class="btn-gradient w-full">Convert to WEBP & Download All</button>
</div>
`,
'webp-to-pdf': () => `