Skip to main content

How to Edit PDF Text in the Browser with JavaScript

Why changing one word in a PDF is harder than it looks, and how to do it without drawing a white box over the old text.

Updated 12 min readMarkdown
How to Edit PDF Text in the Browser with JavaScript

We keep hearing the same request from teams that have put a JavaScript PDF viewer in their web app: "The contract says thirty-six months, it should say twenty-four. Can the user just fix it?"

The short answer: the open-source browser libraries cannot change text that is already in a PDF. Most "JavaScript PDF editor" tutorials cover the old words with a white rectangle and draw new ones on top, which leaves the old text in the file. This post explains why the format makes editing hard, what that workaround costs, and how to edit the existing text for real, from a toolbar and from code.

A PDF does not contain paragraphs

An HTML page says "here is a paragraph, lay it out". A PDF says something much closer to "put these glyphs at these coordinates, in this font, at this size". The layout was done once, by whatever program made the file, and only the result was saved.

That has three consequences for anyone who wants to change a word.

There are no lines or paragraphs to edit. What looks like a paragraph is a series of separate text objects. A single line can be several of them, split wherever the font, the weight or the spacing changed. Nothing in the page content says which pieces belong together, or where the paragraph's right edge is. Tagged PDFs do carry a separate structure tree for accessibility, but many files have none, and it does not drive the layout either.

The font is usually incomplete. To keep files small, PDF producers embed a subset of each font: only the characters the document uses in that font. If the bold face was only ever used for the heading "TERMS", the embedded bold font contains five letters. Type anything else in it and there is nothing to draw the new characters with.

Nothing reflows. If the new text is longer than the old, nothing moves the rest of the line, wraps the paragraph or keeps the column aligned. An editor has to work the layout out again from the positions alone.

What PDF.js and pdf-lib can and cannot edit

The two libraries most browser PDF work starts with are both good at what they set out to do.

PDF.js is Mozilla's renderer, the one behind Firefox's built-in viewer. Its FAQ describes it as "a general-purpose library to parse and render PDFs" and says it "is designed for reading PDF files". Its viewer can add annotations on top of a page and fill forms. It does not change the text the page already has.

pdf-lib creates and modifies PDF files in JavaScript. Its feature list includes drawing text, drawing images, filling and flattening forms, and adding, removing and copying pages. Changing text that is already drawn on a page is not on that list.

Real content editing does exist elsewhere: several commercial SDKs do it (ours is one, more on that below), and so do some server-side tools. With the open-source browser libraries, though, almost every tutorial ends up at the same trick.

The white box trick

You cannot change the old words, so you cover them and draw new ones on top:

import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';

const pdfDoc = await PDFDocument.load(existingBytes);
const page = pdfDoc.getPages()[0];
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);

// 1. Hide the old words under a white rectangle
page.drawRectangle({
  x: 212,
  y: 508,
  width: 96,
  height: 14,
  color: rgb(1, 1, 1),
});

// 2. Draw the new words over it
page.drawText('twenty-four months', { x: 212, y: 511, size: 11, font });

const editedBytes = await pdfDoc.save();

On screen it can look fine. The file is another matter:

  • The old text is still there. Select all, copy, search, or run the file through a text extractor, and "thirty-six months" comes back. This is the same mistake as a failed redaction: a value you believe you removed is still in the document you send out.
  • The font does not match. The new words are drawn in Helvetica next to a paragraph set in the document's own face. You can embed the real font with @pdf-lib/fontkit if you have its file, but you rarely do, and the subset inside the PDF cannot be reused for new characters.
  • Longer or shorter text does not fit. If the new text is wider than the box, it runs over what follows. If it is narrower, it leaves a gap.
  • You have to find the coordinates. The numbers in that snippet came from somewhere. In a real app you convert a selection on screen to page coordinates for every edit, accounting for zoom, rotation and the PDF's bottom-left origin.
  • It breaks on anything but white paper. A tinted table row or a scanned background shows the rectangle.

It is a reasonable way to stamp a date on a form. It is not a way to let users edit documents.

What a real JavaScript PDF editor has to do

To change the words instead of covering them, an editor has to do four things:

  1. Group the page's text objects into the lines and blocks a person would call a paragraph.
  2. Write the change back into those objects, so the old text is gone from the file.
  3. Set the new characters in the document's own font, and have an answer for the characters the embedded subset lacks.
  4. Rewrap the lines inside the block's width, without pushing the rest of the page around.

That list is what the Edit text tool in the Kernstra Web SDK does. Disclosure: we make it. It is a commercial JavaScript PDF viewer and editor that runs in the browser, and the rest of this post uses it.

Edit PDF text in the browser with JavaScript, step by step

1. Install

npm install @kernstra/pdf-web-sdk

The package includes TypeScript types and works with plain JavaScript, React, Vue, Angular, Svelte, Next.js, Nuxt and SvelteKit. You need a license key to run it. Development keys are free; they watermark what they render and save, which is fine while you build. The get started guide shows where to get one.

2. Open a document in a viewer

Give the viewer one element with a real height:

<div id="pdf-container"></div>
#pdf-container {
  width: 100%;
  height: 100dvh;
}

Then initialize the SDK, open a file and mount the viewer:

import { Kernstra, PDFDocument, PDFViewer, SDKMode } from '@kernstra/pdf-web-sdk';

// Once per page load. The key is bound to your domains, not a secret,
// but read it from an environment variable to keep it out of your source.
await Kernstra.init({ license: import.meta.env.KERNSTRA_LICENSE });

const doc = await PDFDocument.fromUrl('/contract.pdf');
// or: PDFDocument.fromFile(fileInput.files[0])
// or: PDFDocument.fromBytes(uint8Array)

const viewer = new PDFViewer(document.getElementById('pdf-container')!, doc, {
  mode: SDKMode.FULL,
  toolbar: { print: true, download: true },
});
await viewer.whenReady();

A few things trip people up here:

  • The page has to be served over HTTPS or from localhost.
  • The container needs a height that does not come from its own content. With height: auto, or a flex item without min-height: 0, the viewer has nothing to size against; it warns in the console and guesses, so fix the layout.
  • With Vite, add envPrefix: ['VITE_', 'KERNSTRA_'] so browser code can read the key, and set build.target to es2022 or later.

3. Edit the text

Nothing more is needed for the toolbar tool. Your users pick Edit text, double-click a block and type. The block is redrawn on every keystroke as it will be written to the file, in the font the document already uses. They can change the size, weight, italics and color. They can drag the block elsewhere on the page, or pull one of its edges, and the lines rewrap to the new width. If they type a character the embedded font subset does not have, it is taken from a matching bundled face. The whole editing session is one undo step.

4. The same edit from code

Sometimes no person is involved: a price changes, a name gets corrected, a template gets filled in. The tool can be driven from code:

await viewer.activateTool('editText');

const editText = viewer.tools.editText;
const blocks = await editText.listBlocks(0); // page index, zero-based

const total = blocks.find((b) => b.text.startsWith('Total:'));
if (total) {
  await editText.setText(total.id, 'Total: $1,299.00');
  await editText.commit();
}

listBlocks returns each block's text, bounds, font family, size, weight and color. Text set this way goes down the same path as typing, so font handling, reflow and undo behave the same.

Three things to know before you copy it:

  • It needs a key from a paying account. Reading and retyping a block's text from code is switched off on free development keys: listBlocks returns the blocks with empty text, so the find above matches nothing. The toolbar tool is not affected.
  • activateTool is a toggle. Calling it while Edit text is already open puts the tool away.
  • commit() writes the change and leaves the tool. Before the next round of edits, activate the tool and list the blocks again; block ids from before a commit are stale.

5. Save the result

The toolbar's download button covers the common case. To send the edited file somewhere yourself, ask the viewer for an exporter:

// As a Blob, for your own upload
const blob = await viewer.createExporter().getBlob();

// Or straight to the user's disk
await viewer.createExporter().download('contract-edited.pdf');

Open the saved file in any PDF reader and search for the old words. They are gone.

React, Vue, Angular and the rest

The calls are the same in every framework: initialize and mount in browser-only code (useEffect, onMounted, afterNextRender), then destroy the viewer and close the document on unmount. The framework integrations guide has a complete component for React, Vue, Angular, Svelte, Next.js, Nuxt and SvelteKit, including the cleanup that React's StrictMode needs, and there is a full React example on GitHub.

Where the file goes

The document stays in the browser. Opening, rendering, editing and saving happen on the user's device; it is never uploaded to us, and there is no server component for you to run.

The SDK does talk to us for two things, and neither carries document content:

  • A license status check on each page load. It sends the key, a random value, the time, a pseudonymous browser identifier and a few facts about the SDK itself.
  • Downloads of the engine, the text tools and fonts. These are fetched once per browser and cached. The requests send no data, though a request for a substitute font does show which font a document needed.

For networks with no outbound internet, an offline license contacts us for nothing.

Limits

  • It is a commercial product, not open source. Development keys are free and watermarked. Production plans start at $149 a month for an internal or back-office app, with every tool included; public-facing apps are priced by quote.
  • If you only need to display PDFs, use PDF.js. It is free, well maintained, and the right default for viewing, searching and printing. A paid SDK is the wrong purchase for that job.
  • Mixed-direction lines are not there yet. Arabic, Hebrew and Indic scripts are shaped correctly, but a single line that mixes right-to-left and left-to-right text is not yet laid out in both directions.
  • A PDF with no text in it has no text to edit. A scanned page is a picture of words. You can still mark it up and sign it, but there are no text objects to change.

Questions people ask

Can PDF.js edit the text in a PDF?

No. PDF.js renders PDFs, and its viewer can add annotations and fill forms, but it leaves the page's existing text as it is.

Can pdf-lib edit existing text?

No. It can draw new text and fill form fields, which is why tutorials cover the old text with a rectangle.

Is there a free, open-source way to edit PDF text in the browser?

Not that we know of for real text editing. PDF.js and pdf-lib together give you viewing, annotations, form filling and the white box workaround for free. Changing the text itself is where the commercial SDKs and server-side tools come in.

Does the edited PDF keep its original fonts?

With Kernstra, yes. A character the embedded font lacks comes from a matching bundled face.

Is the PDF uploaded to a server?

No. The document's bytes, text and file name never leave the user's device. The SDK's own requests are a license check and downloads of its engine and fonts.

Does it work on scanned PDFs?

A scan is an image, so it has no text to edit. Annotating and signing it work as on any page.

Try it on your own file

The fastest way to judge any of this is with a document you know well. Open one of your own PDFs in the Kernstra playground, double-click a paragraph and change it. Then save the file and search it for the old words.

When you want it in your app, the docs cover every option and the full API, including viewer.tools.editText.

About the author

  • Kernstra makes a JavaScript PDF viewer and editor SDK for web apps. View, edit, annotate, fill, sign and save PDFs entirely in the browser, with true text editing in the document's own fonts. We write about PDFs on the web and what we learn building the SDK. kernstra.com

No comments yet. Be the first to comment.