Build a Browser-Based Image to PDF Converter with JavaScript

By

Introduction

Whether you need to combine scanned documents, screenshots, receipts, notes, certificates, or multiple photos into a single PDF, modern browsers make it easier than ever. With JavaScript running entirely on the client side, you can create a fast, private, and user-friendly tool that processes images without uploading them to any server. This guide walks you through building a complete Image to PDF converter that supports uploading multiple images, sorting them, choosing page orientation and size, configuring margins, and merging images into either a single PDF or separate files—all with preview and download capabilities.

Build a Browser-Based Image to PDF Converter with JavaScript
Source: www.freecodecamp.org

What You Need

  • A text editor (VS Code, Sublime, or any)
  • An HTML file (e.g., index.html)
  • A JavaScript file (e.g., app.js)
  • The jsPDF library (loaded via CDN)
  • A modern web browser (Chrome, Firefox, Edge, etc.)

Step-by-Step Guide

Step 1: Set Up Your Project Files

Create two files in the same folder: index.html and app.js. No backend or database is required—everything runs in the browser. This keeps the tool lightweight and protects user privacy.

Step 2: Include the jsPDF Library

Add the jsPDF library via CDN inside the <head> of your HTML file. This library allows you to generate PDF files directly in JavaScript.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

Once loaded, you can create and export PDF documents from the browser.

Step 3: Create the Upload Interface

Build a simple file input that accepts image files and a button to trigger conversion.

<input type="file" id="upload" multiple accept="image/*">
<button onclick="convertToPDF()">Convert to PDF</button>

Optionally, add controls for sorting, page size, orientation, margins, and merge mode (single vs. separate PDFs). These enhancements make the tool more versatile.

Step 4: Read Uploaded Images with JavaScript

When a user selects files, use the FileReader API to read each image as a data URL. Store the results in an array for later processing.

const fileInput = document.getElementById('upload');
const images = [];

fileInput.addEventListener('change', function(e) {
  const files = e.target.files;
  for (let file of files) {
    const reader = new FileReader();
    reader.onload = function(event) {
      images.push(event.target.result);
    };
    reader.readAsDataURL(file);
  }
});

Step 5: Initialize jsPDF and Create PDF Pages

Inside your conversion function, create a new jsPDF instance with your chosen orientation (portrait or landscape) and unit (e.g., 'mm' or 'in'). Then add each image as a new page.

function convertToPDF() {
  const { jsPDF } = window.jspdf;
  const doc = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' });
  images.forEach((img, index) => {
    if (index !== 0) doc.addPage();
    doc.addImage(img, 'JPEG', 10, 10, 190, 277); // adjust margins
  });
  doc.save('converted-images.pdf');
}

Step 6: Handle Multiple Images and Sorting

Allow users to rearrange images before conversion. You can implement drag-and-drop or simple sort buttons. For a drag-and-drop approach, use the HTML5 Drag and Drop API. Alternatively, provide up/down buttons to move items in the list. Store the order in the images array before generating the PDF.

Build a Browser-Based Image to PDF Converter with JavaScript
Source: www.freecodecamp.org

Step 7: Configure PDF Settings (Orientation, Size, Margins)

Add dropdowns or radio buttons for:

  • Orientation: Portrait or Landscape
  • Page size: A4, Letter, Legal, or custom
  • Margins: No margins, small, medium, large

When initializing jsPDF, pass these options. For margins, adjust the x, y, width, and height parameters in addImage accordingly.

Step 8: Merge into Single PDF or Create Separate PDFs

Provide a toggle for users to choose:

  • Single PDF: All images in one document (default behavior above).
  • Separate PDFs: Generate one PDF per image. This can be done by looping through the images array and saving each as a different file. Note: browsers may block multiple downloads unless triggered by user gestures.

Step 9: Preview and Download

Before downloading, you can show a preview of the generated PDF using an iframe or a blob URL. For example:

const blob = doc.output('blob');
const url = URL.createObjectURL(blob);
window.open(url);

Then trigger the download with doc.save() or a custom download button.

Tips for Real-World Use

  • File size matters: Large images can slow down the browser. Consider resizing images client-side before adding them to the PDF to improve performance.
  • Privacy first: Since all processing happens locally, users can safely upload sensitive documents without server transfer.
  • Browser compatibility: jsPDF works in all modern browsers. Test on Chrome, Firefox, and Edge for consistent behavior.
  • Multiple downloads: When generating separate PDFs, use a loop with a slight delay or prompt users to click each download, as browsers often block automatic multiple downloads.
  • User feedback: Show a progress indicator or loading spinner while generating the PDF, especially for many images.
  • Common mistakes to avoid: Forgetting to call addPage() for subsequent images (unless you want them on the same page), not handling image orientation (rotation), and ignoring memory limits for very large files.

With these steps, you have a fully functional client-side Image to PDF converter that is fast, private, and customizable. Enjoy building!

Tags:

Related Articles

Recommended

Discover More

Transforming Your Astro Workflow: A How-To for the Markdown ComponentWhy the $10 Trillion Robotaxi Opportunity Makes EV Stocks a Smart BetScore Major Savings on Samsung Galaxy Tabs, S26 Ultra Bundle, Fire TV Stick 4K, and OLED Gaming MonitorTesla's Self-Driving Fleet Passes 10 Billion Miles — But Full Autonomy Remains ElusiveHow to Implement Off-Policy Reinforcement Learning Without Temporal Difference Learning