Some test text!
Web / Guides / Replace content
Make sure you have Full API enabled in WebViewer.
To find text or images and replace it in a PDF.
WebViewer({
fullAPI: true,
// other constructor options
}, viewerElement).then(instance => {
const { documentViewer, PDFNet } = instance.Core;
document.getElementById('myBtn').addEventListener('click', async () => {
await PDFNet.initialize();
const doc = await documentViewer.getDocument().getPDFDoc();
// Run PDFNet methods with memory management
await PDFNet.runWithCleanup(async () => {
// lock the document before a write operation
// runWithCleanup will auto unlock when complete
doc.lock();
const replacer = await PDFNet.ContentReplacer.create();
const page = await doc.getPage(1);
// replace an image on the page
const target_region = await page.getMediaBox();
const img = await PDFNet.Image.createFromURL(doc, imagename);
await replacer.addImage(target_region, await img.getSDFObj());
// replace a text placeholder
await replacer.addString('NAME', 'John Smith');
// replace text in a given region
const text = "hello world";
await replacer.addText(target_region, text);
await replacer.process(page);
});
// clear the cache (rendered) data with the newly updated document
documentViewer.refreshAll();
// Update viewer to render with the new document
documentViewer.updateView();
// Refresh searchable and selectable text data with the new document
documentViewer.getDocument().refreshTextData();
});
})
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).
Trial setup questions? Ask experts on Discord
Need other help? Contact Support
Pricing or product questions? Contact Sales