How to replace text in an existing PDF from code
Change the words already in a PDF, keeping their font, size, colour and position, from code on the web, iOS, Android and Flutter with PDF-SDK.
Replacing text in a PDF usually means one of two things: drawing new text on top of the old, or regenerating the whole file. PDF-SDK's document API does neither — it changes the text that is already there, so the result is still a real PDF whose words can be selected, searched and edited again.
This walkthrough translates every block of text on a page. The same steps fill in a template or fix a typo.
What you need
- PDF-SDK 2.4 or later, set up for your platform — see the docs.
- A license key set at launch. A trial key works.
1. Open the document
The document API works with no editor on screen: open the PDF's bytes, or a file on Android.
2. Read the page's text blocks
textBlocks(page) returns the text layers of a page, in reading order. Each one is a layer with an id that keeps
naming it while you change others, and its current text.
3. Replace each block
setText(block, text) replaces a block's text and keeps its font, size, colour and position. A paragraph re-wraps at
its own width; a single line may grow towards the page margin. With shrinkToFit, the size is lowered — to half
at most — until the new text is no taller than the old.
4. Save
save() returns the edited PDF.
All four steps together:
import { PDFDocumentEditor } from '@pdfsdk/editor';
const doc = await PDFDocumentEditor.open(bytes);
for (const block of doc.textBlocks(0)) {
const text = await translate(block.text ?? '');
doc.setText(block, text, { shrinkToFit: true });
}
const edited = doc.save();Did the text fit?
setText tells you how it went: replaced when the new text fits, or overflow when it grew past the old space (REPLACED and OVERFLOW on Android) —
then try shrinkToFit, or shorten the text.
Other scripts
Text can be replaced in any script. On iOS and Android, the system's fonts fill in letters the block's own font
lacks. On the web, pass a fontProvider when you open the document, to supply fonts for those scripts; without one,
text the fonts cannot draw is refused with an unsupportedGlyphs error rather than drawn wrong.
In the editor, too
Every call above also works on the document an editor is showing — editor.document on the web, onDocumentReady on
iOS and Android. Each change then appears at once, and the user can undo it like an edit by hand.
Next: every method of the document API is in the API reference for web, iOS, Android and Flutter. Or see Edit PDF text for what users can do in the editor.
Try it in your app
A free trial unlocks every feature on every platform, in any app.