Sample code for 30+ languages & platforms
Lua 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 Lua Downloads

Lua
local chilkat = require("chilkat")

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

local pdf = chilkat.Pdf.new()
local success = pdf:load_file("qa_data/pdf/four_pages.pdf")
if not success then
    print(pdf.last_error_text)
    return
end

print("pages in the document: " .. pdf.num_pages)

local json = chilkat.JsonObject.new()
local jsonOut = chilkat.JsonObject.new()
json:update_string("type", "text")
json:update_string("text", "INTERNAL")
json:update_string("id", "internal")

-- Every page except the first.
json:update_string("pages", "all")
json:update_string("excludePages", "1")
success = pdf:watermark("add", json, jsonOut)
if not success then
    print(pdf.last_error_text)
    return
end

print("every page but the cover: " .. jsonOut:string_of("pages"))

-- A list of pages and ranges, on a second copy of the document.
local pdf2 = chilkat.Pdf.new()
success = pdf2:load_file("qa_data/pdf/four_pages.pdf")
if not success then
    print(pdf2.last_error_text)
    return
end

local json2 = chilkat.JsonObject.new()
json2:update_string("type", "text")
json2:update_string("text", "APPENDIX")
json2:update_string("id", "appendix")
json2:update_string("pages", "2,4-")
success = pdf2:watermark("add", json2, jsonOut)
if not success then
    print(pdf2.last_error_text)
    return
end

print("page 2 and 4 onwards: " .. jsonOut:string_of("pages"))

success = pdf:write_file("qa_output/four_pages_internal.pdf")
if not success then
    print(pdf.last_error_text)
    return
end

-- Sample output:

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