PDF↔Image Conversion, Local and Cancellable: Inside a Pure-Frontend Tool
Pure-Frontend Implementation of a PDF and Image Interconversion Tool
Keywords: PDF to image, image to PDF, pdf.js, pdf-lib, JSZip, Canvas, local processing, pure frontend, JavaScript, mid-task cancellation, cancellable
1. Background and Requirements
In daily work, converting between PDF and images is a frequent need: extracting a page from a PDF as an image to send to a colleague, or merging several ID photos and invoices into one PDF for review.
Existing online conversion tools commonly have these problems:
- Files must be uploaded to third-party servers, raising the risk of leaking sensitive documents like contracts, invoices, and IDs.
- Most tools add watermarks, limit the number of conversions, or require registration/login or installing a desktop client.
- PDF-to-image lacks clarity and format options; image-to-PDF lacks order adjustment and page size control.
Based on this, I built the Toolion PDF-to-Image / Image-to-PDF tool (project address: https://toolion.cn/pdf-img-convert/), a pure-frontend bidirectional conversion application. All processing happens locally in the browser; no upload is needed.
2. Core Features
| Feature | Description |
|---|---|
| PDF to Image | Renders each PDF page as an independent image, supporting PNG/JPEG formats and three clarity levels: standard, high, ultra. |
| ZIP package download | Packs all converted page images into a ZIP file for easy management and download. |
| Image to PDF | Merges multiple JPG/PNG/WebP images into one PDF file. |
| Drag to reorder | In image-to-PDF mode, drag images to adjust their position in the list; pages are generated according to the final order. |
| Page size options | Supports "auto-fit image size" or "uniform A4 size (centered with white space)". |
| Proportional scaling and centering | Automatically scales and centers images of different sizes to avoid distortion. |
| Pure-frontend local processing | All processing is done in browser memory; files are not uploaded to servers; offline operation is supported. |
| No login, free, no watermark | Open the page and use it; no registration, no watermark, no limit on number of conversions. |
| Cancel mid-task | Click "Cancel Conversion" at any time during conversion; occupied memory is automatically released to avoid prolonged resource use. |
| Dark/light theme | CSS variables adapt to dark mode. |
3. Technical Implementation
3.1 Overall Architecture
The tool is a pure-frontend single-page application. It does not use frameworks like Vue/React; all logic is implemented with native JavaScript:
Browser (pure native JavaScript)
├── Input layer: PDF file / image file selection, conversion mode, format, clarity, page size
├── PDF→Image layer: pdf.js renders pages to Canvas → image Blob → JSZip packages ZIP
├── Image→PDF layer: pdf-lib creates PDF → embeds images (WebP converted to JPEG via Canvas) → saves output
└── Rendering layer: file list, drag reorder, progress bar, result panel, download button
3.2 Dependencies
The page loads four key libraries via CDN:
<script src="https://unpkg.com/[email protected]/dist/pdf-lib.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
- pdf.js 3.11.174: parses PDF files, retrieves each page view, and renders to Canvas.
- pdf-lib 1.17.1: creates new PDF documents, embeds images, adds pages, and saves output.
- JSZip 3.10.1: packages multiple images generated from PDF conversion into a ZIP file for download.
- FileSaver.js 2.0.5: saves generated Blobs as files; degrades to native
a.downloadin non-HTTPS environments.
Before use, the tool checks whether required dependencies loaded successfully and sets pdf.js's Worker resource path:
const DEPS = {
pdfjsLib: typeof pdfjsLib !== 'undefined',
PDFLib: typeof PDFLib !== 'undefined',
JSZip: typeof JSZip !== 'undefined',
saveAs: typeof saveAs !== 'undefined'
};
if (DEPS.pdfjsLib) {
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
}
function ensureDeps(required) {
const missing = required.filter(name => !DEPS[name]);
if (missing.length > 0) {
alert('Core dependency library failed to load: ' + missing.join('、') + '. Please check the network and refresh the page to retry.');
return false;
}
return true;
}
3.3 PDF to Image (Core Flow)
PDF-to-image uses pdf.js to render page by page, then packages the output images with JSZip. The whole process supports task lifecycle management and mid-task cancellation:
const job = beginJob(); // show cancel button, start progress timer
const arrayBuffer = await pdfFile.arrayBuffer();
if (isCancelled(job)) throw makeAbortError();
pdf = await pdfjsLib.getDocument({ data: new Uint8Array(arrayBuffer.slice(0)) }).promise;
job.pdfDoc = pdf;
if (isCancelled(job)) throw makeAbortError();
const numPages = pdf.numPages;
const zip = new JSZip();
const folderName = (pdfFile.name.replace(/\.pdf$/i, '') || 'images')
.replace(/[\/\\:*?"<>|]/g, '_'); // clean illegal characters from filename
const folder = zip.folder(folderName);
for (let i = 1; i <= numPages; i++) {
if (isCancelled(job)) throw makeAbortError();
updateProgress(Math.round(((i - 1) / numPages) * 100), `Rendering page ${i} / ${numPages}...`);
const page = await pdf.getPage(i);
if (isCancelled(job)) throw makeAbortError();
let viewport = page.getViewport({ scale }); // scale determined by clarity option: 1.5 / 2.0 / 3.0
// Limit maximum size to prevent extremely long pages from creating overly large Canvas
const MAX_DIM = 3000;
if (viewport.width > MAX_DIM || viewport.height > MAX_DIM) {
const fixScale = Math.min(MAX_DIM / viewport.width, MAX_DIM / viewport.height);
viewport = page.getViewport({ scale: scale * fixScale });
}
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d', { alpha: false });
canvas.width = Math.round(viewport.width);
canvas.height = Math.round(viewport.height);
// render task can be cancelled; cancel() interrupts pdf.js rendering
const renderTask = page.render({ canvasContext: ctx, viewport });
job.renderTask = renderTask;
try {
await renderTask.promise;
} catch (renderErr) {
canvas.width = 0; canvas.height = 0;
throw renderErr;
} finally {
if (job.renderTask === renderTask) job.renderTask = null;
}
if (isCancelled(job)) {
canvas.width = 0; canvas.height = 0;
throw makeAbortError();
}
const blob = await new Promise(resolve => canvas.toBlob(resolve, format, 0.9));
canvas.width = 0; canvas.height = 0; // release memory promptly
if (isCancelled(job)) throw makeAbortError();
if (!blob) {
throw new Error('Page ' + i + ' rendering failed. The page may be too large or the browser may be out of memory.');
}
const imgData = await blob.arrayBuffer();
folder.file(`page_${String(i).padStart(3, '0')}.${ext}`, imgData);
updateProgress(Math.round((i / numPages) * 100), `Completed page ${i} / ${numPages}...`);
// Yield execution time slices to avoid freezing the page, also update progress bar and elapsed time
await new Promise(r => setTimeout(r, 10));
}
if (isCancelled(job)) throw makeAbortError();
updateProgress(98, 'Packaging ZIP...');
const content = await zip.generateAsync({ type: 'blob' });
if (isCancelled(job)) throw makeAbortError();
updateProgress(100, 'Done!');
hideProgress();
showResult(`Successfully exported ${numPages} images`, content, `${folderName}_images.zip`);
Key points:
- Clarity option: Standard (scale 1.5, about 108 DPI), High (scale 2.0, about 144 DPI), Ultra (scale 3.0, about 216 DPI). Higher clarity yields larger file sizes.
- Format option: PNG (lossless, larger size) or JPEG (lossy, smaller size).
- Maximum dimension limit:
MAX_DIM = 3000px; overlong or wide pages are scaled down proportionally to prevent memory overflow from oversized Canvas. - Page-by-page processing and memory release: After each page is rendered, Canvas width/height are reset to zero to avoid cumulative memory usage.
- Yield time slices:
await new Promise(r => setTimeout(r, 10))gives the browser a chance to update the progress bar and avoid blocking the main thread for long periods. - Filename safety: Illegal characters such as
\ / : * ? " < > |are cleaned from the ZIP folder name. - Resource release:
finallyblock callspdf.destroy()to release pdf.js resources. - Mid-task cancellation:
isCancelled(job)is checked before and after each page loop. When the user clicks "Cancel Conversion", it throwsAbortErrorand interruptsrenderTask. Occupied Canvas and pdf.js resources are released immediately. - Progress timer: The progress bar adds an "elapsed N seconds" display so users can gauge processing time.
Generated ZIP files use names like page_001.png, page_002.png, etc., for easy lookup by page.
3.4 Image to PDF (Core Flow)
Image-to-PDF uses pdf-lib to create the document and embeds each image as an independent page. The whole process supports task lifecycle management and mid-task cancellation:
const job = beginJob(); // show cancel button, start progress timer
const pdfDoc = await PDFLib.PDFDocument.create();
const files = img2pdfFiles.slice(); // snapshot, avoid order changes due to mid-task list modifications
const total = files.length;
for (let i = 0; i < total; i++) {
if (isCancelled(job)) throw makeAbortError();
updateProgress(Math.round((i / total) * 100), `Processing image ${i + 1} / ${total}...`);
const file = files[i];
const arrayBuffer = await file.arrayBuffer();
if (isCancelled(job)) throw makeAbortError();
let image;
if (file.type === 'image/png') {
image = await pdfDoc.embedPng(arrayBuffer);
} else if (file.type === 'image/jpeg' || file.type === 'image/jpg') {
image = await pdfDoc.embedJpg(arrayBuffer);
} else {
// WebP and other formats pdf-lib doesn't directly support: convert via Canvas to JPEG, full cancellation hooks
image = await convertToJpegEmbed(pdfDoc, file, job);
}
if (isCancelled(job)) throw makeAbortError();
const imgW = image.width;
const imgH = image.height;
if (pageSizeMode === 'auto') {
// page size auto-fits image original size
const page = pdfDoc.addPage([imgW, imgH]);
page.drawImage(image, { x: 0, y: 0, width: imgW, height: imgH });
} else {
// uniform A4 size, choose landscape/portrait based on image orientation
const isLandscape = imgW > imgH;
const pageW = isLandscape ? 841.89 : 595.28;
const pageH = isLandscape ? 595.28 : 841.89;
const page = pdfDoc.addPage([pageW, pageH]);
// proportional scaling and centering
const s = Math.min(pageW / imgW, pageH / imgH);
const drawW = imgW * s;
const drawH = imgH * s;
const x = (pageW - drawW) / 2;
const y = (pageH - drawH) / 2;
page.drawImage(image, { x, y, width: drawW, height: drawH });
}
updateProgress(Math.round(((i + 1) / total) * 100), `Completed image ${i + 1} / ${total}...`);
}
if (isCancelled(job)) throw makeAbortError();
updateProgress(98, 'Saving document...');
const pdfBytes = await pdfDoc.save();
if (isCancelled(job)) throw makeAbortError();
const blob = new Blob([pdfBytes], { type: 'application/pdf' });
updateProgress(100, 'Done!');
hideProgress();
showResult(`Successfully merged ${total} images`, blob, `images_merged.pdf`);
WebP and other formats not directly embeddable are handled by convertToJpegEmbed, which supports cancelling pending image load Promises via job.hooks:
async function convertToJpegEmbed(pdfDoc, file, job) {
const url = URL.createObjectURL(file);
const img = new Image();
let cancelled = false;
const cancelPromise = new Promise((_, reject) => {
job.hooks.push(() => {
cancelled = true;
try { img.onload = img.onerror = null; } catch (e) { /* ignore */ }
try { img.src = ''; } catch (e) { /* ignore */ }
reject(makeAbortError());
});
});
const loadPromise = new Promise((resolve, reject) => {
img.onload = () => resolve();
img.onerror = () => reject(new Error('Image load failed: ' + file.name + ' (format may not be supported)'));
const timer = setTimeout(() => reject(new Error('Image load timeout: ' + file.name)), 15000);
job.hooks.push(() => clearTimeout(timer));
});
img.src = url;
try {
await Promise.race([loadPromise, cancelPromise]);
} finally {
try { img.onload = img.onerror = null; } catch (e) { /* ignore */ }
try { URL.revokeObjectURL(url); } catch (e) { /* ignore */ }
}
if (cancelled || isCancelled(job)) throw makeAbortError();
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
// fill white background to prevent transparent areas turning black in PDF
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
const jpgBlob = await new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', 0.95));
canvas.width = 0; canvas.height = 0;
if (cancelled || isCancelled(job)) throw makeAbortError();
if (!jpgBlob) {
throw new Error('Image to JPEG conversion failed (image may be too large): ' + file.name);
}
const jpgBuffer = await jpgBlob.arrayBuffer();
return pdfDoc.embedJpg(jpgBuffer);
}
Key points:
- Format embedding: PNG uses
embedPng, JPEG usesembedJpg; for WebP and other formats pdf-lib doesn't directly support, the image is drawn to a Canvas with a white background (to avoid black background for transparent areas), thentoBlob('image/jpeg', 0.95)converts it to JPEG before embedding. - Page size:
automode generates pages at the image's original size;A4mode chooses portrait (595.28×841.89 pt) or landscape (841.89×595.28 pt) based on image orientation. - Proportional scaling and centering:
scale = min(pageW/imgW, pageH/imgH)preserves aspect ratio and centers to avoid distortion. - Timeout and error handling: Image loading has a 15-second timeout;
onerrorcatches corrupted files;try-finallyensuresURL.revokeObjectURLreleases object URLs. - Memory management: Canvas and object URLs are released after each page.
- List snapshot:
files = img2pdfFiles.slice()creates a snapshot to prevent order changes from drag-and-drop during conversion. - Mid-task cancellation:
isCancelled(job)is checked before and after processing each image;convertToJpegEmbed's image loading Promise responds to cancellation viajob.hooks; after cancellation, no further pages are embedded. - Filename HTML escaping:
escapeHtmlis applied to filenames before display to prevent XSS.
3.5 Image List and Drag Ordering
Image-to-PDF mode supports multiple uploads and drag ordering:
- Build a unique key from
filename_size_modificationTimefor deduplication, avoiding duplicate files disturbing order. - List items have
draggable="true", using the HTML5 drag-and-drop API for reordering. dragstartrecords the current item index;dropremoves the item from its original position and inserts it at the target position.- Validate that
fromIndexis a valid number and within bounds, preventingparseIntNaN from external file drag-in. - Filenames are HTML-escaped before display to prevent XSS.
3.6 File Download
Generated files (ZIP or PDF) are converted to Blob and downloaded:
if (typeof saveAs === 'function') {
saveAs(downloadBlob, downloadName);
} else {
const url = URL.createObjectURL(downloadBlob);
const a = document.createElement('a');
a.href = url;
a.download = downloadName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
FileSaver.js's saveAs is preferred; if the library fails to load, the fallback creates a hidden a tag to trigger native browser download and promptly calls revokeObjectURL to release memory.
3.7 Frontend Implementation Points
- Dependency detection: Before each conversion button click, check if required libraries are available; if CDN load fails, prompt the user to check the network and refresh.
- Task lifecycle:
beginJob/endJob/cleanupJobuniformly manage cancel button visibility, progress timer start/stop, render task, and pdf document resource release. - State lock: During conversion, buttons are disabled and upload area interaction is closed to prevent duplicate submissions; switching modes cancels any in-progress task first.
- Progress feedback: Progress bar and current status are updated after each page/image, with an "elapsed N seconds" display so users can see processing status.
- Mid-task cancellation: The progress area adds a "Cancel Conversion" button. Clicking marks the task as cancelled, interrupts the pdf.js render task, triggers image-load hooks to release pending Promises, releases occupied Canvas, pdf documents, and object URLs immediately, and shows "Conversion cancelled, no file generated" in the result area.
- Result panel: On success, shows a result message (e.g., "Successfully exported N images") with a download button; after cancellation, indicates no file was generated.
- Memory management:
URL.revokeObjectURLreleases object URLs of images and result Blobs promptly; Canvas width/height are reset after each page. - Dark mode: The site uses CSS variables for colors; in dark mode, card backgrounds, borders, and text colors adapt automatically.
- File type validation: PDF-to-image accepts only
.pdfextension orapplication/pdfMIME type; image-to-PDF acceptsimage/png, image/jpeg, image/webp.
All input, drawing, and conversion happen in the browser locally; file content is never uploaded to any server.
4. Key Technical Challenges and Solutions
| Challenge | Solution |
|---|---|
| pdf-lib doesn't directly support WebP/GIF/BMP | Draw via Canvas with white background, toBlob('image/jpeg') to convert to JPEG, then embed. |
| Transparent background images may appear black in PDF | Fill white background with fillRect before drawing the image. |
| Extremely long PDF pages cause oversized Canvas and memory overflow | Cap max side length at 3000 px, scale down proportionally. |
Large images cause toDataURL memory overflow |
Use toBlob instead, and catch failures in try-catch. |
| Image loading hangs and freezes the page | img.onload/onerror with a 15-second setTimeout timeout. |
| Long conversions block the main thread and freeze the progress bar | After each page/image, setTimeout yields time slices, paired with real-time progress updates. |
| External file drag-in causes sorting index errors | Validate fromIndex is a valid number and within bounds; return early on errors. |
| Illegal characters in ZIP folder name | Regex cleans \ / : * ? " < > and other characters. |
saveAs unavailable in non-HTTPS environments |
FileSaver.js preferred; fallback to native a.download download. |
| CDN failure for third-party libraries | Check dependency availability before conversion; prompt to check network and refresh. |
| Users want to cancel long conversions and release memory | Added "Cancel Conversion" button and task lifecycle management; check isCancelled(job), interrupt renderTask, trigger job.hooks to release pending Promises; pdf.destroy() in finally and Canvas reset. |
| Pure frontend with no backend dependency | All processing is frontend-only; browser can run offline. |
5. Usage Examples
Scenario 1: Convert a 10-page contract PDF to images for page-by-page review
- Open
https://toolion.cn/pdf-img-convert/, keep "PDF to Image" mode. - Click the upload area or drag the PDF file in.
- Choose export format "JPEG (lossy, smaller size)" and clarity "High (about 144 DPI, suitable for printing)".
- Click "Start Conversion and Package Download", wait for the progress bar to complete.
- Download the ZIP archive containing
page_001.jpgtopage_010.jpgfor page-by-page review.
Scenario 2: Merge 5 ID photos into one A4 PDF for reimbursement
- Switch to "Image to PDF" mode.
- Click the upload area or drag 5 JPG/PNG images in.
- Drag to adjust image order, ensuring front and back sides are in correct order.
- Choose page size "Uniform A4 size (centered with white space)".
- Click "Generate PDF and Download", wait for the progress bar to complete.
- Download
images_merged.pdf.
Notes:
- PDF-to-image renders each page as an image; text will no longer be copyable or searchable. Suitable when you only need to view or insert into other documents.
- Higher clarity produces larger image files and correspondingly larger ZIP archives.
- Image-to-PDF supports JPG, PNG, and WebP formats; WebP is converted to JPEG via Canvas before embedding.
- Converting many pages or high-resolution images at once may take several seconds; please wait for the progress to finish.
- If you don't need the complete result, click "Cancel Conversion" to interrupt at any time. Occupied memory is automatically released, and the result area shows "Conversion cancelled, no file generated".
- For sensitive documents like contracts, financial statements, and personal IDs, it's recommended to use local processing tools to avoid uploading to third-party servers.
6. Disclaimer
This article is for technical implementation sharing only. The tool is for learning and daily convenience, and does not constitute any commercial advice. After PDF-to-image conversion, text cannot be copied. Image-to-PDF may alter the original file structure because pages are reassembled. It's recommended to check important documents after generation. The tool processes files in browser local memory; files are not uploaded to any server, and are released from memory when the page is closed.
7. Summary
This article presents a pure-frontend solution for bidirectional PDF and image conversion. The core design ideas:
- Bidirectional conversion: PDF→image (page-by-page rendering + JSZip packaging) and image→PDF (pdf-lib embedding) are done in the same page.
- pdf.js rendering: Each PDF page is rendered to a Canvas, supporting PNG/JPEG output and three clarity levels (standard/high/ultra).
- pdf-lib assembly: PNG/JPEG are embedded directly; WebP is converted to JPEG via Canvas, then embedded; supports A4/auto page size and proportional scaling with centering.
- Drag ordering: HTML5 drag-and-drop API enables custom image order, allowing flexible adjustments before merging.
- ZIP packaging: Multiple images from PDF conversion are packaged into one ZIP file for unified management and download.
- Privacy first: All processing happens in the browser locally; files are never uploaded to servers; no login needed, no watermark.
- Mid-task cancellation: Users can click "Cancel Conversion" to interrupt at any time; occupied memory and rendering resources are automatically released.
- Robustness: Dependency load detection, image loading timeout, Canvas max dimension limit, memory release, try-catch error handling, and
saveAsfallback.
This solution suits scenarios needing lightweight, pure-frontend PDF and image interconversion, and can serve as a technical reference for frontend document-processing tool pages.
#PDFtoImage #ImageToPDF #PDFandImageConversion #pdf.js #pdf-lib #JSZip #PureFrontend #JavaScript #Canvas #LocalProcessing #PrivacySecurity #OfficeTools #DocumentProcessing #ToolDevelopment
Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.
MAX_DIM = 3000, I accept that. For overly long pages, not scaling proportionally and Canvas blowing up means whole-page memory overflow; preventing it beforehand is better than fixing it after. But reducing size alone isn't enough—what really freezes people is your line about 'using setTimeout to yield time slices after each page': yielding every 10 ms, a 50-page contract still takes several minutes to convert, the progress bar moves, but users will still think it's stuck. The real bottleneck for this kind of tool has never been single-page rendering, but rather the absence of a cancel button: once it's halfway through, you can't stop it. Does your current version support cancelling mid-conversion?
Thanks for your comment, your point is spot on. You're right: the original version really had no cancellation entry point, once conversion started you could only wait, a 50-page contract half-converted couldn't be stopped. We've fixed that. Let me clarify one small point: setTimeout(..., 10) yielding time slices isn't the main reason a 50-page conversion takes minutes—50 pages total about half a second. What actually stalls is each page's page.render() and canvas.toBlob(), especially with high/ultra-high resolution and complex pages, a single page can block the main thread, and the progress bar only updates between pages, so you get the visual of 'progress bar moving but seems frozen.' That UX issue is also addressed. The current version adds these: A 'Cancel Conversion' button in the progress area, visible during conversion; clicking triggers cancellation, the button becomes 'Cancelling...' and is disabled to prevent repeated clicks; For PDF-to-image, each page's renderTask is saved; on cancel, renderTask.cancel() is called directly, pdf.js throws a cancellation exception, and the loop exits immediately; For image-to-PDF, images needing transcoding like WebP have their loading Promises registered in job.hooks; cancel triggers reject so the Promise doesn't hang forever; Whether completed or cancelled, the pdf.js document is destroyed, canvases cleared, object URLs released, button state restored, and a clear message 'Conversion cancelled, no file generated' is shown; Progress text changed to 'Completed i/N pages', with 'Elapsed X min X sec' on the right, reducing the 'seems frozen' misjudgment. So the answer now is: mid-conversion cancellation is supported. Cancellation isn't simply stopping the loop; it also interrupts the rendering task in progress, cleans the memory already occupied, discards the incomplete ZIP/PDF, and returns the UI to a state ready to restart. So that judgment of yours—'the real bottleneck isn't single-page rendering, but the absence of a cancel button'—we accept and have implemented it in code. Thanks again for your comment, and please point out any further issues.