< iOS samples

StamperTest - Swift

The sample shows how to use 'pdftron.PDF.Stamper' utility class to stamp PDF pages with text, images, or with other PDF pages. ElementBuilder and ElementWriter should be used for more complex PDF stamping operations.

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

import PDFNet
import Foundation

//---------------------------------------------------------------------------------------
// The following sample shows how to add new content (or watermark) PDF pages
// using 'pdftron.PDF.Stamper' utility class.
//
// Stamper can be used to PDF pages with text, images, or with other PDF content
// in only a few lines of code. Although Stamper is very simple to use compared
// to ElementBuilder/ElementWriter it is not as powerful or flexible. In case you
// need full control over PDF creation use ElementBuilder/ElementWriter to add
// new content to existing PDF pages as shown in the ElementBuilder sample project.
//---------------------------------------------------------------------------------------
func runStamperTest() -> Int {
    return autoreleasepool {
        var ret = 0
        
        
        
        //--------------------------------------------------------------------------------
        // Example 1) Add text stamp to all pages, then remove text stamp from odd pages.
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                doc.initSecurityHandler()
                
                let s: PTStamper = PTStamper(size_type: e_ptrelative_scale, a: 0.5, b: 0.5)
                s.setAlignment(e_pthorizontal_center, vertical_alignment: e_ptvertical_center)
                let red = PTColorPt(x: 1, y: 0, z: 0, w: 0)
                // set text color to red
                s.setFontColor(red)
                let set = PTPageSet(range_start: 1, range_end: doc.getPageCount(), filter: e_ptall)
                s.stampText(doc, src_txt: "If you are reading this\nthis is an even page\n", dest_pages: set)
                //delete all text stamps in even pages
                let set2 = PTPageSet(range_start: 1, range_end: doc.getPageCount(), filter: e_ptodd)
                PTStamper.deleteStamps(doc, page_set: set2)
                
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter.ex1.pdf").path, flags: e_ptlinearized.rawValue)
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        //--------------------------------------------------------------------------------
        // Example 2) Add Image stamp to first 2 pages.
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                doc.initSecurityHandler()
                
                let s: PTStamper = PTStamper(size_type: e_ptrelative_scale, a: 0.05, b: 0.05)
                let img = PTImage.create(doc.getSDFDoc(), filename: Bundle.main.path(forResource: "peppers", ofType: "jpg"))
                s.setSize(e_ptrelative_scale, a: 0.5, b: 0.5)
                //set position of the image to the center, left of PDF pages
                s.setAlignment(e_pthorizontal_left, vertical_alignment: e_ptvertical_center)
                let pt = PTColorPt(x: 0, y: 0, z: 0, w: 0)
                s.setFontColor(pt)
                s.setRotation(180)
                s.setAsBackground(false)
                //only stamp first 2 pages
                let ps = PTPageSet(range_start: 1, range_end: 2, filter: e_ptall)
                s.stampImage(doc, src_img: img, dest_pages: ps)
                
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter.ex2.pdf").path, flags: e_ptlinearized.rawValue)
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        //--------------------------------------------------------------------------------
        // Example 3) Add Page stamp to all pages.
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                doc.initSecurityHandler()
                
                let fish_doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "fish", ofType: "pdf"))
                fish_doc.initSecurityHandler()
                
                let s: PTStamper = PTStamper(size_type: e_ptrelative_scale, a: 0.5, b: 0.5)
                let src_page: PTPage = fish_doc.getPage(1)
                let page_one_crop: PTPDFRect = src_page.getCropBox()
                // set size of the image to 10% of the original while keep the old aspect ratio
                s.setSize(e_ptabsolute_size, a: page_one_crop.width() * 0.1, b: -1)
                s.setOpacity(0.4)
                s.setRotation(-67)
                //put the image at the bottom right hand corner
                s.setAlignment(e_pthorizontal_right, vertical_alignment: e_ptvertical_bottom)
                let ps = PTPageSet(range_start: 2, range_end: doc.getPageCount(), filter: e_ptall)
                s.stampPage(doc, src_page: src_page, dest_pages: ps)
                
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter.ex3.pdf").path, flags: e_ptlinearized.rawValue)
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        //--------------------------------------------------------------------------------
        // Example 4) Add Image stamp to first 20 odd pages.
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                doc.initSecurityHandler()
                
                let s: PTStamper = PTStamper(size_type: e_ptabsolute_size, a: 20, b: 20)
                s.setOpacity(1)
                s.setRotation(45)
                s.setAsBackground(true)
                s.setPosition(30, vertical_distance: 40, use_percentage: false)
                let img = PTImage.create(doc.getSDFDoc(), filename: Bundle.main.path(forResource: "peppers", ofType: "jpg"))
                let ps = PTPageSet(range_start: 1, range_end: 20, filter: e_ptodd)
                s.stampImage(doc, src_img: img, dest_pages: ps)
                
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter.ex4.pdf").path, flags: e_ptlinearized.rawValue)
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        //--------------------------------------------------------------------------------
        // Example 5) Add text stamp to first 20 even pages
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                doc.initSecurityHandler()
                
                let s: PTStamper = PTStamper(size_type: e_ptrelative_scale, a: 0.5, b: 0.5)
                s.setPosition(0, vertical_distance: 0, use_percentage: false)
                s.setOpacity(0.7)
                s.setRotation(90)
                s.setSize(e_pts_font_size, a: 80, b: -1)
                s.setTextAlignment(e_ptalign_center)
                let ps = PTPageSet(range_start: 1, range_end: 20, filter: e_pteven)
                s.stampText(doc, src_txt: "Goodbye\nMoon", dest_pages: ps)
                
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter.ex5.pdf").path, flags: e_ptlinearized.rawValue)
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        //--------------------------------------------------------------------------------
        // Example 6) Add first page as stamp to all even pages
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                doc.initSecurityHandler()
                
                let fish_doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "fish", ofType: "pdf"))
                fish_doc.initSecurityHandler()
                
                let s: PTStamper = PTStamper(size_type: e_ptrelative_scale, a: 0.3, b: 0.3)
                s.setOpacity(1)
                s.setRotation(270)
                s.setAsBackground(true)
                s.setPosition(0.5, vertical_distance: 0.5, use_percentage: true)
                s.setAlignment(e_pthorizontal_left, vertical_alignment: e_ptvertical_bottom)
                let page_one: PTPage = fish_doc.getPage(1)
                let ps = PTPageSet(range_start: 1, range_end: doc.getPageCount(), filter: e_pteven)
                s.stampPage(doc, src_page: page_one, dest_pages: ps)
                
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter.ex6.pdf").path, flags: e_ptlinearized.rawValue)
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        //--------------------------------------------------------------------------------
        // Example 7) Add image stamp at top right corner in every pages
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                doc.initSecurityHandler()
                
                let s: PTStamper = PTStamper(size_type: e_ptrelative_scale, a: 0.1, b: 0.1)
                s.setOpacity(0.8)
                s.setRotation(135)
                s.setAsBackground(false)
                s.shows(onPrint: false)
                s.setAlignment(e_pthorizontal_left, vertical_alignment: e_ptvertical_top)
                s.setPosition(10, vertical_distance: 10, use_percentage: true)
                
                let img = PTImage.create(doc.getSDFDoc(), filename: Bundle.main.path(forResource: "peppers", ofType: "jpg"))
                let ps = PTPageSet(range_start: 1, range_end: doc.getPageCount(), filter: e_ptall)
                s.stampImage(doc, src_img: img, dest_pages: ps)
                
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter.ex7.pdf").path, flags: e_ptlinearized.rawValue)
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        //--------------------------------------------------------------------------------
        // Example 8) Add Text stamp to first 2 pages, and image stamp to first page.
        //          Because text stamp is set as background, the image is top of the text
        //          stamp. Text stamp on the first page is not visible.
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc = PTPDFDoc(filepath: Bundle.main.path(forResource: "newsletter", ofType: "pdf"))
                doc.initSecurityHandler()
                
                let s: PTStamper = PTStamper(size_type: e_ptrelative_scale, a: 0.07, b: -0.1)
                s.setAlignment(e_pthorizontal_right, vertical_alignment: e_ptvertical_bottom)
                s.setAlignment(e_pthorizontal_center, vertical_alignment: e_ptvertical_top)
                s.setFont(PTFont.create(doc.getSDFDoc(), type: e_ptcourier, embed: true))
                let red = PTColorPt(x: 1, y: 0, z: 0, w: 0)
                s.setFontColor(red) //set color to red
                s.setTextAlignment(e_ptalign_right)
                s.setAsBackground(true) //set text stamp as background
                let ps = PTPageSet(range_start: 1, range_end: 2, filter: e_ptall)
                s.stampText(doc, src_txt: "This is a title!", dest_pages: ps)
                
                let img = PTImage.create(doc.getSDFDoc(), filename: Bundle.main.path(forResource: "peppers", ofType: "jpg"))
                s.setAsBackground(false)    // set image stamp as foreground
                let first_page_ps = PTPageSet(one_page: 1)
                s.stampImage(doc, src_img: img, dest_pages: first_page_ps)
                
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("newsletter.ex8.pdf").path, flags: e_ptlinearized.rawValue)
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        
        print("Done.")
        
        return ret
    }
}