跪拜 Guibai
← Back to the summary

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:

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.

pdf-img-convert1.png

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>

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:

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:

3.5 Image List and Drag Ordering

Image-to-PDF mode supports multiple uploads and drag ordering:

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

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

  1. Open https://toolion.cn/pdf-img-convert/, keep "PDF to Image" mode.
  2. Click the upload area or drag the PDF file in.
  3. Choose export format "JPEG (lossy, smaller size)" and clarity "High (about 144 DPI, suitable for printing)".
  4. Click "Start Conversion and Package Download", wait for the progress bar to complete.
  5. Download the ZIP archive containing page_001.jpg to page_010.jpg for page-by-page review.

Scenario 2: Merge 5 ID photos into one A4 PDF for reimbursement

  1. Switch to "Image to PDF" mode.
  2. Click the upload area or drag 5 JPG/PNG images in.
  3. Drag to adjust image order, ensuring front and back sides are in correct order.
  4. Choose page size "Uniform A4 size (centered with white space)".
  5. Click "Generate PDF and Download", wait for the progress bar to complete.
  6. Download images_merged.pdf.

Notes:

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:

  1. Bidirectional conversion: PDF→image (page-by-page rendering + JSZip packaging) and image→PDF (pdf-lib embedding) are done in the same page.
  2. pdf.js rendering: Each PDF page is rendered to a Canvas, supporting PNG/JPEG output and three clarity levels (standard/high/ultra).
  3. 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.
  4. Drag ordering: HTML5 drag-and-drop API enables custom image order, allowing flexible adjustments before merging.
  5. ZIP packaging: Multiple images from PDF conversion are packaged into one ZIP file for unified management and download.
  6. Privacy first: All processing happens in the browser locally; files are never uploaded to servers; no login needed, no watermark.
  7. Mid-task cancellation: Users can click "Cancel Conversion" to interrupt at any time; occupied memory and rendering resources are automatically released.
  8. Robustness: Dependency load detection, image loading timeout, Canvas max dimension limit, memory release, try-catch error handling, and saveAs fallback.

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

Comments

Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.

组合搭配函数 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.