Some test text!

menu
search

Kotlin PDF editor (programmatic)

Sample Kotlin 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.

Get StartedSamplesDownload

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.
//---------------------------------------------------------------------------------------

package com.pdftron.android.pdfnetsdksamples.samples

import com.pdftron.android.pdfnetsdksamples.OutputListener
import com.pdftron.android.pdfnetsdksamples.PDFNetSample
import com.pdftron.android.pdfnetsdksamples.R
import com.pdftron.android.pdfnetsdksamples.util.Utils
import com.pdftron.common.PDFNetException
import com.pdftron.pdf.*
import com.pdftron.sdf.SDFDoc
import java.util.*

class ElementEditTest : PDFNetSample() {
    init {
        setTitle(R.string.sample_elementedit_title)
        setDescription(R.string.sample_elementedit_description)
    }

    override fun run(outputListener: OutputListener?) {
        super.run(outputListener)
        mOutputListener = outputListener
        mFileList.clear()
        printHeader(outputListener!!)

        val input_filename = "newsletter.pdf"
        val output_filename = "newsletter_edited.pdf"

        try {
            mOutputListener!!.println("Opening the input file...")
            val doc = PDFDoc(Utils.getAssetTempFile(PDFNetSample.INPUT_PATH + input_filename)!!.absolutePath)
            doc.initSecurityHandler()

            val writer = ElementWriter()
            val reader = ElementReader()
            val visited = TreeSet<Int>()

            val itr = doc.pageIterator
            while (itr.hasNext()) {
                try {
                    val page = itr.next()!!
                    visited.add(page.getSDFObj().objNum.toInt())

                    reader.begin(page)
                    writer.begin(page, ElementWriter.e_replacement, false, true, page.getResourceDict())

                    processElements(writer, reader, visited)
                    writer.end()
                    reader.end()
                } catch (e: Exception) {
                    mOutputListener!!.printError(e.stackTrace)
                }

            }

            // Save modified document
            doc.save(Utils.createExternalFile(output_filename, mFileList).absolutePath, SDFDoc.SaveMode.REMOVE_UNUSED, null)
            doc.close()
            mOutputListener!!.println("Done. Result saved in $output_filename...")
        } catch (e: Exception) {
            mOutputListener!!.printError(e.stackTrace)
        }

        for (file in mFileList) {
            addToFileList(file)
        }
        printFooter(outputListener)
    }

    companion object {

        private var mOutputListener: OutputListener? = null

        private val mFileList = ArrayList<String>()
        @Throws(PDFNetException::class)
        fun processElements(writer: ElementWriter, reader: ElementReader, visited: MutableSet<Int>) {
            var element: Element
            while (true) {
                element = reader.next()
                if (element == null) {
                    break
                }
                when (element.type) {
                    Element.e_image, Element.e_inline_image -> {
                    }
                    Element.e_path -> {
                        // Set all paths to red color.
                        val gs = element.gState
                        gs.fillColorSpace = ColorSpace.createDeviceRGB()
                        gs.fillColor = ColorPt(1.0, 0.0, 0.0)
                        writer.writeElement(element)
                    }
                    Element.e_text -> {
                        // Set all text to blue color.
                        val gs = element.gState
                        gs.fillColorSpace = ColorSpace.createDeviceRGB()
                        gs.fillColor = ColorPt(0.0, 0.0, 1.0)
                        writer.writeElement(element)
                    }
                    Element.e_form -> {
                        writer.writeElement(element) // write Form XObject reference to current stream
                        val form_obj = element.xObject
                        if (!visited.contains(form_obj.objNum.toInt()))
                        // if this XObject has not been processed
                        {
                            // recursively process the Form XObject
                            visited.add(form_obj.objNum.toInt())
                            val new_writer = ElementWriter()
                            reader.formBegin()
                            new_writer.begin(form_obj)

                            reader.clearChangeList()
                            new_writer.setDefaultGState(reader)

                            processElements(new_writer, reader, visited)
                            new_writer.end()
                            reader.end()
                        }
                    }
                    else -> writer.writeElement(element)
                }// remove all images by skipping them
            }

        }
    }

}
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