Some test text!

menu
search
chevron_right iOS samples

Swift PDF editor (programmatic)

Sample Swift code for using PDFTron SDK to programmatically edit an existing PDF document's page display list and the graphics state attributes on existing elements. In particular, this sample strips all images from the page and changes the text color to blue. You can also build a GUI with interactive PDF editor widgets. Some of PDFTron SDK's other functions for programmatically editing PDFs include the Cos/SDF low-level API, page manipulation, and more. Learn more about our PDF Editing & Manipulation Library.

To run this sample, get started with a free trial of PDFTron 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 shows how to edit the page display list and how to modify graphics state
// attributes on existing Elements. In particular the sample program strips all images from
// the page, changes path fill color to red, and changes text color to blue.
//---------------------------------------------------------------------------------------

private func ProcessElementEditTestElements(reader: PTElementReader, writer: PTElementWriter, visited: NSMutableSet) {
    while let element = reader.next() {
        switch element.getType() {
        case e_ptimage, e_ptinline_image:
            // remove all images by skipping them
            break
        case e_ptpath:
            // Set all paths to red color.
            let gs: PTGState = element.getGState()
            gs.setFill(PTColorSpace.createDeviceRGB())
            let cp = PTColorPt(x: 1, y: 0, z: 0, w: 0)
            gs.setFillColor(with: cp)
            writer.write(element)
        case e_pttext_obj:
            // Set all text to blue color.
            let gs: PTGState = element.getGState()
            gs.setFill(PTColorSpace.createDeviceRGB())
            let cp = PTColorPt(x: 0, y: 0, z: 1, w: 0)
            gs.setFillColor(with: cp)
            writer.write(element)
        case e_ptform:
            writer.write(element)   // write Form XObject reference to current stream
            
            let form_obj: PTObj = element.getXObject()
            
            if !visited.contains(form_obj.getNum()) {
                // recursively process the Form XObject
                visited.add(form_obj.getNum())
                let new_writer: PTElementWriter = PTElementWriter()
                reader.formBegin()
                new_writer.writerBegin(withSDFObj: form_obj, compress: true, resources: nil)
                ProcessElementEditTestElements(reader: reader, writer: new_writer, visited: visited)
                reader.end()
                new_writer.end()
            }
        default:
            writer.write(element)
        }
    }
}

func runElementEditTest() -> Int {
    return autoreleasepool {
        var ret: Int = 0
        

        do {
            try PTPDFNet.catchException {
                print("Opening the input file...")
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                doc.initSecurityHandler()
                
                let writer: PTElementWriter = PTElementWriter()
                let reader: PTElementReader = PTElementReader()
                let visited = NSMutableSet()
                
                let itr: PTPageIterator = doc.getPageIterator(1)
                while itr.hasNext() {
                    let page: PTPage = itr.current()
                    visited.add(page.getSDFObj().getNum())
                    
                    reader.readerBegin(with: page, ocg_context: nil)
                    writer.begin(page, placement: e_ptreplacement, page_coord_sys: false, compress: true)
                    
                    ProcessElementEditTestElements(reader: reader, writer: writer, visited: visited)
                    
                    writer.end()
                    reader.end()
                    
                    itr.next()
                }
                
                // Save modified document
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter_edited.pdf").path, flags: e_ptremove_unused.rawValue)
                print("Done. Result saved in newsletter_edited.pdf...")
            }
        } catch let e as NSError {
            print("Caught PDFNet exception: \(e)")
            ret = 1
        }
        
        return ret
    }
}
close

Free Trial

Get unlimited trial usage of PDFTron SDK to bring accurate, reliable, and fast document processing capabilities to any application or workflow.

Select a platform to get started with your free trial.

Unlimited usage. No email address required.

PDFTron Receives USD$71 Million Growth Investment Led By Silversmith Capital Partners

Learn more
close