跪拜 Guibai
← All articles
Frontend

PDF↔Image Conversion, Local and Cancellable: Inside a Pure-Frontend Tool

By Toolion ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Sensitive documents never leave the machine, and the patterns for cancellation, timeout, and memory release show how to keep long-running browser tasks responsive without a server.

Summary

A browser-only utility handles both PDF-to-image and image-to-PDF conversion without any server upload. PDF pages render one by one through pdf.js onto a Canvas, then bundle into a ZIP via JSZip; images embed into a fresh PDF with pdf-lib, and WebP files take a detour through Canvas-to-JPEG conversion because pdf-lib can't embed them directly. The whole thing runs on native JavaScript with no framework, pulling four libraries from CDN.

The tool exists because online converters force sensitive contracts, invoices, and IDs onto third-party servers, slap on watermarks, or limit free use. Everything here stays in browser memory, works offline, and offers drag reordering, A4 or auto page sizing, and three clarity levels for PDF export. The engineering details matter: a 3000-px cap on Canvas dimensions prevents memory blowouts on long pages; each page resets its Canvas to zero after rendering; a 15-second image load timeout stops hung files from freezing the UI; and a cancel button interrupts pdf.js render tasks and pending image promises via job hooks, releasing the occupied memory and showing a "no file generated" message.

Takeaways
— pdf.js renders each PDF page to a Canvas; clarity scales of 1.5, 2.0, and 3.0 map to roughly 108, 144, and 216 DPI.
— MAX_DIM = 3000 px caps canvas width and height, scaling down overlong pages to avoid memory overflow.
— WebP images are drawn onto a Canvas with a white background and exported as JPEG (quality 0.95) before pdf-lib embedding.
— Cancellation checks isCancelled(job) before and after each page and calls renderTask.cancel() to interrupt pdf.js rendering.
— Image loading in convertToJpegEmbed has a 15-second timeout and uses job.hooks to reject the pending promise on cancel.
— Canvas width and height are reset to zero after each page render to release memory.
— PDF-to-image packages pages into a ZIP with names like page_001.png, page_002.png; folder names have illegal characters \ / : * ? " < > | stripped.
— The tool uses no framework, only native JavaScript, with four CDN libraries: pdf.js 3.11.174, pdf-lib 1.17.1, JSZip 3.10.1, and FileSaver.js 2.0.5.
— Image-to-PDF offers auto page size (image original dimensions) or uniform A4, choosing landscape (841.89×595.28 pt) or portrait (595.28×841.89 pt) based on orientation.
— A snapshot via slice() of the file list protects the merge order from drag-and-drop changes mid-conversion.
Conclusions

Relying on native JavaScript keeps the dependency set to four CDN libraries, but the real complexity is coordinating cancellation across pdf.js render tasks, image loaders, and Blob creation.

Converting WebP to JPEG loses transparency, an acceptable tradeoff for PDF output but a reminder that browser-only conversion has format limits.

The 15-second image load timeout prevents a hung network request from freezing the UI, but it also means very large images on slow connections may time out before they finish loading.

The task lifecycle pattern of checking cancellation between every await point, rather than only at the start, is what makes the cancel button actually release resources mid-operation.

Concepts & terms
renderTask.cancel()
A pdf.js method that interrupts an in-progress page render. Calling it causes the render promise to reject, allowing the surrounding code to catch the error, release the Canvas, and abort the conversion.
job.hooks
An array of callbacks registered during image-to-PDF conversion. When the user cancels, each hook runs to reject pending image-load promises and clear timers, so no unresolved async operation keeps the browser occupied.
Canvas MAX_DIM cap
A maximum dimension of 3000 pixels applied to rendering viewports. If a PDF page exceeds this, the scale is reduced proportionally so the Canvas never becomes large enough to exhaust browser memory.
From the discussion
Featured comments
组合搭配函数 1 likes

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?

Toolion

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.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗