Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.7.0+

Watermark Only Some of a PDF's Pages

See more PDF Watermark Examples

Demonstrates choosing the pages to stamp. "pages" takes all (the default), first, last, odd, even, or a list of 1-based pages and ranges such as 1,3,5-9,12- where a trailing dash means "to the end". "excludePages" takes the same syntax and is applied afterwards, which is how you say "every page except the cover". The result reports the pages the watermark actually landed on.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  This example requires the Chilkat API to have been previously unlocked.
    //  See Global Unlock Sample for sample code.

    //  The PDF used in this example is available at four_pages.pdf

    let pdf = CkoPdf()!
    success = pdf.loadFile(filePath: "qa_data/pdf/four_pages.pdf")
    if success == false {
        print("\(pdf.lastErrorText!)")
        return
    }

    print("pages in the document: \(pdf.numPages.intValue)")

    let json = CkoJsonObject()!
    let jsonOut = CkoJsonObject()!
    json.updateString(jsonPath: "type", value: "text")
    json.updateString(jsonPath: "text", value: "INTERNAL")
    json.updateString(jsonPath: "id", value: "internal")

    //  Every page except the first.
    json.updateString(jsonPath: "pages", value: "all")
    json.updateString(jsonPath: "excludePages", value: "1")
    success = pdf.watermark(op: "add", jsonIn: json, jsonOut: jsonOut)
    if success == false {
        print("\(pdf.lastErrorText!)")
        return
    }

    print("every page but the cover: \(jsonOut.string(of: "pages")!)")

    //  A list of pages and ranges, on a second copy of the document.
    let pdf2 = CkoPdf()!
    success = pdf2.loadFile(filePath: "qa_data/pdf/four_pages.pdf")
    if success == false {
        print("\(pdf2.lastErrorText!)")
        return
    }

    let json2 = CkoJsonObject()!
    json2.updateString(jsonPath: "type", value: "text")
    json2.updateString(jsonPath: "text", value: "APPENDIX")
    json2.updateString(jsonPath: "id", value: "appendix")
    json2.updateString(jsonPath: "pages", value: "2,4-")
    success = pdf2.watermark(op: "add", jsonIn: json2, jsonOut: jsonOut)
    if success == false {
        print("\(pdf2.lastErrorText!)")
        return
    }

    print("page 2 and 4 onwards: \(jsonOut.string(of: "pages")!)")

    success = pdf.writeFile(path: "qa_output/four_pages_internal.pdf")
    if success == false {
        print("\(pdf.lastErrorText!)")
        return
    }

    //  Sample output:

    //  pages in the document: 4
    //  every page but the cover: 2-4
    //  page 2 and 4 onwards: 2,4

}