Some test text!

Search
Hamburger Icon

Search & replace PDF text or images in Swift

More languages

More languages
JavaScript
Java (Android)
C++
C#
C# (.NET Core)
Go
Java
Kotlin
Obj-C
JS (Node.js)
PHP
Python
Ruby
Swift
C# (UWP)
VB
C# (Xamarin)

Sample Swift code to use PDFTron SDK for searching and replacing text strings and images inside existing PDF files (e.g. business cards and other PDF templates). Unlike PDF forms, the ContentReplacer works on actual PDF content and is not limited to static rectangular annotation regions. Learn more about our Swift PDF Library and PDF Editing & Manipulation Library.

Get Started Samples Download

To run this sample, get started with a free trial of Apryse SDK.

//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import PDFNet
import Foundation

//-----------------------------------------------------------------------------------------
// The sample code illustrates how to use the ContentReplacer class to make using
// 'template' pdf documents easier.
//-----------------------------------------------------------------------------------------

func runContentReplacerTest() -> Int {
    return autoreleasepool {
        let input_path: String = (Bundle.main.resourcePath)! + ("/")
        let output_path: String = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("").path
        
        var ret: Int = 0
        
        
        // The following example illustrates how to replace an image in a certain region,
        // and how to change template text.
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: input_path + ("BusinessCardTemplate.pdf"))
                doc.initSecurityHandler()
                
                // first, replace the image on the first page
                let replacer: PTContentReplacer = PTContentReplacer()
                let page: PTPage = doc.getPage(1)
                let img: PTImage = PTImage.create(doc.getSDFDoc(), filename: input_path + ("peppers.jpg"))
                replacer.addImage(page.getMediaBox(), replacement_image: img.getSDFObj())
                // next, replace the text place holders on the second page
                replacer.add("NAME", replacement_text: "John Smith")
                replacer.add("QUALIFICATIONS", replacement_text: "Philosophy Doctor")
                replacer.add("JOB_TITLE", replacement_text: "Software Developer")
                replacer.add("ADDRESS_LINE1", replacement_text: "#100 123 Software Rd")
                replacer.add("ADDRESS_LINE2", replacement_text: "Vancouver, BC")
                replacer.add("PHONE_OFFICE", replacement_text: "604-730-8989")
                replacer.add("PHONE_MOBILE", replacement_text: "604-765-4321")
                replacer.add("EMAIL", replacement_text: "info@pdftron.com")
                replacer.add("WEBSITE_URL", replacement_text: "http://www.pdftron.com")
                // finally, apply
                replacer.process(page)
                
                doc.save(toFile: URL(fileURLWithPath: output_path).appendingPathComponent("BusinessCard.pdf").path, flags: 0)
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        // The following example illustrates how to replace text in a given region
        do {
            try PTPDFNet.catchException {
                // Open the document that was saved in the previous code sample
                let doc: PTPDFDoc = PTPDFDoc(filepath: input_path + ("newsletter.pdf"))
                doc.initSecurityHandler()
                
                let replacer: PTContentReplacer = PTContentReplacer()
                let page: PTPage = doc.getPage(1)
                let target_region: PTPDFRect = page.getMediaBox()
                replacer.addText(target_region, replacement_text: "hello hello hello hello hello hello hello hello hello hello")
                replacer.process(page)
                
                doc.save(toFile: URL(fileURLWithPath: output_path).appendingPathComponent("ContentReplaced.pdf").path, flags: 0)
                
                print("Done.")
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        return ret
    }
}