Replacing text & images in PDFs using Apryse's Web SDK

To find text or images and replace it in a PDF.

1WebViewer({
2 fullAPI: true,
3 // other constructor options
4}, viewerElement).then(instance => {
5 const { documentViewer, PDFNet } = instance.Core;
6
7 document.getElementById('myBtn').addEventListener('click', async () => {
8 await PDFNet.initialize();
9 const doc = await documentViewer.getDocument().getPDFDoc();
10
11 // Run PDFNet methods with memory management
12 await PDFNet.runWithCleanup(async () => {
13
14 // lock the document before a write operation
15 // runWithCleanup will auto unlock when complete
16 doc.lock();
17
18 const replacer = await PDFNet.ContentReplacer.create();
19 const page = await doc.getPage(1);
20
21 // replace an image on the page
22 const target_region = await page.getMediaBox();
23 const img = await PDFNet.Image.createFromURL(doc, imagename);
24 await replacer.addImage(target_region, await img.getSDFObj());
25
26 // replace a text placeholder
27 await replacer.addString('NAME', 'John Smith');
28
29 // replace text in a given region
30 const text = "hello world";
31 await replacer.addText(target_region, text);
32 await replacer.process(page);
33 });
34
35 // clear the cache (rendered) data with the newly updated document
36 documentViewer.refreshAll();
37
38 // Update viewer to render with the new document
39 documentViewer.updateView();
40
41 // Refresh searchable and selectable text data with the new document
42 documentViewer.getDocument().refreshTextData();
43 });
44})

Replace PDF text or images
Full code sample which shows how to use pdftron.PDF.ContentReplacer to search and replace text strings and images in existing PDF (e.g. business cards and other PDF templates).

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales