Most "PDF tools" sites upload your file to a server. For simple jobs you do not need one. Merging, splitting, turning images into a PDF and even compressing a scanned PDF can all run in the browser, so nothing leaves the user's machine and you have no backend to run.
In this post I will build that in Nuxt 4. The full code is in an MIT-licensed starter you can clone, and there is a live demo:
- Repo: https://github.com/mani-django09/nuxt-pdf-tools-starter
- Demo: https://nuxt-pdf-tools-starter.netlify.app
The two libraries
You need two, because they do different jobs:
- pdf-lib creates and edits PDFs: copy pages between documents, embed JPG/PNG images, save bytes. It cannot render a page to pixels.
- pdfjs-dist (Mozilla's pdf.js) parses and renders PDFs to a canvas. It cannot write PDFs.
Merge and split only need pdf-lib. Compress and "PDF to image" need pdf.js to get pixels, and compress then uses pdf-lib to build the new file.
npx nuxi init pdf-tools
cd pdf-tools
npm i pdf-lib pdfjs-dist jszip
Rule 1: browser only
Both libraries touch browser APIs. Do not import them at the top of a file that runs during SSR. I keep all PDF code in one composable and import the libraries lazily inside functions, which are only called from event handlers:
// app/composables/usePdf.ts
async function loadPdfLib() {
return await import('pdf-lib')
}
async function loadPdfjs() {
const pdfjs = await import('pdfjs-dist')
const worker = (await import('pdfjs-dist/build/pdf.worker.min.mjs?url')).default
pdfjs.GlobalWorkerOptions.workerSrc = worker
return pdfjs
}
The ?url import is the part that trips people up. pdf.js runs its parser in a web worker, and Vite needs to emit the worker file and give you its URL. Importing the worker with ?url does exactly that.
Merge
Create an empty document, then copy every page of every input into it:
export async function mergePdfs(files: File[]): Promise<Blob> {
const { PDFDocument } = await loadPdfLib()
const out = await PDFDocument.create()
for (const file of files) {
const src = await PDFDocument.load(await file.arrayBuffer())
const pages = await out.copyPages(src, src.getPageIndices())
pages.forEach(p => out.addPage(p))
}
return new Blob([await out.save() as BlobPart], { type: 'application/pdf' })
}
Order of the files array is the order of the output, so a drag-to-reorder list in the UI is all the "merge order" feature you need.
Split
Users think in page ranges like 1-3, 5, 8-. Parse that into zero-based groups, and make each comma-separated part its own output file:
export function parseRanges(input: string, total: number): number[][] {
const groups: number[][] = []
for (const raw of input.split(',')) {
const part = raw.trim()
if (!part) continue
const m = part.match(/^(\d*)\s*-\s*(\d*)$/)
let from: number, to: number
if (m) {
from = m[1] ? parseInt(m[1], 10) : 1
to = m[2] ? parseInt(m[2], 10) : total
} else if (/^\d+$/.test(part)) {
from = to = parseInt(part, 10)
} else {
throw new Error(`Cannot read "${part}". Use values like 1-3, 5, 8-`)
}
if (from < 1 || to > total || from > to) {
throw new Error(`Range "${part}" is outside 1-${total}`)
}
const g: number[] = []
for (let i = from; i <= to; i++) g.push(i - 1)
groups.push(g)
}
if (!groups.length) throw new Error('Enter at least one page or range')
return groups
}
Validate loudly. A silent "page 40 of a 12 page file" is the kind of bug users report as "the tool is broken". Then splitting is the merge loop in reverse: for each group, create a document and copyPages from the source. Several outputs? Zip them with JSZip so the user gets one download.
Compress (and what it really does)
Honest version: in the browser, the practical way to shrink a PDF is to render each page to a canvas, export it as a JPEG, and rebuild the PDF from those images.
export async function compressPdf(file: File, opts: { quality: number, scale: number }) {
const pdfjs = await loadPdfjs()
const { PDFDocument } = await loadPdfLib()
const src = await pdfjs.getDocument({ data: new Uint8Array(await file.arrayBuffer()) }).promise
const out = await PDFDocument.create()
for (let i = 1; i <= src.numPages; i++) {
const page = await src.getPage(i)
const size = page.getViewport({ scale: 1 }) // PDF points
const canvas = await renderPage(page, opts.scale) // pixels
const jpg = await canvasToBlob(canvas, 'image/jpeg', opts.quality)
const img = await out.embedJpg(new Uint8Array(await jpg.arrayBuffer()))
const p = out.addPage([size.width, size.height])
p.drawImage(img, { x: 0, y: 0, width: size.width, height: size.height })
canvas.width = canvas.height = 0 // free the bitmap
}
return new Blob([await out.save() as BlobPart], { type: 'application/pdf' })
}
Two details matter:
-
Keep the page size in points, not pixels. Render at
scalefor sharpness, but create the output page from the scale 1 viewport. Otherwise a 2x render gives you a page twice as big. - Free canvases. Setting width and height to 0 releases the bitmap. On a 60 page scan, forgetting this is how you crash a phone tab.
The trade-off is real: the result is lossy and the text is no longer selectable. That is fine for scans and photo-heavy files, and the wrong choice for a text-heavy contract you need to search. Say so in your UI. I put it in the code comment and the README as well.
If you need "make it under 200 KB" rather than "quality 0.6", you can search over quality (and scale): compress, measure the blob size, bisect, stop when you are just under the target. Start with a binary search on quality between 0.2 and 0.95, and only lower scale if quality alone cannot reach the size. (The starter takes fixed options; this search is a suggestion, not something it does.)
Images to PDF and PDF to images
Images to PDF: embedJpg / embedPng for those two formats. For WebP, GIF or BMP, draw through a canvas, export PNG and embed that:
const bmp = await createImageBitmap(file)
const canvas = document.createElement('canvas')
canvas.width = bmp.width
canvas.height = bmp.height
canvas.getContext('2d')!.drawImage(bmp, 0, 0)
PDF to images is the render step from compress, but you keep each canvas as PNG or JPEG instead of embedding it, then zip the results.
Downloading the result
A tiny helper turns any Blob into a file download:
export function downloadBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), 5000)
}
Optional: saving results with NuxtHub Blob
If you want shareable links or history, the repo has an optional/nuxthub-blob/ folder with three server routes (upload, list, serve) that store files in NuxtHub Blob. They cap uploads at 25 MB, accept only PDF, ZIP, PNG and JPEG, sanitise filenames, and only serve from a results/ prefix. It is opt-in: the tools work with no server at all.
Where browser-only stops
This approach is great for private, small to medium files. It stops being the right tool when you need:
- Office formats (Word, Excel, PowerPoint to or from PDF). That needs LibreOffice or similar on a server.
- OCR on scanned files at any volume.
- Very large PDFs on low-memory phones.
- Real "strip images but keep text" compression, which needs a server tool like Ghostscript.
I run a larger toolkit that covers those on a server, at smallpdf.us (independent site, not affiliated with Smallpdf.com; uploaded files are deleted about an hour after processing). The Nuxt starter is the no-server subset, and it is MIT licensed, so take whatever you want.
Try it
git clone https://github.com/mani-django09/nuxt-pdf-tools-starter
cd nuxt-pdf-tools-starter
npm i && npm run dev
If you find a PDF that breaks one of the tools, open an issue with the symptom (not the file, please). Those are the cases I most want to fix.
Top comments (0)